code
stringlengths 82
53.2k
| code_codestyle
int64 0
721
| style_context
stringlengths 91
41.9k
| style_context_codestyle
int64 0
699
| label
int64 0
1
|
---|---|---|---|---|
import unittest
import numpy as np
from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DonutImageProcessor
class __magic_name__ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : int , _lowercase : List[str] , _lowercase : List[Any]=7 , _lowercase : Union[str, Any]=3 , _lowercase : str=18 , _lowercase : str=30 , _lowercase : Tuple=400 , _lowercase : List[Any]=True , _lowercase : Optional[Any]=None , _lowercase : Optional[Any]=True , _lowercase : Optional[int]=False , _lowercase : Any=True , _lowercase : List[str]=True , _lowercase : Optional[int]=[0.5, 0.5, 0.5] , _lowercase : Tuple=[0.5, 0.5, 0.5] , ):
"""simple docstring"""
_UpperCamelCase: Dict = parent
_UpperCamelCase: List[str] = batch_size
_UpperCamelCase: Dict = num_channels
_UpperCamelCase: List[str] = image_size
_UpperCamelCase: Optional[int] = min_resolution
_UpperCamelCase: Tuple = max_resolution
_UpperCamelCase: str = do_resize
_UpperCamelCase: List[str] = size if size is not None else {'''height''': 18, '''width''': 20}
_UpperCamelCase: Tuple = do_thumbnail
_UpperCamelCase: Optional[Any] = do_align_axis
_UpperCamelCase: Optional[Any] = do_pad
_UpperCamelCase: Tuple = do_normalize
_UpperCamelCase: Tuple = image_mean
_UpperCamelCase: Tuple = image_std
def lowerCAmelCase ( self : Optional[int] ):
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size": self.size,
"do_thumbnail": self.do_thumbnail,
"do_align_long_axis": self.do_align_axis,
"do_pad": self.do_pad,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
}
@require_torch
@require_vision
class __magic_name__ ( __lowercase , unittest.TestCase ):
"""simple docstring"""
lowerCAmelCase : Tuple = DonutImageProcessor if is_vision_available() else None
def lowerCAmelCase ( self : str ):
"""simple docstring"""
_UpperCamelCase: List[str] = DonutImageProcessingTester(self )
@property
def lowerCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase ( self : str ):
"""simple docstring"""
_UpperCamelCase: Dict = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''do_resize''' ) )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''size''' ) )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''do_thumbnail''' ) )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''do_align_long_axis''' ) )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''do_pad''' ) )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''do_normalize''' ) )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''image_mean''' ) )
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''image_std''' ) )
def lowerCAmelCase ( self : str ):
"""simple docstring"""
_UpperCamelCase: Any = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 20} )
_UpperCamelCase: List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} )
# Previous config had dimensions in (width, height) order
_UpperCamelCase: int = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) )
self.assertEqual(image_processor.size , {'''height''': 84, '''width''': 42} )
def lowerCAmelCase ( self : List[str] ):
"""simple docstring"""
pass
@is_flaky()
def lowerCAmelCase ( self : Dict ):
"""simple docstring"""
_UpperCamelCase: Union[str, Any] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_UpperCamelCase: List[str] = 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
_UpperCamelCase: str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
# Test batched
_UpperCamelCase: str = 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,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
@is_flaky()
def lowerCAmelCase ( self : List[str] ):
"""simple docstring"""
_UpperCamelCase: Tuple = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_UpperCamelCase: List[Any] = 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
_UpperCamelCase: Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
# Test batched
_UpperCamelCase: Optional[Any] = 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,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
@is_flaky()
def lowerCAmelCase ( self : str ):
"""simple docstring"""
_UpperCamelCase: List[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_UpperCamelCase: Union[str, 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
_UpperCamelCase: List[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
# Test batched
_UpperCamelCase: List[Any] = 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,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , ) | 271 |
'''simple docstring'''
from __future__ import annotations
from functools import lru_cache
from math import ceil
_a : Optional[Any] = 100
_a : Dict = set(range(3, NUM_PRIMES, 2))
primes.add(2)
_a : int
for prime in range(3, ceil(NUM_PRIMES**0.5), 2):
if prime not in primes:
continue
primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime)))
@lru_cache(maxsize=1_0_0 )
def _a (lowercase__ : int ) -> set[int]:
"""simple docstring"""
if number_to_partition < 0:
return set()
elif number_to_partition == 0:
return {1}
__snake_case = set()
__snake_case = 42
__snake_case = 42
for prime in primes:
if prime > number_to_partition:
continue
for sub in partition(number_to_partition - prime ):
ret.add(sub * prime )
return ret
def _a (lowercase__ : int = 5_0_0_0 ) -> int | None:
"""simple docstring"""
for number_to_partition in range(1 , lowercase__ ):
if len(partition(lowercase__ ) ) > number_unique_partitions:
return number_to_partition
return None
if __name__ == "__main__":
print(f'''{solution() = }''')
| 56 | 0 |
import math
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import SchedulerMixin, SchedulerOutput
class SCREAMING_SNAKE_CASE ( snake_case , snake_case ):
"""simple docstring"""
A_ = 1
@register_to_config
def __init__( self: Any , __A: int = 10_00 , __A: Optional[Union[np.ndarray, List[float]]] = None ) -> List[str]:
# set `betas`, `alphas`, `timesteps`
self.set_timesteps(__A )
# standard deviation of the initial noise distribution
_A = 1.0
# For now we only support F-PNDM, i.e. the runge-kutta method
# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
# mainly at formula (9), (12), (13) and the Algorithm 2.
_A = 4
# running values
_A = []
def __A ( self: str , __A: int , __A: Union[str, torch.device] = None ) -> int:
_A = num_inference_steps
_A = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1]
_A = torch.cat([steps, torch.tensor([0.0] )] )
if self.config.trained_betas is not None:
_A = torch.tensor(self.config.trained_betas , dtype=torch.floataa )
else:
_A = torch.sin(steps * math.pi / 2 ) ** 2
_A = (1.0 - self.betas**2) ** 0.5
_A = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1]
_A = timesteps.to(__A )
_A = []
def __A ( self: Tuple , __A: torch.FloatTensor , __A: int , __A: torch.FloatTensor , __A: bool = True , ) -> Union[SchedulerOutput, Tuple]:
if self.num_inference_steps is None:
raise ValueError(
'''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' )
_A = (self.timesteps == timestep).nonzero().item()
_A = timestep_index + 1
_A = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
self.ets.append(__A )
if len(self.ets ) == 1:
_A = self.ets[-1]
elif len(self.ets ) == 2:
_A = (3 * self.ets[-1] - self.ets[-2]) / 2
elif len(self.ets ) == 3:
_A = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
else:
_A = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])
_A = self._get_prev_sample(__A , __A , __A , __A )
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=__A )
def __A ( self: Optional[int] , __A: torch.FloatTensor , *__A: Tuple , **__A: List[Any] ) -> torch.FloatTensor:
return sample
def __A ( self: List[str] , __A: Optional[Any] , __A: Optional[Any] , __A: Any , __A: List[Any] ) -> List[Any]:
_A = self.alphas[timestep_index]
_A = self.betas[timestep_index]
_A = self.alphas[prev_timestep_index]
_A = self.betas[prev_timestep_index]
_A = (sample - sigma * ets) / max(__A , 1e-8 )
_A = next_alpha * pred + ets * next_sigma
return prev_sample
def __len__( self: List[str] ) -> Dict:
return self.config.num_train_timesteps
| 62 |
__A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []}
__A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]}
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = True
_A = []
for neighbour in graph[vert]:
if not visited[neighbour]:
order += topology_sort(_lowercase , _lowercase , _lowercase )
order.append(_lowercase )
return order
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = True
_A = [vert]
for neighbour in reversed_graph[vert]:
if not visited[neighbour]:
component += find_components(_lowercase , _lowercase , _lowercase )
return component
def __A ( _lowercase ):
'''simple docstring'''
_A = len(_lowercase ) * [False]
_A = {vert: [] for vert in range(len(_lowercase ) )}
for vert, neighbours in graph.items():
for neighbour in neighbours:
reversed_graph[neighbour].append(_lowercase )
_A = []
for i, was_visited in enumerate(_lowercase ):
if not was_visited:
order += topology_sort(_lowercase , _lowercase , _lowercase )
_A = []
_A = len(_lowercase ) * [False]
for i in range(len(_lowercase ) ):
_A = order[len(_lowercase ) - i - 1]
if not visited[vert]:
_A = find_components(_lowercase , _lowercase , _lowercase )
components_list.append(_lowercase )
return components_list
| 62 | 1 |
'''simple docstring'''
import contextlib
import copy
import random
from typing import Any, Dict, Iterable, Optional, Union
import numpy as np
import torch
from .utils import deprecate, is_transformers_available
if is_transformers_available():
import transformers
def lowerCAmelCase (__A):
"""simple docstring"""
random.seed(__A)
np.random.seed(__A)
torch.manual_seed(__A)
torch.cuda.manual_seed_all(__A)
# ^^ safe to call this function even if cuda is not available
class __A :
'''simple docstring'''
def __init__(self , A , A = 0.9999 , A = 0.0 , A = 0 , A = False , A = 1.0 , A = 2 / 3 , A = None , A = None , **A , ) -> List[str]:
"""simple docstring"""
if isinstance(A , torch.nn.Module ):
_a = (
'''Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. '''
'''Please pass the parameters of the module instead.'''
)
deprecate(
'''passing a `torch.nn.Module` to `ExponentialMovingAverage`''' , '''1.0.0''' , A , standard_warn=A , )
_a = parameters.parameters()
# set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility
_a = True
if kwargs.get('''max_value''' , A ) is not None:
_a = '''The `max_value` argument is deprecated. Please use `decay` instead.'''
deprecate('''max_value''' , '''1.0.0''' , A , standard_warn=A )
_a = kwargs['''max_value''']
if kwargs.get('''min_value''' , A ) is not None:
_a = '''The `min_value` argument is deprecated. Please use `min_decay` instead.'''
deprecate('''min_value''' , '''1.0.0''' , A , standard_warn=A )
_a = kwargs['''min_value''']
_a = list(A )
_a = [p.clone().detach() for p in parameters]
if kwargs.get('''device''' , A ) is not None:
_a = '''The `device` argument is deprecated. Please use `to` instead.'''
deprecate('''device''' , '''1.0.0''' , A , standard_warn=A )
self.to(device=kwargs['''device'''] )
_a = None
_a = decay
_a = min_decay
_a = update_after_step
_a = use_ema_warmup
_a = inv_gamma
_a = power
_a = 0
_a = None # set in `step()`
_a = model_cls
_a = model_config
@classmethod
def a__ (cls , A , A ) -> "EMAModel":
"""simple docstring"""
_a , _a = model_cls.load_config(A , return_unused_kwargs=A )
_a = model_cls.from_pretrained(A )
_a = cls(model.parameters() , model_cls=A , model_config=model.config )
ema_model.load_state_dict(A )
return ema_model
def a__ (self , A ) -> Tuple:
"""simple docstring"""
if self.model_cls is None:
raise ValueError('''`save_pretrained` can only be used if `model_cls` was defined at __init__.''' )
if self.model_config is None:
raise ValueError('''`save_pretrained` can only be used if `model_config` was defined at __init__.''' )
_a = self.model_cls.from_config(self.model_config )
_a = self.state_dict()
state_dict.pop('''shadow_params''' , A )
model.register_to_config(**A )
self.copy_to(model.parameters() )
model.save_pretrained(A )
def a__ (self , A ) -> float:
"""simple docstring"""
_a = max(0 , optimization_step - self.update_after_step - 1 )
if step <= 0:
return 0.0
if self.use_ema_warmup:
_a = 1 - (1 + step / self.inv_gamma) ** -self.power
else:
_a = (1 + step) / (10 + step)
_a = min(A , self.decay )
# make sure decay is not smaller than min_decay
_a = max(A , self.min_decay )
return cur_decay_value
@torch.no_grad()
def a__ (self , A ) -> Optional[Any]:
"""simple docstring"""
if isinstance(A , torch.nn.Module ):
_a = (
'''Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. '''
'''Please pass the parameters of the module instead.'''
)
deprecate(
'''passing a `torch.nn.Module` to `ExponentialMovingAverage.step`''' , '''1.0.0''' , A , standard_warn=A , )
_a = parameters.parameters()
_a = list(A )
self.optimization_step += 1
# Compute the decay factor for the exponential moving average.
_a = self.get_decay(self.optimization_step )
_a = decay
_a = 1 - decay
_a = contextlib.nullcontext
if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
import deepspeed
for s_param, param in zip(self.shadow_params , A ):
if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
_a = deepspeed.zero.GatheredParameters(A , modifier_rank=A )
with context_manager():
if param.requires_grad:
s_param.sub_(one_minus_decay * (s_param - param) )
else:
s_param.copy_(A )
def a__ (self , A ) -> None:
"""simple docstring"""
_a = list(A )
for s_param, param in zip(self.shadow_params , A ):
param.data.copy_(s_param.to(param.device ).data )
def a__ (self , A=None , A=None ) -> None:
"""simple docstring"""
_a = [
p.to(device=A , dtype=A ) if p.is_floating_point() else p.to(device=A )
for p in self.shadow_params
]
def a__ (self ) -> dict:
"""simple docstring"""
return {
"decay": self.decay,
"min_decay": self.min_decay,
"optimization_step": self.optimization_step,
"update_after_step": self.update_after_step,
"use_ema_warmup": self.use_ema_warmup,
"inv_gamma": self.inv_gamma,
"power": self.power,
"shadow_params": self.shadow_params,
}
def a__ (self , A ) -> None:
"""simple docstring"""
_a = [param.detach().cpu().clone() for param in parameters]
def a__ (self , A ) -> None:
"""simple docstring"""
if self.temp_stored_params is None:
raise RuntimeError('''This ExponentialMovingAverage has no `store()`ed weights ''' '''to `restore()`''' )
for c_param, param in zip(self.temp_stored_params , A ):
param.data.copy_(c_param.data )
# Better memory-wise.
_a = None
def a__ (self , A ) -> None:
"""simple docstring"""
_a = copy.deepcopy(A )
_a = state_dict.get('''decay''' , self.decay )
if self.decay < 0.0 or self.decay > 1.0:
raise ValueError('''Decay must be between 0 and 1''' )
_a = state_dict.get('''min_decay''' , self.min_decay )
if not isinstance(self.min_decay , A ):
raise ValueError('''Invalid min_decay''' )
_a = state_dict.get('''optimization_step''' , self.optimization_step )
if not isinstance(self.optimization_step , A ):
raise ValueError('''Invalid optimization_step''' )
_a = state_dict.get('''update_after_step''' , self.update_after_step )
if not isinstance(self.update_after_step , A ):
raise ValueError('''Invalid update_after_step''' )
_a = state_dict.get('''use_ema_warmup''' , self.use_ema_warmup )
if not isinstance(self.use_ema_warmup , A ):
raise ValueError('''Invalid use_ema_warmup''' )
_a = state_dict.get('''inv_gamma''' , self.inv_gamma )
if not isinstance(self.inv_gamma , (float, int) ):
raise ValueError('''Invalid inv_gamma''' )
_a = state_dict.get('''power''' , self.power )
if not isinstance(self.power , (float, int) ):
raise ValueError('''Invalid power''' )
_a = state_dict.get('''shadow_params''' , A )
if shadow_params is not None:
_a = shadow_params
if not isinstance(self.shadow_params , A ):
raise ValueError('''shadow_params must be a list''' )
if not all(isinstance(A , torch.Tensor ) for p in self.shadow_params ):
raise ValueError('''shadow_params must all be Tensors''' )
| 11 | from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_torch_available,
)
a_ = {
'configuration_speecht5': [
'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP',
'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP',
'SpeechT5Config',
'SpeechT5HifiGanConfig',
],
'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'],
'processing_speecht5': ['SpeechT5Processor'],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ = ['SpeechT5Tokenizer']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ = [
'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST',
'SpeechT5ForSpeechToText',
'SpeechT5ForSpeechToSpeech',
'SpeechT5ForTextToSpeech',
'SpeechT5Model',
'SpeechT5PreTrainedModel',
'SpeechT5HifiGan',
]
if TYPE_CHECKING:
from .configuration_speechta import (
SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP,
SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP,
SpeechTaConfig,
SpeechTaHifiGanConfig,
)
from .feature_extraction_speechta import SpeechTaFeatureExtractor
from .processing_speechta import SpeechTaProcessor
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_speechta import SpeechTaTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_speechta import (
SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST,
SpeechTaForSpeechToSpeech,
SpeechTaForSpeechToText,
SpeechTaForTextToSpeech,
SpeechTaHifiGan,
SpeechTaModel,
SpeechTaPreTrainedModel,
)
else:
import sys
a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 417 | 0 |
'''simple docstring'''
def a ( UpperCamelCase_ : int ) -> int:
if n == 1 or not isinstance(UpperCamelCase_ , UpperCamelCase_ ):
return 0
elif n == 2:
return 1
else:
snake_case__ =[0, 1]
for i in range(2 , n + 1 ):
sequence.append(sequence[i - 1] + sequence[i - 2] )
return sequence[n]
def a ( UpperCamelCase_ : int ) -> int:
snake_case__ =0
snake_case__ =2
while digits < n:
index += 1
snake_case__ =len(str(fibonacci(UpperCamelCase_ ) ) )
return index
def a ( UpperCamelCase_ : int = 1000 ) -> int:
return fibonacci_digits_index(UpperCamelCase_ )
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| 581 |
'''simple docstring'''
import argparse
import math
import os
import torch
from neural_compressor.utils.pytorch import load
from PIL import Image
from transformers import CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel
def a ( ) -> Optional[int]:
snake_case__ =argparse.ArgumentParser()
parser.add_argument(
'-m' , '--pretrained_model_name_or_path' , type=UpperCamelCase_ , default=UpperCamelCase_ , required=UpperCamelCase_ , help='Path to pretrained model or model identifier from huggingface.co/models.' , )
parser.add_argument(
'-c' , '--caption' , type=UpperCamelCase_ , default='robotic cat with wings' , help='Text used to generate images.' , )
parser.add_argument(
'-n' , '--images_num' , type=UpperCamelCase_ , default=4 , help='How much images to generate.' , )
parser.add_argument(
'-s' , '--seed' , type=UpperCamelCase_ , default=42 , help='Seed for random process.' , )
parser.add_argument(
'-ci' , '--cuda_id' , type=UpperCamelCase_ , default=0 , help='cuda_id.' , )
snake_case__ =parser.parse_args()
return args
def a ( UpperCamelCase_ : Any , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Optional[Any] ) -> str:
if not len(UpperCamelCase_ ) == rows * cols:
raise ValueError('The specified number of rows and columns are not correct.' )
snake_case__ , snake_case__ =imgs[0].size
snake_case__ =Image.new('RGB' , size=(cols * w, rows * h) )
snake_case__ , snake_case__ =grid.size
for i, img in enumerate(UpperCamelCase_ ):
grid.paste(UpperCamelCase_ , box=(i % cols * w, i // cols * h) )
return grid
def a ( UpperCamelCase_ : Any , UpperCamelCase_ : str="robotic cat with wings" , UpperCamelCase_ : Union[str, Any]=7.5 , UpperCamelCase_ : Dict=50 , UpperCamelCase_ : int=1 , UpperCamelCase_ : int=42 , ) -> Dict:
snake_case__ =torch.Generator(pipeline.device ).manual_seed(UpperCamelCase_ )
snake_case__ =pipeline(
UpperCamelCase_ , guidance_scale=UpperCamelCase_ , num_inference_steps=UpperCamelCase_ , generator=UpperCamelCase_ , num_images_per_prompt=UpperCamelCase_ , ).images
snake_case__ =int(math.sqrt(UpperCamelCase_ ) )
snake_case__ =image_grid(UpperCamelCase_ , rows=_rows , cols=num_images_per_prompt // _rows )
return grid, images
SCREAMING_SNAKE_CASE__ : int = parse_args()
# Load models and create wrapper for stable diffusion
SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder='''tokenizer''')
SCREAMING_SNAKE_CASE__ : Tuple = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='''text_encoder''')
SCREAMING_SNAKE_CASE__ : Tuple = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder='''vae''')
SCREAMING_SNAKE_CASE__ : Tuple = UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='''unet''')
SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionPipeline.from_pretrained(
args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer
)
SCREAMING_SNAKE_CASE__ : List[str] = lambda images, clip_input: (images, False)
if os.path.exists(os.path.join(args.pretrained_model_name_or_path, '''best_model.pt''')):
SCREAMING_SNAKE_CASE__ : List[Any] = load(args.pretrained_model_name_or_path, model=unet)
unet.eval()
setattr(pipeline, '''unet''', unet)
else:
SCREAMING_SNAKE_CASE__ : List[Any] = unet.to(torch.device('''cuda''', args.cuda_id))
SCREAMING_SNAKE_CASE__ : List[str] = pipeline.to(unet.device)
SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ : Tuple = generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed)
grid.save(os.path.join(args.pretrained_model_name_or_path, '''{}.png'''.format('''_'''.join(args.caption.split()))))
SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(args.pretrained_model_name_or_path, '''_'''.join(args.caption.split()))
os.makedirs(dirname, exist_ok=True)
for idx, image in enumerate(images):
image.save(os.path.join(dirname, '''{}.png'''.format(idx + 1)))
| 581 | 1 |
"""simple docstring"""
import numpy as np
from cva import destroyAllWindows, imread, imshow, waitKey
class _lowerCAmelCase :
def __init__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> str:
'''simple docstring'''
if dst_width < 0 or dst_height < 0:
raise ValueError("Destination width/height should be > 0" )
snake_case : int = img
snake_case : str = img.shape[1]
snake_case : int = img.shape[0]
snake_case : Any = dst_width
snake_case : Optional[Any] = dst_height
snake_case : List[Any] = self.src_w / self.dst_w
snake_case : Tuple = self.src_h / self.dst_h
snake_case : int = (
np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 255
)
def lowerCamelCase ( self ) -> Optional[Any]:
'''simple docstring'''
for i in range(self.dst_h ):
for j in range(self.dst_w ):
snake_case : Tuple = self.img[self.get_y(__SCREAMING_SNAKE_CASE )][self.get_x(__SCREAMING_SNAKE_CASE )]
def lowerCamelCase ( self , UpperCamelCase__ ) -> Tuple:
'''simple docstring'''
return int(self.ratio_x * x )
def lowerCamelCase ( self , UpperCamelCase__ ) -> str:
'''simple docstring'''
return int(self.ratio_y * y )
if __name__ == "__main__":
__snake_case = 800, 600
__snake_case = imread("""image_data/lena.jpg""", 1)
__snake_case = NearestNeighbour(im, dst_w, dst_h)
n.process()
imshow(
F'''Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}''', n.output
)
waitKey(0)
destroyAllWindows()
| 178 |
'''simple docstring'''
from packaging import version
from .import_utils import is_accelerate_available
if is_accelerate_available():
import accelerate
def _lowerCAmelCase ( lowercase ) -> Optional[int]:
if not is_accelerate_available():
return method
__lowerCAmelCase = version.parse(accelerate.__version__ ).base_version
if version.parse(lowercase ) < version.parse("""0.17.0""" ):
return method
def wrapper(self , *lowercase , **lowercase ):
if hasattr(self , """_hf_hook""" ) and hasattr(self._hf_hook , """pre_forward""" ):
self._hf_hook.pre_forward(self )
return method(self , *lowercase , **lowercase )
return wrapper
| 689 | 0 |
'''simple docstring'''
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline
else:
from .pipeline_kandinsky import KandinskyPipeline
from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline
from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline
from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput
from .text_encoder import MultilingualCLIP | 266 |
'''simple docstring'''
import numpy as np
from cva import destroyAllWindows, imread, imshow, waitKey
class a :
"""simple docstring"""
def __init__( self : Union[str, Any] , snake_case : List[Any] , snake_case : int , snake_case : int ) -> List[Any]:
if dst_width < 0 or dst_height < 0:
raise ValueError('''Destination width/height should be > 0''' )
__UpperCAmelCase : str = img
__UpperCAmelCase : List[Any] = img.shape[1]
__UpperCAmelCase : Optional[Any] = img.shape[0]
__UpperCAmelCase : Dict = dst_width
__UpperCAmelCase : List[str] = dst_height
__UpperCAmelCase : Union[str, Any] = self.src_w / self.dst_w
__UpperCAmelCase : List[str] = self.src_h / self.dst_h
__UpperCAmelCase : Optional[int] = (
np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 255
)
def lowerCamelCase__ ( self : Any ) -> str:
for i in range(self.dst_h ):
for j in range(self.dst_w ):
__UpperCAmelCase : Any = self.img[self.get_y(snake_case )][self.get_x(snake_case )]
def lowerCamelCase__ ( self : int , snake_case : int ) -> int:
return int(self.ratio_x * x )
def lowerCamelCase__ ( self : Optional[Any] , snake_case : int ) -> int:
return int(self.ratio_y * y )
if __name__ == "__main__":
__UpperCAmelCase , __UpperCAmelCase :int = 8_0_0, 6_0_0
__UpperCAmelCase :Dict = imread("image_data/lena.jpg", 1)
__UpperCAmelCase :int = NearestNeighbour(im, dst_w, dst_h)
n.process()
imshow(
f"""Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}""", n.output
)
waitKey(0)
destroyAllWindows() | 266 | 1 |
def UpperCamelCase_( lowerCamelCase_ ) -> Tuple:
_lowercase : Tuple = 0
_lowercase : Any = len(lowerCamelCase_ )
for i in range(n - 1 ):
for j in range(i + 1 , lowerCamelCase_ ):
if arr[i] > arr[j]:
num_inversions += 1
return num_inversions
def UpperCamelCase_( lowerCamelCase_ ) -> Dict:
if len(lowerCamelCase_ ) <= 1:
return arr, 0
_lowercase : Any = len(lowerCamelCase_ ) // 2
_lowercase : List[str] = arr[0:mid]
_lowercase : Tuple = arr[mid:]
_lowercase , _lowercase : Dict = count_inversions_recursive(lowerCamelCase_ )
_lowercase , _lowercase : Optional[int] = count_inversions_recursive(lowerCamelCase_ )
_lowercase , _lowercase : List[str] = _count_cross_inversions(lowerCamelCase_ , lowerCamelCase_ )
_lowercase : List[Any] = inversion_p + inversions_q + cross_inversions
return c, num_inversions
def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Optional[Any]:
_lowercase : Any = []
_lowercase : Union[str, Any] = 0
while i < len(lowerCamelCase_ ) and j < len(lowerCamelCase_ ):
if p[i] > q[j]:
# if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P)
# These are all inversions. The claim emerges from the
# property that P is sorted.
num_inversion += len(lowerCamelCase_ ) - i
r.append(q[j] )
j += 1
else:
r.append(p[i] )
i += 1
if i < len(lowerCamelCase_ ):
r.extend(p[i:] )
else:
r.extend(q[j:] )
return r, num_inversion
def UpperCamelCase_( ) -> Optional[int]:
_lowercase : Union[str, Any] = [10, 2, 1, 5, 5, 2, 11]
# this arr has 8 inversions:
# (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2)
_lowercase : Optional[int] = count_inversions_bf(lowerCamelCase_ )
_lowercase , _lowercase : Any = count_inversions_recursive(lowerCamelCase_ )
assert num_inversions_bf == num_inversions_recursive == 8
print('number of inversions = ' , lowerCamelCase_ )
# testing an array with zero inversion (a sorted arr_1)
arr_a.sort()
_lowercase : List[str] = count_inversions_bf(lowerCamelCase_ )
_lowercase , _lowercase : List[str] = count_inversions_recursive(lowerCamelCase_ )
assert num_inversions_bf == num_inversions_recursive == 0
print('number of inversions = ' , lowerCamelCase_ )
# an empty list should also have zero inversions
_lowercase : Tuple = []
_lowercase : Tuple = count_inversions_bf(lowerCamelCase_ )
_lowercase , _lowercase : List[str] = count_inversions_recursive(lowerCamelCase_ )
assert num_inversions_bf == num_inversions_recursive == 0
print('number of inversions = ' , lowerCamelCase_ )
if __name__ == "__main__":
main()
| 89 |
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
| 112 | 0 |
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 lowerCAmelCase__ ( unittest.TestCase ):
'''simple docstring'''
def __UpperCamelCase ( self ):
'''simple docstring'''
__A =inspect.getfile(accelerate.test_utils )
__A =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
__A =test_metrics
@require_cpu
def __UpperCamelCase ( self ):
'''simple docstring'''
debug_launcher(self.test_metrics.main , num_processes=1 )
@require_cpu
def __UpperCamelCase ( self ):
'''simple docstring'''
debug_launcher(self.test_metrics.main )
@require_single_gpu
def __UpperCamelCase ( self ):
'''simple docstring'''
self.test_metrics.main()
@require_multi_gpu
def __UpperCamelCase ( self ):
'''simple docstring'''
print(f'''Found {torch.cuda.device_count()} devices.''' )
__A =['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path]
with patch_environment(omp_num_threads=1 ):
execute_subprocess_async(UpperCamelCase__ , env=os.environ.copy() )
| 711 |
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
_lowerCamelCase : str = '''src/transformers'''
# This is to make sure the transformers module imported is the one in the repo.
_lowerCamelCase : int = direct_transformers_import(TRANSFORMERS_PATH)
# Regexes that match TF/Flax/PT model names.
_lowerCamelCase : Union[str, Any] = re.compile(R'''TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''')
_lowerCamelCase : 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.
_lowerCamelCase : List[Any] = re.compile(R'''(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''')
# Fill this with tuples (pipeline_tag, model_mapping, auto_model)
_lowerCamelCase : int = [
('''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 A__ ( __A : List[str] ) ->List[str]:
__A =re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , __A )
return [m.group(0 ) for m in matches]
def A__ ( ) ->Tuple:
__A =transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
__A ={
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.
__A =collections.defaultdict(__A )
__A =collections.defaultdict(__A )
__A =collections.defaultdict(__A )
# Let's lookup through all transformers object (once) and find if models are supported by a given backend.
for attr_name in dir(__A ):
__A =None
if _re_tf_models.match(__A ) is not None:
__A =tf_models
__A =_re_tf_models.match(__A ).groups()[0]
elif _re_flax_models.match(__A ) is not None:
__A =flax_models
__A =_re_flax_models.match(__A ).groups()[0]
elif _re_pt_models.match(__A ) is not None:
__A =pt_models
__A =_re_pt_models.match(__A ).groups()[0]
if lookup_dict is not None:
while len(__A ) > 0:
if attr_name in model_prefix_to_model_type:
__A =True
break
# Try again after removing the last word in the name
__A =''''''.join(camel_case_split(__A )[:-1] )
__A =set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) )
__A =list(__A )
all_models.sort()
__A ={'''model_type''': all_models}
__A =[pt_models[t] for t in all_models]
__A =[tf_models[t] for t in all_models]
__A =[flax_models[t] for t in all_models]
# Now let's use the auto-mapping names to make sure
__A ={}
for t in all_models:
if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES:
__A ='''AutoProcessor'''
elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES:
__A ='''AutoTokenizer'''
elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES:
__A ='''AutoFeatureExtractor'''
else:
# Default to AutoTokenizer if a model has nothing, for backward compatibility.
__A ='''AutoTokenizer'''
__A =[processors[t] for t in all_models]
return pd.DataFrame(__A )
def A__ ( __A : List[Any] ) ->Union[str, Any]:
__A =[
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:
__A =[model_mapping, F'''TF_{model_mapping}''', F'''FLAX_{model_mapping}''']
__A =[auto_class, F'''TF_{auto_class}''', F'''Flax_{auto_class}''']
# Loop through all three frameworks
for module, cls, mapping in zip(__A , __A , __A ):
# The type of pipeline may not exist in this framework
if not hasattr(__A , __A ):
continue
# First extract all model_names
__A =[]
for name in getattr(__A , __A ).values():
if isinstance(__A , __A ):
model_names.append(__A )
else:
model_names.extend(list(__A ) )
# 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 A__ ( __A : int , __A : Optional[Any] ) ->Dict:
__A =get_frameworks_table()
__A =Dataset.from_pandas(__A )
__A =hf_hub_download(
'''huggingface/transformers-metadata''' , '''pipeline_tags.json''' , repo_type='''dataset''' , token=__A )
__A =Dataset.from_json(__A )
__A ={
tags_dataset[i]['''model_class''']: (tags_dataset[i]['''pipeline_tag'''], tags_dataset[i]['''auto_class'''])
for i in range(len(__A ) )
}
__A =update_pipeline_and_auto_class_table(__A )
# Sort the model classes to avoid some nondeterministic updates to create false update commits.
__A =sorted(table.keys() )
__A =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],
} )
__A =Dataset.from_pandas(__A )
with tempfile.TemporaryDirectory() as tmp_dir:
frameworks_dataset.to_json(os.path.join(__A , '''frameworks.json''' ) )
tags_dataset.to_json(os.path.join(__A , '''pipeline_tags.json''' ) )
if commit_sha is not None:
__A =(
F'''Update with commit {commit_sha}\n\nSee: '''
F'''https://github.com/huggingface/transformers/commit/{commit_sha}'''
)
else:
__A ='''Update'''
upload_folder(
repo_id='''huggingface/transformers-metadata''' , folder_path=__A , repo_type='''dataset''' , token=__A , commit_message=__A , )
def A__ ( ) ->str:
__A ={tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS}
__A =transformers_module.pipelines.SUPPORTED_TASKS
__A =[]
for key in pipeline_tasks:
if key not in in_table:
__A =pipeline_tasks[key]['''pt''']
if isinstance(__A , (list, tuple) ):
__A =model[0]
__A =model.__name__
if model not in in_table.values():
missing.append(__A )
if len(__A ) > 0:
__A =''', '''.join(__A )
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__":
_lowerCamelCase : Optional[int] = 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.''')
_lowerCamelCase : Optional[Any] = parser.parse_args()
if args.check_only:
check_pipeline_tags()
else:
update_metadata(args.token, args.commit_sha)
| 516 | 0 |
'''simple docstring'''
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import flax
import jax
import jax.numpy as jnp
from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils_flax import (
CommonSchedulerState,
FlaxKarrasDiffusionSchedulers,
FlaxSchedulerMixin,
FlaxSchedulerOutput,
add_noise_common,
get_velocity_common,
)
@flax.struct.dataclass
class lowerCAmelCase__ :
"""simple docstring"""
__UpperCamelCase = 42
# setable values
__UpperCamelCase = 42
__UpperCamelCase = 42
__UpperCamelCase = None
@classmethod
def __lowerCAmelCase ( cls : Tuple , A__ : CommonSchedulerState , A__ : jnp.ndarray , A__ : jnp.ndarray ) -> Union[str, Any]:
'''simple docstring'''
return cls(common=A__ , init_noise_sigma=A__ , timesteps=A__ )
@dataclass
class lowerCAmelCase__ ( lowerCAmelCase_ ):
"""simple docstring"""
__UpperCamelCase = 42
class lowerCAmelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ ):
"""simple docstring"""
__UpperCamelCase = [e.name for e in FlaxKarrasDiffusionSchedulers]
__UpperCamelCase = 42
@property
def __lowerCAmelCase ( self : Optional[Any] ) -> Dict:
'''simple docstring'''
return True
@register_to_config
def __init__( self : List[str] , A__ : int = 1_0_0_0 , A__ : float = 0.0_001 , A__ : float = 0.02 , A__ : str = "linear" , A__ : Optional[jnp.ndarray] = None , A__ : str = "fixed_small" , A__ : bool = True , A__ : str = "epsilon" , A__ : jnp.dtype = jnp.floataa , ) -> str:
'''simple docstring'''
a__ : List[Any] = dtype
def __lowerCAmelCase ( self : str , A__ : Optional[CommonSchedulerState] = None ) -> DDPMSchedulerState:
'''simple docstring'''
if common is None:
a__ : List[str] = CommonSchedulerState.create(self )
# standard deviation of the initial noise distribution
a__ : int = jnp.array(1.0 , dtype=self.dtype )
a__ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1]
return DDPMSchedulerState.create(
common=A__ , init_noise_sigma=A__ , timesteps=A__ , )
def __lowerCAmelCase ( self : List[str] , A__ : DDPMSchedulerState , A__ : jnp.ndarray , A__ : Optional[int] = None ) -> jnp.ndarray:
'''simple docstring'''
return sample
def __lowerCAmelCase ( self : str , A__ : DDPMSchedulerState , A__ : int , A__ : Tuple = () ) -> DDPMSchedulerState:
'''simple docstring'''
a__ : Dict = self.config.num_train_timesteps // num_inference_steps
# creates integer timesteps by multiplying by ratio
# rounding to avoid issues when num_inference_step is power of 3
a__ : Optional[int] = (jnp.arange(0 , A__ ) * step_ratio).round()[::-1]
return state.replace(
num_inference_steps=A__ , timesteps=A__ , )
def __lowerCAmelCase ( self : List[str] , A__ : DDPMSchedulerState , A__ : List[Any] , A__ : Optional[Any]=None , A__ : Any=None ) -> List[Any]:
'''simple docstring'''
a__ : str = state.common.alphas_cumprod[t]
a__ : int = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )
# For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf)
# and sample from it to get previous sample
# x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample
a__ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t]
if variance_type is None:
a__ : Union[str, Any] = self.config.variance_type
# hacks - were probably added for training stability
if variance_type == "fixed_small":
a__ : Union[str, Any] = jnp.clip(A__ , a_min=1E-20 )
# for rl-diffuser https://arxiv.org/abs/2205.09991
elif variance_type == "fixed_small_log":
a__ : Any = jnp.log(jnp.clip(A__ , a_min=1E-20 ) )
elif variance_type == "fixed_large":
a__ : Optional[Any] = state.common.betas[t]
elif variance_type == "fixed_large_log":
# Glide max_log
a__ : Optional[int] = jnp.log(state.common.betas[t] )
elif variance_type == "learned":
return predicted_variance
elif variance_type == "learned_range":
a__ : str = variance
a__ : str = state.common.betas[t]
a__ : Union[str, Any] = (predicted_variance + 1) / 2
a__ : Optional[int] = frac * max_log + (1 - frac) * min_log
return variance
def __lowerCAmelCase ( self : Optional[Any] , A__ : DDPMSchedulerState , A__ : jnp.ndarray , A__ : int , A__ : jnp.ndarray , A__ : Optional[jax.random.KeyArray] = None , A__ : bool = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]:
'''simple docstring'''
a__ : Optional[int] = timestep
if key is None:
a__ : int = jax.random.PRNGKey(0 )
if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]:
a__ , a__ : Tuple = jnp.split(A__ , sample.shape[1] , axis=1 )
else:
a__ : List[str] = None
# 1. compute alphas, betas
a__ : int = state.common.alphas_cumprod[t]
a__ : Tuple = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )
a__ : Optional[Any] = 1 - alpha_prod_t
a__ : str = 1 - alpha_prod_t_prev
# 2. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
if self.config.prediction_type == "epsilon":
a__ : Union[str, Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
elif self.config.prediction_type == "sample":
a__ : List[Any] = model_output
elif self.config.prediction_type == "v_prediction":
a__ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
else:
raise ValueError(
F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` '
''' for the FlaxDDPMScheduler.''' )
# 3. Clip "predicted x_0"
if self.config.clip_sample:
a__ : Dict = jnp.clip(A__ , -1 , 1 )
# 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
a__ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t
a__ : str = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t
# 5. Compute predicted previous sample µ_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
a__ : Any = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
# 6. Add noise
def random_variance():
a__ : Optional[int] = jax.random.split(A__ , num=1 )
a__ : Optional[int] = jax.random.normal(A__ , shape=model_output.shape , dtype=self.dtype )
return (self._get_variance(A__ , A__ , predicted_variance=A__ ) ** 0.5) * noise
a__ : Tuple = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) )
a__ : Optional[int] = pred_prev_sample + variance
if not return_dict:
return (pred_prev_sample, state)
return FlaxDDPMSchedulerOutput(prev_sample=A__ , state=A__ )
def __lowerCAmelCase ( self : List[Any] , A__ : DDPMSchedulerState , A__ : jnp.ndarray , A__ : jnp.ndarray , A__ : jnp.ndarray , ) -> jnp.ndarray:
'''simple docstring'''
return add_noise_common(state.common , A__ , A__ , A__ )
def __lowerCAmelCase ( self : Dict , A__ : DDPMSchedulerState , A__ : jnp.ndarray , A__ : jnp.ndarray , A__ : jnp.ndarray , ) -> jnp.ndarray:
'''simple docstring'''
return get_velocity_common(state.common , A__ , A__ , A__ )
def __len__( self : Dict ) -> int:
'''simple docstring'''
return self.config.num_train_timesteps
| 688 |
'''simple docstring'''
import inspect
from typing import List, Optional, Tuple, Union
import numpy as np
import PIL
import torch
import torch.utils.checkpoint
from ...models import UNetaDModel, VQModel
from ...schedulers import (
DDIMScheduler,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
)
from ...utils import PIL_INTERPOLATION, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
def __a ( lowerCAmelCase__ : Dict ):
a__ , a__ : int = image.size
a__ , a__ : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
a__ : Tuple = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] )
a__ : List[Any] = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 255.0
a__ : Any = image[None].transpose(0 , 3 , 1 , 2 )
a__ : Dict = torch.from_numpy(lowerCAmelCase__ )
return 2.0 * image - 1.0
class lowerCAmelCase__ ( lowerCAmelCase_ ):
"""simple docstring"""
def __init__( self : Optional[Any] , A__ : VQModel , A__ : UNetaDModel , A__ : Union[
DDIMScheduler,
PNDMScheduler,
LMSDiscreteScheduler,
EulerDiscreteScheduler,
EulerAncestralDiscreteScheduler,
DPMSolverMultistepScheduler,
] , ) -> str:
'''simple docstring'''
super().__init__()
self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ )
@torch.no_grad()
def __call__( self : List[str] , A__ : Union[torch.Tensor, PIL.Image.Image] = None , A__ : Optional[int] = 1 , A__ : Optional[int] = 1_0_0 , A__ : Optional[float] = 0.0 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> Union[Tuple, ImagePipelineOutput]:
'''simple docstring'''
if isinstance(A__ , PIL.Image.Image ):
a__ : List[Any] = 1
elif isinstance(A__ , torch.Tensor ):
a__ : List[str] = image.shape[0]
else:
raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(A__ )}' )
if isinstance(A__ , PIL.Image.Image ):
a__ : Union[str, Any] = preprocess(A__ )
a__ , a__ : Dict = image.shape[-2:]
# in_channels should be 6: 3 for latents, 3 for low resolution image
a__ : Optional[int] = (batch_size, self.unet.config.in_channels // 2, height, width)
a__ : Optional[int] = next(self.unet.parameters() ).dtype
a__ : List[str] = randn_tensor(A__ , generator=A__ , device=self.device , dtype=A__ )
a__ : Any = image.to(device=self.device , dtype=A__ )
# set timesteps and move to the correct device
self.scheduler.set_timesteps(A__ , device=self.device )
a__ : int = self.scheduler.timesteps
# scale the initial noise by the standard deviation required by the scheduler
a__ : str = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature.
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
a__ : Union[str, Any] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
a__ : str = {}
if accepts_eta:
a__ : Dict = eta
for t in self.progress_bar(A__ ):
# concat latents and low resolution image in the channel dimension.
a__ : str = torch.cat([latents, image] , dim=1 )
a__ : Optional[Any] = self.scheduler.scale_model_input(A__ , A__ )
# predict the noise residual
a__ : Union[str, Any] = self.unet(A__ , A__ ).sample
# compute the previous noisy sample x_t -> x_t-1
a__ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample
# decode the image latents with the VQVAE
a__ : List[Any] = self.vqvae.decode(A__ ).sample
a__ : List[Any] = torch.clamp(A__ , -1.0 , 1.0 )
a__ : Optional[Any] = image / 2 + 0.5
a__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
a__ : Union[str, Any] = self.numpy_to_pil(A__ )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=A__ )
| 688 | 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
UpperCAmelCase_ = logging.get_logger(__name__)
UpperCAmelCase_ = {
'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__ ( __lowerCamelCase ):
'''simple docstring'''
a : int = "owlvit_text_model"
def __init__( self, __magic_name__=49408, __magic_name__=512, __magic_name__=2048, __magic_name__=12, __magic_name__=8, __magic_name__=16, __magic_name__="quick_gelu", __magic_name__=1E-5, __magic_name__=0.0, __magic_name__=0.02, __magic_name__=1.0, __magic_name__=0, __magic_name__=49406, __magic_name__=49407, **__magic_name__, ) -> Tuple:
"""simple docstring"""
super().__init__(pad_token_id=__magic_name__, bos_token_id=__magic_name__, eos_token_id=__magic_name__, **__magic_name__ )
UpperCamelCase__ : Optional[int] = vocab_size
UpperCamelCase__ : List[str] = hidden_size
UpperCamelCase__ : Optional[int] = intermediate_size
UpperCamelCase__ : int = num_hidden_layers
UpperCamelCase__ : Optional[int] = num_attention_heads
UpperCamelCase__ : str = max_position_embeddings
UpperCamelCase__ : str = hidden_act
UpperCamelCase__ : int = layer_norm_eps
UpperCamelCase__ : Union[str, Any] = attention_dropout
UpperCamelCase__ : List[Any] = initializer_range
UpperCamelCase__ : Dict = initializer_factor
@classmethod
def UpperCamelCase__ ( cls, __magic_name__, **__magic_name__ ) -> "PretrainedConfig":
"""simple docstring"""
cls._set_token_in_kwargs(__magic_name__ )
UpperCamelCase__ : List[str] = cls.get_config_dict(__magic_name__, **__magic_name__ )
# get the text config dict if we are loading from OwlViTConfig
if config_dict.get('''model_type''' ) == "owlvit":
UpperCamelCase__ : Optional[int] = 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(__magic_name__, **__magic_name__ )
class lowercase__ ( __lowerCamelCase ):
'''simple docstring'''
a : Optional[int] = "owlvit_vision_model"
def __init__( self, __magic_name__=768, __magic_name__=3072, __magic_name__=12, __magic_name__=12, __magic_name__=3, __magic_name__=768, __magic_name__=32, __magic_name__="quick_gelu", __magic_name__=1E-5, __magic_name__=0.0, __magic_name__=0.02, __magic_name__=1.0, **__magic_name__, ) -> Optional[Any]:
"""simple docstring"""
super().__init__(**__magic_name__ )
UpperCamelCase__ : Union[str, Any] = hidden_size
UpperCamelCase__ : Optional[int] = intermediate_size
UpperCamelCase__ : Optional[Any] = num_hidden_layers
UpperCamelCase__ : str = num_attention_heads
UpperCamelCase__ : List[Any] = num_channels
UpperCamelCase__ : int = image_size
UpperCamelCase__ : List[str] = patch_size
UpperCamelCase__ : Optional[Any] = hidden_act
UpperCamelCase__ : List[str] = layer_norm_eps
UpperCamelCase__ : Optional[Any] = attention_dropout
UpperCamelCase__ : Any = initializer_range
UpperCamelCase__ : Tuple = initializer_factor
@classmethod
def UpperCamelCase__ ( cls, __magic_name__, **__magic_name__ ) -> "PretrainedConfig":
"""simple docstring"""
cls._set_token_in_kwargs(__magic_name__ )
UpperCamelCase__ : Union[str, Any] = cls.get_config_dict(__magic_name__, **__magic_name__ )
# get the vision config dict if we are loading from OwlViTConfig
if config_dict.get('''model_type''' ) == "owlvit":
UpperCamelCase__ : Any = 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(__magic_name__, **__magic_name__ )
class lowercase__ ( __lowerCamelCase ):
'''simple docstring'''
a : int = "owlvit"
a : Optional[Any] = True
def __init__( self, __magic_name__=None, __magic_name__=None, __magic_name__=512, __magic_name__=2.6592, __magic_name__=True, **__magic_name__, ) -> List[Any]:
"""simple docstring"""
super().__init__(**__magic_name__ )
if text_config is None:
UpperCamelCase__ : Tuple = {}
logger.info('''text_config is None. Initializing the OwlViTTextConfig with default values.''' )
if vision_config is None:
UpperCamelCase__ : Union[str, Any] = {}
logger.info('''vision_config is None. initializing the OwlViTVisionConfig with default values.''' )
UpperCamelCase__ : List[str] = OwlViTTextConfig(**__magic_name__ )
UpperCamelCase__ : Union[str, Any] = OwlViTVisionConfig(**__magic_name__ )
UpperCamelCase__ : Optional[int] = projection_dim
UpperCamelCase__ : Union[str, Any] = logit_scale_init_value
UpperCamelCase__ : int = return_dict
UpperCamelCase__ : Dict = 1.0
@classmethod
def UpperCamelCase__ ( cls, __magic_name__, **__magic_name__ ) -> "PretrainedConfig":
"""simple docstring"""
cls._set_token_in_kwargs(__magic_name__ )
UpperCamelCase__ : Optional[Any] = cls.get_config_dict(__magic_name__, **__magic_name__ )
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(__magic_name__, **__magic_name__ )
@classmethod
def UpperCamelCase__ ( cls, __magic_name__, __magic_name__, **__magic_name__ ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase__ : Optional[Any] = {}
UpperCamelCase__ : List[str] = text_config
UpperCamelCase__ : List[str] = vision_config
return cls.from_dict(__magic_name__, **__magic_name__ )
def UpperCamelCase__ ( self ) -> Dict:
"""simple docstring"""
UpperCamelCase__ : str = copy.deepcopy(self.__dict__ )
UpperCamelCase__ : Union[str, Any] = self.text_config.to_dict()
UpperCamelCase__ : List[Any] = self.vision_config.to_dict()
UpperCamelCase__ : str = self.__class__.model_type
return output
class lowercase__ ( __lowerCamelCase ):
'''simple docstring'''
@property
def UpperCamelCase__ ( self ) -> Mapping[str, Mapping[int, str]]:
"""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 UpperCamelCase__ ( self ) -> Mapping[str, Mapping[int, str]]:
"""simple docstring"""
return OrderedDict(
[
('''logits_per_image''', {0: '''batch'''}),
('''logits_per_text''', {0: '''batch'''}),
('''text_embeds''', {0: '''batch'''}),
('''image_embeds''', {0: '''batch'''}),
] )
@property
def UpperCamelCase__ ( self ) -> float:
"""simple docstring"""
return 1E-4
def UpperCamelCase__ ( self, __magic_name__, __magic_name__ = -1, __magic_name__ = -1, __magic_name__ = None, ) -> Mapping[str, Any]:
"""simple docstring"""
UpperCamelCase__ : Union[str, Any] = super().generate_dummy_inputs(
processor.tokenizer, batch_size=__magic_name__, seq_length=__magic_name__, framework=__magic_name__ )
UpperCamelCase__ : Optional[Any] = super().generate_dummy_inputs(
processor.image_processor, batch_size=__magic_name__, framework=__magic_name__ )
return {**text_input_dict, **image_input_dict}
@property
def UpperCamelCase__ ( self ) -> int:
"""simple docstring"""
return 14
| 721 |
from __future__ import annotations
def lowerCAmelCase_ ( __UpperCAmelCase: str , __UpperCAmelCase: str ) -> bool:
UpperCamelCase__ : List[str] = get_failure_array(__UpperCAmelCase )
# 2) Step through text searching for pattern
UpperCamelCase__ ,UpperCamelCase__ : Dict = 0, 0 # index into text, pattern
while i < len(__UpperCAmelCase ):
if pattern[j] == text[i]:
if j == (len(__UpperCAmelCase ) - 1):
return True
j += 1
# if this is a prefix in our pattern
# just go back far enough to continue
elif j > 0:
UpperCamelCase__ : Optional[int] = failure[j - 1]
continue
i += 1
return False
def lowerCAmelCase_ ( __UpperCAmelCase: str ) -> list[int]:
UpperCamelCase__ : Union[str, Any] = [0]
UpperCamelCase__ : Tuple = 0
UpperCamelCase__ : Tuple = 1
while j < len(__UpperCAmelCase ):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
UpperCamelCase__ : str = failure[i - 1]
continue
j += 1
failure.append(__UpperCAmelCase )
return failure
if __name__ == "__main__":
# Test 1)
UpperCAmelCase_ = 'abc1abc12'
UpperCAmelCase_ = 'alskfjaldsabc1abc1abc12k23adsfabcabc'
UpperCAmelCase_ = 'alskfjaldsk23adsfabcabc'
assert kmp(pattern, texta) and not kmp(pattern, texta)
# Test 2)
UpperCAmelCase_ = 'ABABX'
UpperCAmelCase_ = 'ABABZABABYABABX'
assert kmp(pattern, text)
# Test 3)
UpperCAmelCase_ = 'AAAB'
UpperCAmelCase_ = 'ABAAAAAB'
assert kmp(pattern, text)
# Test 4)
UpperCAmelCase_ = 'abcdabcy'
UpperCAmelCase_ = 'abcxabcdabxabcdabcdabcy'
assert kmp(pattern, text)
# Test 5)
UpperCAmelCase_ = 'aabaabaaa'
assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
| 369 | 0 |
'''simple docstring'''
import unittest
from transformers import (
MODEL_FOR_OBJECT_DETECTION_MAPPING,
AutoFeatureExtractor,
AutoModelForObjectDetection,
ObjectDetectionPipeline,
is_vision_available,
pipeline,
)
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_pytesseract,
require_tf,
require_timm,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_vision_available():
from PIL import Image
else:
class lowerCamelCase :
'''simple docstring'''
@staticmethod
def lowercase__ ( *lowerCAmelCase_ : str , **lowerCAmelCase_ : List[str] ) -> Dict:
'''simple docstring'''
pass
@is_pipeline_test
@require_vision
@require_timm
@require_torch
class lowerCamelCase ( unittest.TestCase ):
'''simple docstring'''
__snake_case = MODEL_FOR_OBJECT_DETECTION_MAPPING
def lowercase__ ( self : Dict , lowerCAmelCase_ : Dict , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[Any] ) -> Tuple:
'''simple docstring'''
A__ : Tuple =ObjectDetectionPipeline(model=lowerCAmelCase_ , image_processor=lowerCAmelCase_ )
return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"]
def lowercase__ ( self : Union[str, Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ) -> Optional[Any]:
'''simple docstring'''
A__ : Any =object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 )
self.assertGreater(len(lowerCAmelCase_ ) , 0 )
for detected_object in outputs:
self.assertEqual(
lowerCAmelCase_ , {
"""score""": ANY(lowerCAmelCase_ ),
"""label""": ANY(lowerCAmelCase_ ),
"""box""": {"""xmin""": ANY(lowerCAmelCase_ ), """ymin""": ANY(lowerCAmelCase_ ), """xmax""": ANY(lowerCAmelCase_ ), """ymax""": ANY(lowerCAmelCase_ )},
} , )
import datasets
A__ : Union[str, Any] =datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" )
A__ : Any =[
Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ),
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
# RGBA
dataset[0]["""file"""],
# LA
dataset[1]["""file"""],
# L
dataset[2]["""file"""],
]
A__ : List[Any] =object_detector(lowerCAmelCase_ , threshold=0.0 )
self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) )
for outputs in batch_outputs:
self.assertGreater(len(lowerCAmelCase_ ) , 0 )
for detected_object in outputs:
self.assertEqual(
lowerCAmelCase_ , {
"""score""": ANY(lowerCAmelCase_ ),
"""label""": ANY(lowerCAmelCase_ ),
"""box""": {"""xmin""": ANY(lowerCAmelCase_ ), """ymin""": ANY(lowerCAmelCase_ ), """xmax""": ANY(lowerCAmelCase_ ), """ymax""": ANY(lowerCAmelCase_ )},
} , )
@require_tf
@unittest.skip("""Object detection not implemented in TF""" )
def lowercase__ ( self : Union[str, Any] ) -> Optional[int]:
'''simple docstring'''
pass
@require_torch
def lowercase__ ( self : Dict ) -> List[Any]:
'''simple docstring'''
A__ : str ="""hf-internal-testing/tiny-detr-mobilenetsv3"""
A__ : Optional[Any] =AutoModelForObjectDetection.from_pretrained(lowerCAmelCase_ )
A__ : List[str] =AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )
A__ : Dict =ObjectDetectionPipeline(model=lowerCAmelCase_ , feature_extractor=lowerCAmelCase_ )
A__ : List[Any] =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 )
self.assertEqual(
nested_simplify(lowerCAmelCase_ , decimals=4 ) , [
{"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}},
{"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}},
] , )
A__ : Any =object_detector(
[
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
] , threshold=0.0 , )
self.assertEqual(
nested_simplify(lowerCAmelCase_ , decimals=4 ) , [
[
{"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}},
{"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}},
],
[
{"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}},
{"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}},
],
] , )
@require_torch
@slow
def lowercase__ ( self : Dict ) -> Optional[Any]:
'''simple docstring'''
A__ : int ="""facebook/detr-resnet-50"""
A__ : Optional[int] =AutoModelForObjectDetection.from_pretrained(lowerCAmelCase_ )
A__ : Optional[Any] =AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )
A__ : Tuple =ObjectDetectionPipeline(model=lowerCAmelCase_ , feature_extractor=lowerCAmelCase_ )
A__ : Optional[Any] =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" )
self.assertEqual(
nested_simplify(lowerCAmelCase_ , decimals=4 ) , [
{"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}},
{"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}},
{"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}},
{"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}},
{"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}},
] , )
A__ : List[Any] =object_detector(
[
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
] )
self.assertEqual(
nested_simplify(lowerCAmelCase_ , decimals=4 ) , [
[
{"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}},
{"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}},
{"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}},
{"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}},
{"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}},
],
[
{"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}},
{"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}},
{"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}},
{"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}},
{"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}},
],
] , )
@require_torch
@slow
def lowercase__ ( self : List[str] ) -> List[str]:
'''simple docstring'''
A__ : Tuple ="""facebook/detr-resnet-50"""
A__ : Tuple =pipeline("""object-detection""" , model=lowerCAmelCase_ )
A__ : Tuple =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" )
self.assertEqual(
nested_simplify(lowerCAmelCase_ , decimals=4 ) , [
{"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}},
{"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}},
{"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}},
{"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}},
{"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}},
] , )
A__ : int =object_detector(
[
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
] )
self.assertEqual(
nested_simplify(lowerCAmelCase_ , decimals=4 ) , [
[
{"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}},
{"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}},
{"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}},
{"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}},
{"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}},
],
[
{"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}},
{"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}},
{"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}},
{"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}},
{"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}},
],
] , )
@require_torch
@slow
def lowercase__ ( self : Any ) -> Optional[Any]:
'''simple docstring'''
A__ : Any =0.9985
A__ : Any ="""facebook/detr-resnet-50"""
A__ : List[str] =pipeline("""object-detection""" , model=lowerCAmelCase_ )
A__ : Tuple =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=lowerCAmelCase_ )
self.assertEqual(
nested_simplify(lowerCAmelCase_ , decimals=4 ) , [
{"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}},
{"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}},
] , )
@require_torch
@require_pytesseract
@slow
def lowercase__ ( self : int ) -> Optional[int]:
'''simple docstring'''
A__ : Optional[int] ="""Narsil/layoutlmv3-finetuned-funsd"""
A__ : Any =0.9993
A__ : Tuple =pipeline("""object-detection""" , model=lowerCAmelCase_ , threshold=lowerCAmelCase_ )
A__ : Union[str, Any] =object_detector(
"""https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" )
self.assertEqual(
nested_simplify(lowerCAmelCase_ , decimals=4 ) , [
{"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 2_94, """ymin""": 2_54, """xmax""": 3_43, """ymax""": 2_64}},
{"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 2_94, """ymin""": 2_54, """xmax""": 3_43, """ymax""": 2_64}},
] , )
| 215 |
'''simple docstring'''
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.models import Sequential
if __name__ == "__main__":
__snake_case : str = pd.read_csv('sample_data.csv', header=None)
__snake_case : int = df.shape[:1][0]
# If you're using some other dataset input the target column
__snake_case : Optional[int] = df.iloc[:, 1:2]
__snake_case : Optional[Any] = actual_data.values.reshape(len_data, 1)
__snake_case : Optional[Any] = MinMaxScaler().fit_transform(actual_data)
__snake_case : List[str] = 10
__snake_case : Optional[int] = 5
__snake_case : Dict = 20
__snake_case : int = len_data - periods * look_back
__snake_case : Any = actual_data[:division]
__snake_case : List[str] = actual_data[division - look_back :]
__snake_case , __snake_case : List[Any] = [], []
__snake_case , __snake_case : Union[str, Any] = [], []
for i in range(0, len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
__snake_case : Any = np.array(train_x)
__snake_case : List[Any] = np.array(test_x)
__snake_case : Tuple = np.array([list(i.ravel()) for i in train_y])
__snake_case : int = np.array([list(i.ravel()) for i in test_y])
__snake_case : Optional[int] = Sequential()
model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True))
model.add(LSTM(64, input_shape=(128, 1)))
model.add(Dense(forward_days))
model.compile(loss='mean_squared_error', optimizer='adam')
__snake_case : Union[str, Any] = model.fit(
x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4
)
__snake_case : Any = model.predict(x_test)
| 215 | 1 |
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import AutoTokenizer, BarkProcessor
from transformers.testing_utils import require_torch, slow
@require_torch
class _a ( unittest.TestCase ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase ="ylacombe/bark-small"
_UpperCAmelCase =tempfile.mkdtemp()
_UpperCAmelCase ="en_speaker_1"
_UpperCAmelCase ="This is a test string"
_UpperCAmelCase ="speaker_embeddings_path.json"
_UpperCAmelCase ="speaker_embeddings"
def SCREAMING_SNAKE_CASE ( self , **_snake_case ):
return AutoTokenizer.from_pretrained(self.checkpoint , **_snake_case )
def SCREAMING_SNAKE_CASE ( self ):
shutil.rmtree(self.tmpdirname )
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase =self.get_tokenizer()
_UpperCAmelCase =BarkProcessor(tokenizer=_snake_case )
processor.save_pretrained(self.tmpdirname )
_UpperCAmelCase =BarkProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
@slow
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase =BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
processor.save_pretrained(
self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , )
_UpperCAmelCase =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" )
_UpperCAmelCase =BarkProcessor.from_pretrained(
self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase =BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
_UpperCAmelCase =35
_UpperCAmelCase =2
_UpperCAmelCase =8
_UpperCAmelCase ={
"semantic_prompt": np.ones(_snake_case ),
"coarse_prompt": np.ones((nb_codebooks_coarse, seq_len) ),
"fine_prompt": np.ones((nb_codebooks_total, seq_len) ),
}
# test providing already loaded voice_preset
_UpperCAmelCase =processor(text=self.input_string , voice_preset=_snake_case )
_UpperCAmelCase =inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_snake_case , np.array([] ) ).tolist() )
# test loading voice preset from npz file
_UpperCAmelCase =os.path.join(self.tmpdirname , "file.npz" )
np.savez(_snake_case , **_snake_case )
_UpperCAmelCase =processor(text=self.input_string , voice_preset=_snake_case )
_UpperCAmelCase =inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_snake_case , np.array([] ) ).tolist() )
# test loading voice preset from the hub
_UpperCAmelCase =processor(text=self.input_string , voice_preset=self.voice_preset )
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase =self.get_tokenizer()
_UpperCAmelCase =BarkProcessor(tokenizer=_snake_case )
_UpperCAmelCase =processor(text=self.input_string )
_UpperCAmelCase =tokenizer(
self.input_string , padding="max_length" , max_length=256 , add_special_tokens=_snake_case , return_attention_mask=_snake_case , return_token_type_ids=_snake_case , )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
| 592 |
import pytest
from datasets.splits import SplitDict, SplitInfo
from datasets.utils.py_utils import asdict
@pytest.mark.parametrize(
"split_dict" , [
SplitDict(),
SplitDict({"train": SplitInfo(name="train" , num_bytes=1337 , num_examples=42 , dataset_name="my_dataset" )} ),
SplitDict({"train": SplitInfo(name="train" , num_bytes=1337 , num_examples=42 )} ),
SplitDict({"train": SplitInfo()} ),
] , )
def lowerCamelCase__ ( _lowerCamelCase ) ->List[str]:
_UpperCAmelCase =split_dict._to_yaml_list()
assert len(_lowerCamelCase ) == len(_lowerCamelCase )
_UpperCAmelCase =SplitDict._from_yaml_list(_lowerCamelCase )
for split_name, split_info in split_dict.items():
# dataset_name field is deprecated, and is therefore not part of the YAML dump
_UpperCAmelCase =None
# the split name of split_dict takes over the name of the split info object
_UpperCAmelCase =split_name
assert split_dict == reloaded
@pytest.mark.parametrize(
"split_info" , [SplitInfo(), SplitInfo(dataset_name=_lowerCamelCase ), SplitInfo(dataset_name="my_dataset" )] )
def lowerCamelCase__ ( _lowerCamelCase ) ->Any:
# For backward compatibility, we need asdict(split_dict) to return split info dictrionaries with the "dataset_name"
# field even if it's deprecated. This way old versionso of `datasets` can still reload dataset_infos.json files
_UpperCAmelCase =asdict(SplitDict({"train": split_info} ) )
assert "dataset_name" in split_dict_asdict["train"]
assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
| 592 | 1 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from ..models.auto import AutoProcessor
from ..models.vision_encoder_decoder import VisionEncoderDecoderModel
from ..utils import is_vision_available
from .base import PipelineTool
if is_vision_available():
from PIL import Image
class SCREAMING_SNAKE_CASE (a__ ):
lowerCAmelCase = '''naver-clova-ix/donut-base-finetuned-docvqa'''
lowerCAmelCase = (
'''This is a tool that answers a question about an document (pdf). It takes an input named `document` which '''
'''should be the document containing the information, as well as a `question` that is the question about the '''
'''document. It returns a text that contains the answer to the question.'''
)
lowerCAmelCase = '''document_qa'''
lowerCAmelCase = AutoProcessor
lowerCAmelCase = VisionEncoderDecoderModel
lowerCAmelCase = ['''image''', '''text''']
lowerCAmelCase = ['''text''']
def __init__( self , *_UpperCAmelCase , **_UpperCAmelCase):
'''simple docstring'''
if not is_vision_available():
raise ValueError('Pillow must be installed to use the DocumentQuestionAnsweringTool.')
super().__init__(*_UpperCAmelCase , **_UpperCAmelCase)
def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase):
'''simple docstring'''
__A : Optional[int] = '<s_docvqa><s_question>{user_input}</s_question><s_answer>'
__A : List[Any] = task_prompt.replace('{user_input}' , _UpperCAmelCase)
__A : Tuple = self.pre_processor.tokenizer(
_UpperCAmelCase , add_special_tokens=_UpperCAmelCase , return_tensors='pt').input_ids
__A : Any = self.pre_processor(_UpperCAmelCase , return_tensors='pt').pixel_values
return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values}
def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase):
'''simple docstring'''
return self.model.generate(
inputs['pixel_values'].to(self.device) , decoder_input_ids=inputs['decoder_input_ids'].to(self.device) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=_UpperCAmelCase , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=_UpperCAmelCase , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=_UpperCAmelCase , ).sequences
def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase):
'''simple docstring'''
__A : Optional[Any] = self.pre_processor.batch_decode(_UpperCAmelCase)[0]
__A : Optional[Any] = sequence.replace(self.pre_processor.tokenizer.eos_token , '')
__A : int = sequence.replace(self.pre_processor.tokenizer.pad_token , '')
__A : Any = re.sub(R'<.*?>' , '' , _UpperCAmelCase , count=1).strip() # remove first task start token
__A : List[str] = self.pre_processor.tokenajson(_UpperCAmelCase)
return sequence["answer"] | 8 |
"""simple docstring"""
import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
convert,
ensure_valid_input,
generate_identified_filename,
infer_shapes,
quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow
class lowerCamelCase_:
'''simple docstring'''
def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
return None
class lowerCamelCase_:
'''simple docstring'''
def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
return None
class lowerCamelCase_( unittest.TestCase ):
'''simple docstring'''
lowercase__ : Tuple = [
# (model_name, model_kwargs)
('bert-base-cased', {}),
('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore
]
@require_tf
@slow
def snake_case__ ( self ):
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
self._test_export(lowerCamelCase__ , '''tf''' , 1_2 , **lowerCamelCase__ )
@require_torch
@slow
def snake_case__ ( self ):
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
self._test_export(lowerCamelCase__ , '''pt''' , 1_2 , **lowerCamelCase__ )
@require_torch
@slow
def snake_case__ ( self ):
from transformers import BertModel
_lowerCamelCase = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words''']
with NamedTemporaryFile(mode='''w+t''' ) as vocab_file:
vocab_file.write('''\n'''.join(lowerCamelCase__ ) )
vocab_file.flush()
_lowerCamelCase = BertTokenizerFast(vocab_file.name )
with TemporaryDirectory() as bert_save_dir:
_lowerCamelCase = BertModel(BertConfig(vocab_size=len(lowerCamelCase__ ) ) )
model.save_pretrained(lowerCamelCase__ )
self._test_export(lowerCamelCase__ , '''pt''' , 1_2 , lowerCamelCase__ )
@require_tf
@slow
def snake_case__ ( self ):
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
_lowerCamelCase = self._test_export(lowerCamelCase__ , '''tf''' , 1_2 , **lowerCamelCase__ )
_lowerCamelCase = quantize(Path(lowerCamelCase__ ) )
# Ensure the actual quantized model is not bigger than the original one
if quantized_path.stat().st_size >= Path(lowerCamelCase__ ).stat().st_size:
self.fail('''Quantized model is bigger than initial ONNX model''' )
@require_torch
@slow
def snake_case__ ( self ):
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
_lowerCamelCase = self._test_export(lowerCamelCase__ , '''pt''' , 1_2 , **lowerCamelCase__ )
_lowerCamelCase = quantize(lowerCamelCase__ )
# Ensure the actual quantized model is not bigger than the original one
if quantized_path.stat().st_size >= Path(lowerCamelCase__ ).stat().st_size:
self.fail('''Quantized model is bigger than initial ONNX model''' )
def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , **lowerCamelCase__ ):
try:
# Compute path
with TemporaryDirectory() as tempdir:
_lowerCamelCase = Path(lowerCamelCase__ ).joinpath('''model.onnx''' )
# Remove folder if exists
if path.parent.exists():
path.parent.rmdir()
# Export
convert(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ )
return path
except Exception as e:
self.fail(lowerCamelCase__ )
@require_torch
@require_tokenizers
@slow
def snake_case__ ( self ):
from transformers import BertModel
_lowerCamelCase = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) )
_lowerCamelCase = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' )
self._test_infer_dynamic_axis(lowerCamelCase__ , lowerCamelCase__ , '''pt''' )
@require_tf
@require_tokenizers
@slow
def snake_case__ ( self ):
from transformers import TFBertModel
_lowerCamelCase = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) )
_lowerCamelCase = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' )
self._test_infer_dynamic_axis(lowerCamelCase__ , lowerCamelCase__ , '''tf''' )
def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
_lowerCamelCase = FeatureExtractionPipeline(lowerCamelCase__ , lowerCamelCase__ )
_lowerCamelCase = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1''']
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = infer_shapes(lowerCamelCase__ , lowerCamelCase__ )
# Assert all variables are present
self.assertEqual(len(lowerCamelCase__ ) , len(lowerCamelCase__ ) )
self.assertTrue(all(var_name in shapes for var_name in variable_names ) )
self.assertSequenceEqual(variable_names[:3] , lowerCamelCase__ )
self.assertSequenceEqual(variable_names[3:] , lowerCamelCase__ )
# Assert inputs are {0: batch, 1: sequence}
for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} )
# Assert outputs are {0: batch, 1: sequence} and {0: batch}
self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} )
self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} )
def snake_case__ ( self ):
_lowerCamelCase = ['''input_ids''', '''attention_mask''', '''token_type_ids''']
_lowerCamelCase = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]}
_lowerCamelCase , _lowerCamelCase = ensure_valid_input(FuncContiguousArgs() , lowerCamelCase__ , lowerCamelCase__ )
# Should have exactly the same number of args (all are valid)
self.assertEqual(len(lowerCamelCase__ ) , 3 )
# Should have exactly the same input names
self.assertEqual(set(lowerCamelCase__ ) , set(lowerCamelCase__ ) )
# Parameter should be reordered according to their respective place in the function:
# (input_ids, token_type_ids, attention_mask)
self.assertEqual(lowerCamelCase__ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) )
# Generated args are interleaved with another args (for instance parameter "past" in GPT2)
_lowerCamelCase , _lowerCamelCase = ensure_valid_input(FuncNonContiguousArgs() , lowerCamelCase__ , lowerCamelCase__ )
# Should have exactly the one arg (all before the one not provided "some_other_args")
self.assertEqual(len(lowerCamelCase__ ) , 1 )
self.assertEqual(len(lowerCamelCase__ ) , 1 )
# Should have only "input_ids"
self.assertEqual(inputs_args[0] , tokens['''input_ids'''] )
self.assertEqual(ordered_input_names[0] , '''input_ids''' )
def snake_case__ ( self ):
_lowerCamelCase = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' )
self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
| 661 | 0 |
import argparse
import json
from collections import OrderedDict
import torch
from huggingface_hub import cached_download, hf_hub_url
from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification
def A ( _lowercase ):
SCREAMING_SNAKE_CASE : Optional[Any] = []
embed.append(
(
f"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight""",
f"""stage{idx}.patch_embed.proj.weight""",
) )
embed.append(
(
f"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias""",
f"""stage{idx}.patch_embed.proj.bias""",
) )
embed.append(
(
f"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight""",
f"""stage{idx}.patch_embed.norm.weight""",
) )
embed.append(
(
f"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias""",
f"""stage{idx}.patch_embed.norm.bias""",
) )
return embed
def A ( _lowercase , _lowercase ):
SCREAMING_SNAKE_CASE : Optional[Any] = []
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked""",
f"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight""",
f"""stage{idx}.blocks.{cnt}.attn.proj_q.weight""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias""",
f"""stage{idx}.blocks.{cnt}.attn.proj_q.bias""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight""",
f"""stage{idx}.blocks.{cnt}.attn.proj_k.weight""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias""",
f"""stage{idx}.blocks.{cnt}.attn.proj_k.bias""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight""",
f"""stage{idx}.blocks.{cnt}.attn.proj_v.weight""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias""",
f"""stage{idx}.blocks.{cnt}.attn.proj_v.bias""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight""",
f"""stage{idx}.blocks.{cnt}.attn.proj.weight""",
) )
attention_weights.append(
(
f"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias""",
f"""stage{idx}.blocks.{cnt}.attn.proj.bias""",
) )
attention_weights.append(
(f"""cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight""", f"""stage{idx}.blocks.{cnt}.mlp.fc1.weight""") )
attention_weights.append(
(f"""cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias""", f"""stage{idx}.blocks.{cnt}.mlp.fc1.bias""") )
attention_weights.append(
(f"""cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight""", f"""stage{idx}.blocks.{cnt}.mlp.fc2.weight""") )
attention_weights.append(
(f"""cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias""", f"""stage{idx}.blocks.{cnt}.mlp.fc2.bias""") )
attention_weights.append(
(f"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight""", f"""stage{idx}.blocks.{cnt}.norm1.weight""") )
attention_weights.append(
(f"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias""", f"""stage{idx}.blocks.{cnt}.norm1.bias""") )
attention_weights.append(
(f"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight""", f"""stage{idx}.blocks.{cnt}.norm2.weight""") )
attention_weights.append(
(f"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias""", f"""stage{idx}.blocks.{cnt}.norm2.bias""") )
return attention_weights
def A ( _lowercase ):
SCREAMING_SNAKE_CASE : int = []
token.append((f"""cvt.encoder.stages.{idx}.cls_token""", '''stage2.cls_token''') )
return token
def A ( ):
SCREAMING_SNAKE_CASE : Any = []
head.append(('''layernorm.weight''', '''norm.weight''') )
head.append(('''layernorm.bias''', '''norm.bias''') )
head.append(('''classifier.weight''', '''head.weight''') )
head.append(('''classifier.bias''', '''head.bias''') )
return head
def A ( _lowercase , _lowercase , _lowercase , _lowercase ):
SCREAMING_SNAKE_CASE : List[str] = '''imagenet-1k-id2label.json'''
SCREAMING_SNAKE_CASE : str = 1_000
SCREAMING_SNAKE_CASE : Optional[Any] = '''huggingface/label-files'''
SCREAMING_SNAKE_CASE : List[Any] = num_labels
SCREAMING_SNAKE_CASE : List[str] = json.load(open(cached_download(hf_hub_url(_lowercase , _lowercase , repo_type='''dataset''' ) ) , '''r''' ) )
SCREAMING_SNAKE_CASE : Tuple = {int(_lowercase ): v for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE : List[Any] = idalabel
SCREAMING_SNAKE_CASE : Any = {v: k for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE : int = CvtConfig(num_labels=_lowercase , idalabel=_lowercase , labelaid=_lowercase )
# For depth size 13 (13 = 1+2+10)
if cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "13":
SCREAMING_SNAKE_CASE : int = [1, 2, 10]
# For depth size 21 (21 = 1+4+16)
elif cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "21":
SCREAMING_SNAKE_CASE : Dict = [1, 4, 16]
# For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20)
else:
SCREAMING_SNAKE_CASE : Any = [2, 2, 20]
SCREAMING_SNAKE_CASE : List[str] = [3, 12, 16]
SCREAMING_SNAKE_CASE : int = [192, 768, 1_024]
SCREAMING_SNAKE_CASE : Any = CvtForImageClassification(_lowercase )
SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' )
SCREAMING_SNAKE_CASE : Any = image_size
SCREAMING_SNAKE_CASE : Any = torch.load(_lowercase , map_location=torch.device('''cpu''' ) )
SCREAMING_SNAKE_CASE : str = OrderedDict()
SCREAMING_SNAKE_CASE : Union[str, Any] = []
for idx in range(len(config.depth ) ):
if config.cls_token[idx]:
SCREAMING_SNAKE_CASE : List[str] = list_of_state_dict + cls_token(_lowercase )
SCREAMING_SNAKE_CASE : Optional[Any] = list_of_state_dict + embeddings(_lowercase )
for cnt in range(config.depth[idx] ):
SCREAMING_SNAKE_CASE : List[Any] = list_of_state_dict + attention(_lowercase , _lowercase )
SCREAMING_SNAKE_CASE : Any = list_of_state_dict + final()
for gg in list_of_state_dict:
print(_lowercase )
for i in range(len(_lowercase ) ):
SCREAMING_SNAKE_CASE : Tuple = original_weights[list_of_state_dict[i][1]]
model.load_state_dict(_lowercase )
model.save_pretrained(_lowercase )
image_processor.save_pretrained(_lowercase )
# Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al
if __name__ == "__main__":
__UpperCamelCase : Union[str, Any] = argparse.ArgumentParser()
parser.add_argument(
'--cvt_model',
default='cvt-w24',
type=str,
help='Name of the cvt model you\'d like to convert.',
)
parser.add_argument(
'--image_size',
default=384,
type=int,
help='Input Image Size',
)
parser.add_argument(
'--cvt_file_name',
default=R'cvtmodels\CvT-w24-384x384-IN-22k.pth',
type=str,
help='Input Image Size',
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
)
__UpperCamelCase : Tuple = parser.parse_args()
convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
| 705 | import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from timm import create_model
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform
from transformers import BitConfig, BitForImageClassification, BitImageProcessor
from transformers.image_utils import PILImageResampling
from transformers.utils import logging
logging.set_verbosity_info()
__UpperCamelCase : str = logging.get_logger(__name__)
def A ( _lowercase ):
SCREAMING_SNAKE_CASE : Any = '''huggingface/label-files'''
SCREAMING_SNAKE_CASE : Any = '''imagenet-1k-id2label.json'''
SCREAMING_SNAKE_CASE : Any = json.load(open(hf_hub_download(_lowercase , _lowercase , repo_type='''dataset''' ) , '''r''' ) )
SCREAMING_SNAKE_CASE : Union[str, Any] = {int(_lowercase ): v for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE : Dict = {v: k for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE : str = '''std_conv''' if '''bit''' in model_name else False
# note that when using BiT as backbone for ViT-hybrid checkpoints,
# one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same",
# config.conv_layer = "std_conv_same"
SCREAMING_SNAKE_CASE : Optional[int] = BitConfig(
conv_layer=_lowercase , num_labels=1_000 , idalabel=_lowercase , labelaid=_lowercase , )
return config
def A ( _lowercase ):
if "stem.conv" in name:
SCREAMING_SNAKE_CASE : Optional[int] = name.replace('''stem.conv''' , '''bit.embedder.convolution''' )
if "blocks" in name:
SCREAMING_SNAKE_CASE : Tuple = name.replace('''blocks''' , '''layers''' )
if "head.fc" in name:
SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace('''head.fc''' , '''classifier.1''' )
if name.startswith('''norm''' ):
SCREAMING_SNAKE_CASE : str = '''bit.''' + name
if "bit" not in name and "classifier" not in name:
SCREAMING_SNAKE_CASE : Union[str, Any] = '''bit.encoder.''' + name
return name
def A ( ):
SCREAMING_SNAKE_CASE : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
SCREAMING_SNAKE_CASE : List[str] = Image.open(requests.get(_lowercase , stream=_lowercase ).raw )
return im
@torch.no_grad()
def A ( _lowercase , _lowercase , _lowercase=False ):
SCREAMING_SNAKE_CASE : List[Any] = get_config(_lowercase )
# load original model from timm
SCREAMING_SNAKE_CASE : Optional[Any] = create_model(_lowercase , pretrained=_lowercase )
timm_model.eval()
# load state_dict of original model
SCREAMING_SNAKE_CASE : Optional[int] = timm_model.state_dict()
for key in state_dict.copy().keys():
SCREAMING_SNAKE_CASE : Dict = state_dict.pop(_lowercase )
SCREAMING_SNAKE_CASE : Optional[int] = val.squeeze() if '''head''' in key else val
# load HuggingFace model
SCREAMING_SNAKE_CASE : str = BitForImageClassification(_lowercase )
model.eval()
model.load_state_dict(_lowercase )
# create image processor
SCREAMING_SNAKE_CASE : Optional[Any] = create_transform(**resolve_data_config({} , model=_lowercase ) )
SCREAMING_SNAKE_CASE : List[str] = transform.transforms
SCREAMING_SNAKE_CASE : Union[str, Any] = {
'''bilinear''': PILImageResampling.BILINEAR,
'''bicubic''': PILImageResampling.BICUBIC,
'''nearest''': PILImageResampling.NEAREST,
}
SCREAMING_SNAKE_CASE : Tuple = BitImageProcessor(
do_resize=_lowercase , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_lowercase , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=_lowercase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , )
SCREAMING_SNAKE_CASE : Any = prepare_img()
SCREAMING_SNAKE_CASE : Union[str, Any] = transform(_lowercase ).unsqueeze(0 )
SCREAMING_SNAKE_CASE : Optional[int] = processor(_lowercase , return_tensors='''pt''' ).pixel_values
# verify pixel values
assert torch.allclose(_lowercase , _lowercase )
# verify logits
with torch.no_grad():
SCREAMING_SNAKE_CASE : Dict = model(_lowercase )
SCREAMING_SNAKE_CASE : Optional[Any] = outputs.logits
print('''Logits:''' , logits[0, :3] )
print('''Predicted class:''' , model.config.idalabel[logits.argmax(-1 ).item()] )
SCREAMING_SNAKE_CASE : List[Any] = timm_model(_lowercase )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(_lowercase , outputs.logits , atol=1e-3 )
print('''Looks ok!''' )
if pytorch_dump_folder_path is not None:
Path(_lowercase ).mkdir(exist_ok=_lowercase )
print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" )
model.save_pretrained(_lowercase )
processor.save_pretrained(_lowercase )
if push_to_hub:
print(f"""Pushing model {model_name} and processor to the hub""" )
model.push_to_hub(f"""ybelkada/{model_name}""" )
processor.push_to_hub(f"""ybelkada/{model_name}""" )
if __name__ == "__main__":
__UpperCamelCase : Any = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='resnetv2_50x1_bitm',
type=str,
help='Name of the BiT timm model you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
)
parser.add_argument(
'--push_to_hub',
action='store_true',
help='Whether to push the model to the hub.',
)
__UpperCamelCase : Optional[int] = parser.parse_args()
convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 34 | 0 |
import math
import tensorflow as tf
from packaging import version
def UpperCamelCase__( UpperCamelCase__ : Optional[int] )->int:
A__ = tf.convert_to_tensor(UpperCamelCase__ )
A__ = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) ))
return x * cdf
def UpperCamelCase__( UpperCamelCase__ : Union[str, Any] )->Tuple:
A__ = tf.convert_to_tensor(UpperCamelCase__ )
A__ = tf.cast(math.pi , x.dtype )
A__ = tf.cast(0.044715 , x.dtype )
A__ = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(UpperCamelCase__ , 3 )) ))
return x * cdf
def UpperCamelCase__( UpperCamelCase__ : Optional[int] )->Any:
A__ = tf.convert_to_tensor(UpperCamelCase__ )
return x * tf.tanh(tf.math.softplus(UpperCamelCase__ ) )
def UpperCamelCase__( UpperCamelCase__ : Any )->Union[str, Any]:
A__ = tf.convert_to_tensor(UpperCamelCase__ )
A__ = tf.cast(0.044715 , x.dtype )
A__ = tf.cast(0.7978845608 , x.dtype )
return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) ))
def UpperCamelCase__( UpperCamelCase__ : Union[str, Any] )->List[str]:
A__ = tf.convert_to_tensor(UpperCamelCase__ )
A__ = tf.cast(1.702 , x.dtype )
return x * tf.math.sigmoid(coeff * x )
def UpperCamelCase__( UpperCamelCase__ : Optional[int] )->Dict:
return tf.clip_by_value(_gelu(UpperCamelCase__ ) , -10 , 10 )
def UpperCamelCase__( UpperCamelCase__ : Any , UpperCamelCase__ : Optional[int]=-1 )->str:
A__ , A__ = tf.split(UpperCamelCase__ , 2 , axis=UpperCamelCase__ )
return a * tf.math.sigmoid(UpperCamelCase__ )
if version.parse(tf.version.VERSION) >= version.parse('2.4'):
def UpperCamelCase__( UpperCamelCase__ : Any )->List[str]:
return tf.keras.activations.gelu(UpperCamelCase__ , approximate=UpperCamelCase__ )
a__: List[str] = tf.keras.activations.gelu
a__: List[str] = approximate_gelu_wrap
else:
a__: Tuple = _gelu
a__: Optional[int] = _gelu_new
a__: Union[str, Any] = {
'gelu': gelu,
'gelu_10': gelu_aa,
'gelu_fast': gelu_fast,
'gelu_new': gelu_new,
'glu': glu,
'mish': mish,
'quick_gelu': quick_gelu,
'relu': tf.keras.activations.relu,
'sigmoid': tf.keras.activations.sigmoid,
'silu': tf.keras.activations.swish,
'swish': tf.keras.activations.swish,
'tanh': tf.keras.activations.tanh,
}
def UpperCamelCase__( UpperCamelCase__ : Optional[Any] )->Any:
if activation_string in ACTaFN:
return ACTaFN[activation_string]
else:
raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}" )
| 190 |
import itertools
import math
def UpperCamelCase__( UpperCamelCase__ : int )->bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(math.sqrt(UpperCamelCase__ ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def UpperCamelCase__( )->Tuple:
A__ = 2
while True:
if is_prime(UpperCamelCase__ ):
yield num
num += 1
def UpperCamelCase__( UpperCamelCase__ : int = 1_00_01 )->int:
return next(itertools.islice(prime_generator() , nth - 1 , UpperCamelCase__ ) )
if __name__ == "__main__":
print(F"{solution() = }")
| 190 | 1 |
from __future__ import annotations
import copy
import inspect
import json
import math
import os
import tempfile
import unittest
from importlib import import_module
import numpy as np
from transformers import ViTMAEConfig
from transformers.file_utils import cached_property, is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, require_vision, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFViTMAEForPreTraining, TFViTMAEModel
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class lowerCamelCase__ :
'''simple docstring'''
def __init__( self :List[Any] , a :str , a :Union[str, Any]=1_3 , a :List[Any]=3_0 , a :str=2 , a :str=3 , a :Any=True , a :List[Any]=True , a :Any=3_2 , a :List[Any]=2 , a :str=4 , a :List[Any]=3_7 , a :Dict="gelu" , a :Tuple=0.1 , a :List[Any]=0.1 , a :Tuple=1_0 , a :Optional[int]=0.02 , a :Any=3 , a :str=0.6 , a :Optional[int]=None , ) -> Any:
__UpperCamelCase : int = parent
__UpperCamelCase : Tuple = batch_size
__UpperCamelCase : List[str] = image_size
__UpperCamelCase : Any = patch_size
__UpperCamelCase : int = num_channels
__UpperCamelCase : int = is_training
__UpperCamelCase : Tuple = use_labels
__UpperCamelCase : Optional[Any] = hidden_size
__UpperCamelCase : int = num_hidden_layers
__UpperCamelCase : Any = num_attention_heads
__UpperCamelCase : List[str] = intermediate_size
__UpperCamelCase : Dict = hidden_act
__UpperCamelCase : List[str] = hidden_dropout_prob
__UpperCamelCase : Any = attention_probs_dropout_prob
__UpperCamelCase : Any = type_sequence_label_size
__UpperCamelCase : int = initializer_range
__UpperCamelCase : int = mask_ratio
__UpperCamelCase : Union[str, Any] = scope
# in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
# (we add 1 for the [CLS] token)
__UpperCamelCase : int = (image_size // patch_size) ** 2
__UpperCamelCase : Any = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) )
def _lowerCamelCase ( self :Any ) -> str:
__UpperCamelCase : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__UpperCamelCase : List[Any] = None
if self.use_labels:
__UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__UpperCamelCase : Dict = self.get_config()
return config, pixel_values, labels
def _lowerCamelCase ( self :Optional[Any] ) -> Optional[Any]:
return ViTMAEConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=snake_case_ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , )
def _lowerCamelCase ( self :Union[str, Any] , a :List[Any] , a :Optional[Any] , a :List[str] ) -> int:
__UpperCamelCase : Dict = TFViTMAEModel(config=snake_case_ )
__UpperCamelCase : Optional[Any] = model(snake_case_ , training=snake_case_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _lowerCamelCase ( self :Union[str, Any] , a :str , a :Tuple , a :str ) -> str:
__UpperCamelCase : str = TFViTMAEForPreTraining(snake_case_ )
__UpperCamelCase : Any = model(snake_case_ , training=snake_case_ )
# expected sequence length = num_patches
__UpperCamelCase : List[str] = (self.image_size // self.patch_size) ** 2
__UpperCamelCase : int = self.patch_size**2 * self.num_channels
self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) )
# test greyscale images
__UpperCamelCase : List[Any] = 1
__UpperCamelCase : Union[str, Any] = TFViTMAEForPreTraining(snake_case_ )
__UpperCamelCase : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
__UpperCamelCase : List[Any] = model(snake_case_ , training=snake_case_ )
__UpperCamelCase : int = self.patch_size**2
self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) )
def _lowerCamelCase ( self :Dict ) -> Optional[int]:
__UpperCamelCase : int = self.prepare_config_and_inputs()
((__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase)) : Any = config_and_inputs
__UpperCamelCase : List[Any] = {"pixel_values": pixel_values}
return config, inputs_dict
@require_tf
class lowerCamelCase__ ( _a , _a , unittest.TestCase):
'''simple docstring'''
_A = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
_A = {"""feature-extraction""": TFViTMAEModel} if is_tf_available() else {}
_A = False
_A = False
_A = False
_A = False
def _lowerCamelCase ( self :str ) -> Optional[int]:
__UpperCamelCase : Dict = TFViTMAEModelTester(self )
__UpperCamelCase : int = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ , hidden_size=3_7 )
def _lowerCamelCase ( self :Optional[int] ) -> Tuple:
self.config_tester.run_common_tests()
@unittest.skip(reason="ViTMAE does not use inputs_embeds" )
def _lowerCamelCase ( self :Dict ) -> Union[str, Any]:
pass
def _lowerCamelCase ( self :str ) -> Any:
__UpperCamelCase , __UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__UpperCamelCase : int = model_class(snake_case_ )
self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) )
__UpperCamelCase : Any = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(snake_case_ , tf.keras.layers.Layer ) )
def _lowerCamelCase ( self :int ) -> Tuple:
__UpperCamelCase , __UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__UpperCamelCase : Tuple = model_class(snake_case_ )
__UpperCamelCase : Optional[int] = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__UpperCamelCase : Any = [*signature.parameters.keys()]
__UpperCamelCase : int = ["pixel_values"]
self.assertListEqual(arg_names[:1] , snake_case_ )
def _lowerCamelCase ( self :List[Any] ) -> str:
__UpperCamelCase : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*snake_case_ )
def _lowerCamelCase ( self :Optional[Any] ) -> List[Any]:
__UpperCamelCase : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*snake_case_ )
def _lowerCamelCase ( self :List[str] ) -> str:
# make the mask reproducible
np.random.seed(2 )
__UpperCamelCase , __UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common()
__UpperCamelCase : Optional[Any] = int((config.image_size // config.patch_size) ** 2 )
__UpperCamelCase : Any = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
for model_class in self.all_model_classes:
__UpperCamelCase : Union[str, Any] = model_class(snake_case_ )
__UpperCamelCase : int = self._prepare_for_class(snake_case_ , snake_case_ )
__UpperCamelCase : Tuple = model(snake_case_ , noise=snake_case_ )
__UpperCamelCase : Any = copy.deepcopy(self._prepare_for_class(snake_case_ , snake_case_ ) )
__UpperCamelCase : Optional[int] = model(**snake_case_ , noise=snake_case_ )
__UpperCamelCase : Optional[Any] = outputs_dict[0].numpy()
__UpperCamelCase : List[str] = outputs_keywords[0].numpy()
self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1E-6 )
def _lowerCamelCase ( self :Any ) -> str:
# make the mask reproducible
np.random.seed(2 )
__UpperCamelCase , __UpperCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common()
__UpperCamelCase : str = int((config.image_size // config.patch_size) ** 2 )
__UpperCamelCase : str = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
def prepare_numpy_arrays(a :int ):
__UpperCamelCase : str = {}
for k, v in inputs_dict.items():
if tf.is_tensor(snake_case_ ):
__UpperCamelCase : Dict = v.numpy()
else:
__UpperCamelCase : List[str] = np.array(snake_case_ )
return inputs_np_dict
for model_class in self.all_model_classes:
__UpperCamelCase : List[Any] = model_class(snake_case_ )
__UpperCamelCase : Union[str, Any] = self._prepare_for_class(snake_case_ , snake_case_ )
__UpperCamelCase : List[str] = prepare_numpy_arrays(snake_case_ )
__UpperCamelCase : int = model(snake_case_ , noise=snake_case_ )
__UpperCamelCase : Tuple = model(**snake_case_ , noise=snake_case_ )
self.assert_outputs_same(snake_case_ , snake_case_ )
def _lowerCamelCase ( self :Union[str, Any] , a :Union[str, Any] , a :Optional[Any] , a :Tuple ) -> Any:
# make masks reproducible
np.random.seed(2 )
__UpperCamelCase : Tuple = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 )
__UpperCamelCase : int = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
__UpperCamelCase : str = tf.constant(snake_case_ )
# Add `noise` argument.
# PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
__UpperCamelCase : Optional[int] = tf_noise
super().check_pt_tf_models(snake_case_ , snake_case_ , snake_case_ )
def _lowerCamelCase ( self :Optional[Any] ) -> int:
# make mask reproducible
np.random.seed(2 )
__UpperCamelCase , __UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common()
__UpperCamelCase : Any = {
module_member
for model_class in self.all_model_classes
for module in (import_module(model_class.__module__ ),)
for module_member_name in dir(snake_case_ )
if module_member_name.endswith("MainLayer" )
# This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`.
and module_member_name[: -len("MainLayer" )] == model_class.__name__[: -len("Model" )]
for module_member in (getattr(snake_case_ , snake_case_ ),)
if isinstance(snake_case_ , snake_case_ )
and tf.keras.layers.Layer in module_member.__bases__
and getattr(snake_case_ , "_keras_serializable" , snake_case_ )
}
__UpperCamelCase : Optional[int] = int((config.image_size // config.patch_size) ** 2 )
__UpperCamelCase : Optional[int] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
__UpperCamelCase : Optional[int] = tf.convert_to_tensor(snake_case_ )
inputs_dict.update({"noise": noise} )
for main_layer_class in tf_main_layer_classes:
__UpperCamelCase : Dict = main_layer_class(snake_case_ )
__UpperCamelCase : str = {
name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items()
}
__UpperCamelCase : str = tf.keras.Model(snake_case_ , outputs=main_layer(snake_case_ ) )
__UpperCamelCase : Dict = model(snake_case_ )
with tempfile.TemporaryDirectory() as tmpdirname:
__UpperCamelCase : Optional[Any] = os.path.join(snake_case_ , "keras_model.h5" )
model.save(snake_case_ )
__UpperCamelCase : Dict = tf.keras.models.load_model(
snake_case_ , custom_objects={main_layer_class.__name__: main_layer_class} )
assert isinstance(snake_case_ , tf.keras.Model )
__UpperCamelCase : str = model(snake_case_ )
self.assert_outputs_same(snake_case_ , snake_case_ )
@slow
def _lowerCamelCase ( self :int ) -> Any:
# make mask reproducible
np.random.seed(2 )
__UpperCamelCase , __UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
__UpperCamelCase : str = int((config.image_size // config.patch_size) ** 2 )
__UpperCamelCase : Optional[Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
for model_class in self.all_model_classes:
__UpperCamelCase : int = model_class(snake_case_ )
__UpperCamelCase : Optional[Any] = self._prepare_for_class(snake_case_ , snake_case_ )
__UpperCamelCase : Union[str, Any] = model(snake_case_ , noise=snake_case_ )
if model_class.__name__ == "TFViTMAEModel":
__UpperCamelCase : Optional[Any] = outputs.last_hidden_state.numpy()
__UpperCamelCase : Optional[int] = 0
else:
__UpperCamelCase : Optional[Any] = outputs.logits.numpy()
__UpperCamelCase : Optional[int] = 0
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(snake_case_ , saved_model=snake_case_ )
__UpperCamelCase : Tuple = model_class.from_pretrained(snake_case_ )
__UpperCamelCase : Dict = model(snake_case_ , noise=snake_case_ )
if model_class.__name__ == "TFViTMAEModel":
__UpperCamelCase : Dict = after_outputs["last_hidden_state"].numpy()
__UpperCamelCase : List[str] = 0
else:
__UpperCamelCase : Any = after_outputs["logits"].numpy()
__UpperCamelCase : Tuple = 0
__UpperCamelCase : List[Any] = np.amax(np.abs(out_a - out_a ) )
self.assertLessEqual(snake_case_ , 1E-5 )
def _lowerCamelCase ( self :List[Any] ) -> Optional[Any]:
# make mask reproducible
np.random.seed(2 )
__UpperCamelCase , __UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common()
__UpperCamelCase : Tuple = int((config.image_size // config.patch_size) ** 2 )
__UpperCamelCase : Optional[Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
for model_class in self.all_model_classes:
__UpperCamelCase : Optional[int] = model_class(snake_case_ )
__UpperCamelCase : str = self._prepare_for_class(snake_case_ , snake_case_ )
__UpperCamelCase : int = model(snake_case_ , noise=snake_case_ )
__UpperCamelCase : Optional[Any] = model.get_config()
# make sure that returned config is jsonifiable, which is required by keras
json.dumps(snake_case_ )
__UpperCamelCase : Dict = model_class.from_config(model.get_config() )
# make sure it also accepts a normal config
__UpperCamelCase : Any = model_class.from_config(model.config )
__UpperCamelCase : Any = new_model(snake_case_ ) # Build model
new_model.set_weights(model.get_weights() )
__UpperCamelCase : Union[str, Any] = new_model(snake_case_ , noise=snake_case_ )
self.assert_outputs_same(snake_case_ , snake_case_ )
@unittest.skip(
reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." )
def _lowerCamelCase ( self :Tuple ) -> Optional[int]:
pass
@unittest.skip(reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load" )
def _lowerCamelCase ( self :List[Any] ) -> List[Any]:
pass
@slow
def _lowerCamelCase ( self :Any ) -> Optional[int]:
__UpperCamelCase : Union[str, Any] = TFViTMAEModel.from_pretrained("google/vit-base-patch16-224" )
self.assertIsNotNone(snake_case_ )
def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
'''simple docstring'''
__UpperCamelCase : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
return image
@require_tf
@require_vision
class lowerCamelCase__ ( unittest.TestCase):
'''simple docstring'''
@cached_property
def _lowerCamelCase ( self :Optional[int] ) -> int:
return ViTImageProcessor.from_pretrained("facebook/vit-mae-base" ) if is_vision_available() else None
@slow
def _lowerCamelCase ( self :Optional[Any] ) -> Dict:
# make random mask reproducible across the PT and TF model
np.random.seed(2 )
__UpperCamelCase : Union[str, Any] = TFViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base" )
__UpperCamelCase : str = self.default_image_processor
__UpperCamelCase : Union[str, Any] = prepare_img()
__UpperCamelCase : str = image_processor(images=snake_case_ , return_tensors="tf" )
# prepare a noise vector that will be also used for testing the TF model
# (this way we can ensure that the PT and TF models operate on the same inputs)
__UpperCamelCase : Tuple = ViTMAEConfig()
__UpperCamelCase : Optional[Any] = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 )
__UpperCamelCase : Dict = np.random.uniform(size=(1, num_patches) )
# forward pass
__UpperCamelCase : Tuple = model(**snake_case_ , noise=snake_case_ )
# verify the logits
__UpperCamelCase : List[str] = tf.convert_to_tensor([1, 1_9_6, 7_6_8] )
self.assertEqual(outputs.logits.shape , snake_case_ )
__UpperCamelCase : Optional[Any] = tf.convert_to_tensor(
[[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] )
tf.debugging.assert_near(outputs.logits[0, :3, :3] , snake_case_ , atol=1E-4 ) | 720 |
from __future__ import annotations
import time
from collections.abc import Sequence
from random import randint
from matplotlib import pyplot as plt
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Sequence[float] , _lowerCamelCase : int , _lowerCamelCase : int) -> tuple[int | None, int | None, float]:
'''simple docstring'''
if not arr:
return None, None, 0
if low == high:
return low, high, arr[low]
__UpperCamelCase : Tuple = (low + high) // 2
__UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Dict = max_subarray(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase)
__UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Optional[int] = max_subarray(_lowerCamelCase , mid + 1 , _lowerCamelCase)
__UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Dict = max_cross_sum(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase)
if left_sum >= right_sum and left_sum >= cross_sum:
return left_low, left_high, left_sum
elif right_sum >= left_sum and right_sum >= cross_sum:
return right_low, right_high, right_sum
return cross_left, cross_right, cross_sum
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Sequence[float] , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : int) -> tuple[int, int, float]:
'''simple docstring'''
__UpperCamelCase , __UpperCamelCase : Union[str, Any] = float("-inf"), -1
__UpperCamelCase , __UpperCamelCase : Optional[int] = float("-inf"), -1
__UpperCamelCase : int | float = 0
for i in range(_lowerCamelCase , low - 1 , -1):
summ += arr[i]
if summ > left_sum:
__UpperCamelCase : Tuple = summ
__UpperCamelCase : Optional[int] = i
__UpperCamelCase : Union[str, Any] = 0
for i in range(mid + 1 , high + 1):
summ += arr[i]
if summ > right_sum:
__UpperCamelCase : Union[str, Any] = summ
__UpperCamelCase : Optional[int] = i
return max_left, max_right, (left_sum + right_sum)
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int) -> float:
'''simple docstring'''
__UpperCamelCase : Tuple = [randint(1 , _lowerCamelCase) for _ in range(_lowerCamelCase)]
__UpperCamelCase : Optional[Any] = time.time()
max_subarray(_lowerCamelCase , 0 , input_size - 1)
__UpperCamelCase : Any = time.time()
return end - start
def _SCREAMING_SNAKE_CASE ( ) -> None:
'''simple docstring'''
__UpperCamelCase : Dict = [10, 100, 1_000, 10_000, 50_000, 100_000, 200_000, 300_000, 400_000, 500_000]
__UpperCamelCase : Union[str, Any] = [time_max_subarray(_lowerCamelCase) for input_size in input_sizes]
print("No of Inputs\t\tTime Taken")
for input_size, runtime in zip(_lowerCamelCase , _lowerCamelCase):
print(_lowerCamelCase , "\t\t" , _lowerCamelCase)
plt.plot(_lowerCamelCase , _lowerCamelCase)
plt.xlabel("Number of Inputs")
plt.ylabel("Time taken in seconds")
plt.show()
if __name__ == "__main__":
from doctest import testmod
testmod() | 94 | 0 |
"""simple docstring"""
import sys
from .dependency_versions_table import deps
from .utils.versions import require_version, require_version_core
# define which module versions we always want to check at run time
# (usually the ones defined in `install_requires` in setup.py)
#
# order specific notes:
# - tqdm must be checked before tokenizers
lowerCAmelCase__ = '''python tqdm regex requests packaging filelock numpy tokenizers'''.split()
if sys.version_info < (3, 7):
pkgs_to_check_at_runtime.append('''dataclasses''')
if sys.version_info < (3, 8):
pkgs_to_check_at_runtime.append('''importlib_metadata''')
for pkg in pkgs_to_check_at_runtime:
if pkg in deps:
if pkg == "tokenizers":
# must be loaded here, or else tqdm check may fail
from .utils import is_tokenizers_available
if not is_tokenizers_available():
continue # not required, check version only if installed
require_version_core(deps[pkg])
else:
raise ValueError(F"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""")
def snake_case_ ( A_ : List[Any], A_ : int=None ):
'''simple docstring'''
require_version(deps[pkg], A_ )
| 83 |
"""simple docstring"""
import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union
import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn
import transformers
from transformers import (
HfArgumentParser,
Trainer,
TrainingArguments,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaForCTC,
WavaVecaProcessor,
is_apex_available,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process
if is_apex_available():
from apex import amp
if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'):
lowercase_ = True
from torch.cuda.amp import autocast
lowercase_ = logging.getLogger(__name__)
def UpperCAmelCase ( _lowercase : Optional[Any]=None , _lowercase : str=None ) -> List[str]:
"""simple docstring"""
return field(default_factory=lambda: default , metadata=_lowercase )
@dataclass
class __a :
lowerCamelCase : str =field(
metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} )
lowerCamelCase : Optional[str] =field(
default=__snake_case , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , )
lowerCamelCase : Optional[bool] =field(
default=__snake_case , metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} )
lowerCamelCase : Optional[float] =field(
default=0.1 , metadata={'help': 'The dropout ratio for the attention probabilities.'} )
lowerCamelCase : Optional[float] =field(
default=0.1 , metadata={'help': 'The dropout ratio for activations inside the fully connected layer.'} )
lowerCamelCase : Optional[float] =field(
default=0.1 , metadata={
'help': 'The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'
} , )
lowerCamelCase : Optional[float] =field(
default=0.1 , metadata={'help': 'The dropout probabilitiy for all 1D convolutional layers in feature extractor.'} , )
lowerCamelCase : Optional[float] =field(
default=0.05 , metadata={
'help': (
'Propability of each feature vector along the time axis to be chosen as the start of the vector'
'span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'
'vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'
)
} , )
lowerCamelCase : Optional[float] =field(default=0.0 , metadata={'help': 'The LayerDrop probability.'} )
@dataclass
class __a :
lowerCamelCase : Optional[str] =field(
default=__snake_case , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} )
lowerCamelCase : Optional[str] =field(
default='train+validation' , metadata={
'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\''
} , )
lowerCamelCase : bool =field(
default=__snake_case , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} )
lowerCamelCase : Optional[int] =field(
default=__snake_case , metadata={'help': 'The number of processes to use for the preprocessing.'} , )
lowerCamelCase : Optional[int] =field(
default=__snake_case , metadata={
'help': (
'For debugging purposes or quicker training, truncate the number of training examples to this '
'value if set.'
)
} , )
lowerCamelCase : Optional[int] =field(
default=__snake_case , metadata={
'help': (
'For debugging purposes or quicker training, truncate the number of validation examples to this '
'value if set.'
)
} , )
lowerCamelCase : List[str] =list_field(
default=[',', '?', '.', '!', '-', ';', ':', '""', '%', '\'', '"', '�'] , metadata={'help': 'A list of characters to remove from the transcripts.'} , )
@dataclass
class __a :
lowerCamelCase : WavaVecaProcessor
lowerCamelCase : Union[bool, str] =True
lowerCamelCase : Optional[int] =None
lowerCamelCase : Optional[int] =None
lowerCamelCase : Optional[int] =None
lowerCamelCase : Optional[int] =None
def __call__( self , UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase_ = [{'''input_values''': feature['''input_values''']} for feature in features]
lowerCAmelCase_ = [{'''input_ids''': feature['''labels''']} for feature in features]
lowerCAmelCase_ = self.processor.pad(
UpperCAmelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , )
lowerCAmelCase_ = self.processor.pad(
labels=UpperCAmelCase , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors='''pt''' , )
# replace padding with -100 to ignore loss correctly
lowerCAmelCase_ = labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1 ) , -100 )
lowerCAmelCase_ = labels
return batch
class __a ( __snake_case ):
def lowerCamelCase_ ( self , UpperCAmelCase , UpperCAmelCase ):
'''simple docstring'''
model.train()
lowerCAmelCase_ = self._prepare_inputs(UpperCAmelCase )
if self.use_amp:
with autocast():
lowerCAmelCase_ = self.compute_loss(UpperCAmelCase , UpperCAmelCase )
else:
lowerCAmelCase_ = self.compute_loss(UpperCAmelCase , UpperCAmelCase )
if self.args.n_gpu > 1:
if model.module.config.ctc_loss_reduction == "mean":
lowerCAmelCase_ = loss.mean()
elif model.module.config.ctc_loss_reduction == "sum":
lowerCAmelCase_ = loss.sum() / (inputs['''labels'''] >= 0).sum()
else:
raise ValueError(F"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']""" )
if self.args.gradient_accumulation_steps > 1:
lowerCAmelCase_ = loss / self.args.gradient_accumulation_steps
if self.use_amp:
self.scaler.scale(UpperCAmelCase ).backward()
elif self.use_apex:
with amp.scale_loss(UpperCAmelCase , self.optimizer ) as scaled_loss:
scaled_loss.backward()
elif self.deepspeed:
self.deepspeed.backward(UpperCAmelCase )
else:
loss.backward()
return loss.detach()
def UpperCAmelCase ( ) -> Tuple:
"""simple docstring"""
lowerCAmelCase_ = 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.
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = parser.parse_args_into_dataclasses()
# Detecting last checkpoint.
lowerCAmelCase_ = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
lowerCAmelCase_ = get_last_checkpoint(training_args.output_dir )
if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0:
raise ValueError(
F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
'''Use --overwrite_output_dir to overcome.''' )
elif last_checkpoint is not None:
logger.info(
F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
'''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' )
# Setup logging
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , )
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN )
# Log on each process the small summary:
logger.warning(
F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
+ F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" )
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank ):
transformers.utils.logging.set_verbosity_info()
logger.info('''Training/evaluation parameters %s''' , _lowercase )
# Set seed before initializing model.
set_seed(training_args.seed )
# Get the datasets:
lowerCAmelCase_ = datasets.load_dataset(
'''common_voice''' , data_args.dataset_config_name , split=data_args.train_split_name )
lowerCAmelCase_ = datasets.load_dataset('''common_voice''' , data_args.dataset_config_name , split='''test''' )
# Create and save tokenizer
lowerCAmelCase_ = F"""[{"".join(data_args.chars_to_ignore )}]"""
def remove_special_characters(_lowercase : List[str] ):
lowerCAmelCase_ = re.sub(_lowercase , '''''' , batch['''sentence'''] ).lower() + ''' '''
return batch
lowerCAmelCase_ = train_dataset.map(_lowercase , remove_columns=['''sentence'''] )
lowerCAmelCase_ = eval_dataset.map(_lowercase , remove_columns=['''sentence'''] )
def extract_all_chars(_lowercase : str ):
lowerCAmelCase_ = ''' '''.join(batch['''text'''] )
lowerCAmelCase_ = list(set(_lowercase ) )
return {"vocab": [vocab], "all_text": [all_text]}
lowerCAmelCase_ = train_dataset.map(
_lowercase , batched=_lowercase , batch_size=-1 , keep_in_memory=_lowercase , remove_columns=train_dataset.column_names , )
lowerCAmelCase_ = train_dataset.map(
_lowercase , batched=_lowercase , batch_size=-1 , keep_in_memory=_lowercase , remove_columns=eval_dataset.column_names , )
lowerCAmelCase_ = list(set(vocab_train['''vocab'''][0] ) | set(vocab_test['''vocab'''][0] ) )
lowerCAmelCase_ = {v: k for k, v in enumerate(_lowercase )}
lowerCAmelCase_ = vocab_dict[''' ''']
del vocab_dict[" "]
lowerCAmelCase_ = len(_lowercase )
lowerCAmelCase_ = len(_lowercase )
with open('''vocab.json''' , '''w''' ) as vocab_file:
json.dump(_lowercase , _lowercase )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
lowerCAmelCase_ = WavaVecaCTCTokenizer(
'''vocab.json''' , unk_token='''[UNK]''' , pad_token='''[PAD]''' , word_delimiter_token='''|''' , )
lowerCAmelCase_ = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0.0 , do_normalize=_lowercase , return_attention_mask=_lowercase )
lowerCAmelCase_ = WavaVecaProcessor(feature_extractor=_lowercase , tokenizer=_lowercase )
lowerCAmelCase_ = WavaVecaForCTC.from_pretrained(
model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction='''mean''' , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer ) , )
if data_args.max_train_samples is not None:
lowerCAmelCase_ = min(len(_lowercase ) , data_args.max_train_samples )
lowerCAmelCase_ = train_dataset.select(range(_lowercase ) )
if data_args.max_val_samples is not None:
lowerCAmelCase_ = eval_dataset.select(range(data_args.max_val_samples ) )
lowerCAmelCase_ = torchaudio.transforms.Resample(4_8_0_0_0 , 1_6_0_0_0 )
# Preprocessing the datasets.
# We need to read the aduio files as arrays and tokenize the targets.
def speech_file_to_array_fn(_lowercase : Union[str, Any] ):
lowerCAmelCase_ , lowerCAmelCase_ = torchaudio.load(batch['''path'''] )
lowerCAmelCase_ = resampler(_lowercase ).squeeze().numpy()
lowerCAmelCase_ = 1_6_0_0_0
lowerCAmelCase_ = batch['''text''']
return batch
lowerCAmelCase_ = train_dataset.map(
_lowercase , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , )
lowerCAmelCase_ = eval_dataset.map(
_lowercase , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , )
def prepare_dataset(_lowercase : str ):
# check that all files have the correct sampling rate
assert (
len(set(batch['''sampling_rate'''] ) ) == 1
), F"""Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}."""
lowerCAmelCase_ = processor(
audio=batch['''speech'''] , text=batch['''target_text'''] , sampling_rate=batch['''sampling_rate'''][0] )
batch.update(_lowercase )
return batch
lowerCAmelCase_ = train_dataset.map(
_lowercase , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_lowercase , num_proc=data_args.preprocessing_num_workers , )
lowerCAmelCase_ = eval_dataset.map(
_lowercase , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_lowercase , num_proc=data_args.preprocessing_num_workers , )
# Metric
lowerCAmelCase_ = datasets.load_metric('''wer''' )
def compute_metrics(_lowercase : Optional[int] ):
lowerCAmelCase_ = pred.predictions
lowerCAmelCase_ = np.argmax(_lowercase , axis=-1 )
lowerCAmelCase_ = processor.tokenizer.pad_token_id
lowerCAmelCase_ = processor.batch_decode(_lowercase )
# we do not want to group tokens when computing the metrics
lowerCAmelCase_ = processor.batch_decode(pred.label_ids , group_tokens=_lowercase )
lowerCAmelCase_ = wer_metric.compute(predictions=_lowercase , references=_lowercase )
return {"wer": wer}
if model_args.freeze_feature_extractor:
model.freeze_feature_extractor()
# Data collator
lowerCAmelCase_ = DataCollatorCTCWithPadding(processor=_lowercase , padding=_lowercase )
# Initialize our Trainer
lowerCAmelCase_ = CTCTrainer(
model=_lowercase , data_collator=_lowercase , args=_lowercase , compute_metrics=_lowercase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , )
# Training
if training_args.do_train:
if last_checkpoint is not None:
lowerCAmelCase_ = last_checkpoint
elif os.path.isdir(model_args.model_name_or_path ):
lowerCAmelCase_ = model_args.model_name_or_path
else:
lowerCAmelCase_ = None
# Save the feature_extractor and the tokenizer
if is_main_process(training_args.local_rank ):
processor.save_pretrained(training_args.output_dir )
lowerCAmelCase_ = trainer.train(resume_from_checkpoint=_lowercase )
trainer.save_model()
lowerCAmelCase_ = train_result.metrics
lowerCAmelCase_ = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowercase )
)
lowerCAmelCase_ = min(_lowercase , len(_lowercase ) )
trainer.log_metrics('''train''' , _lowercase )
trainer.save_metrics('''train''' , _lowercase )
trainer.save_state()
# Evaluation
lowerCAmelCase_ = {}
if training_args.do_eval:
logger.info('''*** Evaluate ***''' )
lowerCAmelCase_ = trainer.evaluate()
lowerCAmelCase_ = data_args.max_val_samples if data_args.max_val_samples is not None else len(_lowercase )
lowerCAmelCase_ = min(_lowercase , len(_lowercase ) )
trainer.log_metrics('''eval''' , _lowercase )
trainer.save_metrics('''eval''' , _lowercase )
return results
if __name__ == "__main__":
main() | 552 | 0 |
def A__ ( lowercase: list, lowercase: list, lowercase: int, lowercase: int, lowercase: int ) -> int:
if index == number_of_items:
return 0
A : Any =0
A : Optional[Any] =0
A : Dict =knapsack(lowercase, lowercase, lowercase, lowercase, index + 1 )
if weights[index] <= max_weight:
A : List[Any] =values[index] + knapsack(
lowercase, lowercase, lowercase, max_weight - weights[index], index + 1 )
return max(lowercase, lowercase )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 661 | from typing import List
from .keymap import KEYMAP, get_character
def A__ ( lowercase: str ) -> List[str]:
def decorator(lowercase: int ):
A : Tuple =getattr(lowercase, 'handle_key', [] )
handle += [key]
setattr(lowercase, 'handle_key', lowercase )
return func
return decorator
def A__ ( *lowercase: List[str] ) -> Dict:
def decorator(lowercase: Union[str, Any] ):
A : Optional[int] =getattr(lowercase, 'handle_key', [] )
handle += keys
setattr(lowercase, 'handle_key', lowercase )
return func
return decorator
class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ):
'''simple docstring'''
def __new__( cls : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any:
A : Dict =super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
if not hasattr(SCREAMING_SNAKE_CASE__ , 'key_handler' ):
setattr(SCREAMING_SNAKE_CASE__ , 'key_handler' , {} )
setattr(SCREAMING_SNAKE_CASE__ , 'handle_input' , KeyHandler.handle_input )
for value in attrs.values():
A : Optional[Any] =getattr(SCREAMING_SNAKE_CASE__ , 'handle_key' , [] )
for key in handled_keys:
A : str =value
return new_cls
@staticmethod
def SCREAMING_SNAKE_CASE_ ( cls : str ) -> Any:
A : str =get_character()
if char != KEYMAP["undefined"]:
A : List[str] =ord(SCREAMING_SNAKE_CASE__ )
A : List[str] =cls.key_handler.get(SCREAMING_SNAKE_CASE__ )
if handler:
A : List[str] =char
return handler(cls )
else:
return None
def A__ ( cls: Optional[int] ) -> str:
return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
| 661 | 1 |
import tempfile
import unittest
import numpy as np
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import BertConfig, is_flax_available
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax
if is_flax_available():
import os
from flax.core.frozen_dict import unfreeze
from flax.traverse_util import flatten_dict
from transformers import FlaxBertModel
__A = "0.12" # assumed parallelism: 8
@require_flax
@is_staging_test
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@classmethod
def SCREAMING_SNAKE_CASE_ (cls : str) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Optional[int] =TOKEN
HfFolder.save_token(UpperCAmelCase_)
@classmethod
def SCREAMING_SNAKE_CASE_ (cls : Optional[Any]) ->int:
'''simple docstring'''
try:
delete_repo(token=cls._token , repo_id="test-model-flax")
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-model-flax-org")
except HTTPError:
pass
def SCREAMING_SNAKE_CASE_ (self : Any) ->Tuple:
'''simple docstring'''
lowerCamelCase__: str =BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37)
lowerCamelCase__: Dict =FlaxBertModel(UpperCAmelCase_)
model.push_to_hub("test-model-flax" , use_auth_token=self._token)
lowerCamelCase__: Union[str, Any] =FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax""")
lowerCamelCase__: str =flatten_dict(unfreeze(model.params))
lowerCamelCase__: Union[str, Any] =flatten_dict(unfreeze(new_model.params))
for key in base_params.keys():
lowerCamelCase__: List[str] =(base_params[key] - new_params[key]).sum().item()
self.assertLessEqual(UpperCAmelCase_ , 1E-3 , msg=F"""{key} not identical""")
# Reset repo
delete_repo(token=self._token , repo_id="test-model-flax")
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(UpperCAmelCase_ , repo_id="test-model-flax" , push_to_hub=UpperCAmelCase_ , use_auth_token=self._token)
lowerCamelCase__: Tuple =FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax""")
lowerCamelCase__: Optional[int] =flatten_dict(unfreeze(model.params))
lowerCamelCase__: List[str] =flatten_dict(unfreeze(new_model.params))
for key in base_params.keys():
lowerCamelCase__: List[Any] =(base_params[key] - new_params[key]).sum().item()
self.assertLessEqual(UpperCAmelCase_ , 1E-3 , msg=F"""{key} not identical""")
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->str:
'''simple docstring'''
lowerCamelCase__: Any =BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37)
lowerCamelCase__: List[str] =FlaxBertModel(UpperCAmelCase_)
model.push_to_hub("valid_org/test-model-flax-org" , use_auth_token=self._token)
lowerCamelCase__: Optional[int] =FlaxBertModel.from_pretrained("valid_org/test-model-flax-org")
lowerCamelCase__: int =flatten_dict(unfreeze(model.params))
lowerCamelCase__: Any =flatten_dict(unfreeze(new_model.params))
for key in base_params.keys():
lowerCamelCase__: List[str] =(base_params[key] - new_params[key]).sum().item()
self.assertLessEqual(UpperCAmelCase_ , 1E-3 , msg=F"""{key} not identical""")
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-model-flax-org")
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(
UpperCAmelCase_ , repo_id="valid_org/test-model-flax-org" , push_to_hub=UpperCAmelCase_ , use_auth_token=self._token)
lowerCamelCase__: int =FlaxBertModel.from_pretrained("valid_org/test-model-flax-org")
lowerCamelCase__: Union[str, Any] =flatten_dict(unfreeze(model.params))
lowerCamelCase__: Union[str, Any] =flatten_dict(unfreeze(new_model.params))
for key in base_params.keys():
lowerCamelCase__: Tuple =(base_params[key] - new_params[key]).sum().item()
self.assertLessEqual(UpperCAmelCase_ , 1E-3 , msg=F"""{key} not identical""")
def lowerCAmelCase_ ( __a , __a ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase__: int =True
lowerCamelCase__: Any =flatten_dict(modela.params )
lowerCamelCase__: Any =flatten_dict(modela.params )
for key in flat_params_a.keys():
if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1e-4:
lowerCamelCase__: Dict =False
return models_are_equal
@require_flax
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : str) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only")
lowerCamelCase__: str =FlaxBertModel(UpperCAmelCase_)
lowerCamelCase__: int ="bert"
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(os.path.join(UpperCAmelCase_ , UpperCAmelCase_))
with self.assertRaises(UpperCAmelCase_):
lowerCamelCase__: Tuple =FlaxBertModel.from_pretrained(UpperCAmelCase_)
lowerCamelCase__: Optional[int] =FlaxBertModel.from_pretrained(UpperCAmelCase_ , subfolder=UpperCAmelCase_)
self.assertTrue(check_models_equal(UpperCAmelCase_ , UpperCAmelCase_))
def SCREAMING_SNAKE_CASE_ (self : Any) ->Any:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only")
lowerCamelCase__: List[Any] =FlaxBertModel(UpperCAmelCase_)
lowerCamelCase__: int ="bert"
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(os.path.join(UpperCAmelCase_ , UpperCAmelCase_) , max_shard_size="10KB")
with self.assertRaises(UpperCAmelCase_):
lowerCamelCase__: Dict =FlaxBertModel.from_pretrained(UpperCAmelCase_)
lowerCamelCase__: str =FlaxBertModel.from_pretrained(UpperCAmelCase_ , subfolder=UpperCAmelCase_)
self.assertTrue(check_models_equal(UpperCAmelCase_ , UpperCAmelCase_))
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: str ="bert"
lowerCamelCase__: Optional[Any] ="hf-internal-testing/tiny-random-bert-subfolder"
with self.assertRaises(UpperCAmelCase_):
lowerCamelCase__: Union[str, Any] =FlaxBertModel.from_pretrained(UpperCAmelCase_)
lowerCamelCase__: Tuple =FlaxBertModel.from_pretrained(UpperCAmelCase_ , subfolder=UpperCAmelCase_)
self.assertIsNotNone(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: List[str] ="bert"
lowerCamelCase__: Optional[int] ="hf-internal-testing/tiny-random-bert-sharded-subfolder"
with self.assertRaises(UpperCAmelCase_):
lowerCamelCase__: Dict =FlaxBertModel.from_pretrained(UpperCAmelCase_)
lowerCamelCase__: Any =FlaxBertModel.from_pretrained(UpperCAmelCase_ , subfolder=UpperCAmelCase_)
self.assertIsNotNone(UpperCAmelCase_)
| 59 |
'''simple docstring'''
from collections import OrderedDict
from typing import Any, Mapping, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...feature_extraction_utils import FeatureExtractionMixin
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import TensorType, logging
lowerCAmelCase : Any = logging.get_logger(__name__)
lowerCAmelCase : Optional[int] = {
'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json',
# See all Perceiver models at https://huggingface.co/models?filter=perceiver
}
class SCREAMING_SNAKE_CASE__ ( snake_case_):
lowerCAmelCase_ = """perceiver"""
def __init__( self , A_=256 , A_=1280 , A_=768 , A_=1 , A_=26 , A_=8 , A_=8 , A_=None , A_=None , A_="kv" , A_=1 , A_=1 , A_="gelu" , A_=0.1 , A_=0.02 , A_=1e-12 , A_=True , A_=262 , A_=2048 , A_=56 , A_=[368, 496] , A_=16 , A_=1920 , A_=16 , A_=[1, 16, 224, 224] , **A_ , )-> str:
'''simple docstring'''
super().__init__(**A_ )
UpperCamelCase = num_latents
UpperCamelCase = d_latents
UpperCamelCase = d_model
UpperCamelCase = num_blocks
UpperCamelCase = num_self_attends_per_block
UpperCamelCase = num_self_attention_heads
UpperCamelCase = num_cross_attention_heads
UpperCamelCase = qk_channels
UpperCamelCase = v_channels
UpperCamelCase = cross_attention_shape_for_attention
UpperCamelCase = self_attention_widening_factor
UpperCamelCase = cross_attention_widening_factor
UpperCamelCase = hidden_act
UpperCamelCase = attention_probs_dropout_prob
UpperCamelCase = initializer_range
UpperCamelCase = layer_norm_eps
UpperCamelCase = use_query_residual
# masked language modeling attributes
UpperCamelCase = vocab_size
UpperCamelCase = max_position_embeddings
# image classification attributes
UpperCamelCase = image_size
# flow attributes
UpperCamelCase = train_size
# multimodal autoencoding attributes
UpperCamelCase = num_frames
UpperCamelCase = audio_samples_per_frame
UpperCamelCase = samples_per_patch
UpperCamelCase = output_shape
class SCREAMING_SNAKE_CASE__ ( snake_case_):
@property
def UpperCAmelCase_ ( self )-> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
if self.task == "multiple-choice":
UpperCamelCase = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
UpperCamelCase = {0: 'batch', 1: 'sequence'}
return OrderedDict(
[
('inputs', dynamic_axis),
('attention_mask', dynamic_axis),
] )
@property
def UpperCAmelCase_ ( self )-> float:
'''simple docstring'''
return 1e-4
def UpperCAmelCase_ ( self , A_ , A_ = -1 , A_ = -1 , A_ = -1 , A_ = False , A_ = None , A_ = 3 , A_ = 40 , A_ = 40 , )-> Mapping[str, Any]:
'''simple docstring'''
if isinstance(A_ , A_ ):
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
UpperCamelCase = compute_effective_axis_dimension(
A_ , 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
UpperCamelCase = preprocessor.num_special_tokens_to_add(A_ )
UpperCamelCase = compute_effective_axis_dimension(
A_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=A_ )
# Generate dummy inputs according to compute batch and sequence
UpperCamelCase = [' '.join(['a'] ) * seq_length] * batch_size
UpperCamelCase = dict(preprocessor(A_ , return_tensors=A_ ) )
UpperCamelCase = inputs.pop('input_ids' )
return inputs
elif isinstance(A_ , A_ ) and preprocessor.model_input_names[0] == "pixel_values":
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
UpperCamelCase = compute_effective_axis_dimension(A_ , fixed_dimension=OnnxConfig.default_fixed_batch )
UpperCamelCase = self._generate_dummy_images(A_ , A_ , A_ , A_ )
UpperCamelCase = dict(preprocessor(images=A_ , return_tensors=A_ ) )
UpperCamelCase = inputs.pop('pixel_values' )
return inputs
else:
raise ValueError(
'Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.' )
| 3 | 0 |
'''simple docstring'''
def _lowerCamelCase (__lowerCamelCase : int = 100 ) -> int:
a__ = set()
a__ = 0
a__ = n + 1 # maximum limit
for a in range(2 , __lowerCamelCase ):
for b in range(2 , __lowerCamelCase ):
a__ = a**b # calculates the current power
collect_powers.add(__lowerCamelCase ) # adds the result to the set
return len(__lowerCamelCase )
if __name__ == "__main__":
print("Number of terms ", solution(int(str(input()).strip())))
| 289 |
'''simple docstring'''
import argparse
import os
import re
import packaging.version
lowerCAmelCase_ : Optional[int] = "examples/"
lowerCAmelCase_ : Optional[int] = {
"examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"),
"init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"),
"setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","),
"doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"),
}
lowerCAmelCase_ : Optional[int] = {
"init": "src/transformers/__init__.py",
"setup": "setup.py",
}
lowerCAmelCase_ : List[Any] = "README.md"
def _lowerCamelCase (__lowerCamelCase : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[Any] ) -> str:
with open(__lowerCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f:
a__ = f.read()
a__ , a__ = REPLACE_PATTERNS[pattern]
a__ = replace.replace("VERSION" , __lowerCamelCase )
a__ = re_pattern.sub(__lowerCamelCase , __lowerCamelCase )
with open(__lowerCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f:
f.write(__lowerCamelCase )
def _lowerCamelCase (__lowerCamelCase : Union[str, Any] ) -> Dict:
for folder, directories, fnames in os.walk(__lowerCamelCase ):
# Removing some of the folders with non-actively maintained examples from the walk
if "research_projects" in directories:
directories.remove("research_projects" )
if "legacy" in directories:
directories.remove("legacy" )
for fname in fnames:
if fname.endswith(".py" ):
update_version_in_file(os.path.join(__lowerCamelCase , __lowerCamelCase ) , __lowerCamelCase , pattern="examples" )
def _lowerCamelCase (__lowerCamelCase : int , __lowerCamelCase : Any=False ) -> Optional[Any]:
for pattern, fname in REPLACE_FILES.items():
update_version_in_file(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
if not patch:
update_version_in_examples(__lowerCamelCase )
def _lowerCamelCase () -> Tuple:
a__ = "🤗 Transformers currently provides the following architectures"
a__ = "1. Want to contribute a new model?"
with open(__lowerCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f:
a__ = f.readlines()
# Find the start of the list.
a__ = 0
while not lines[start_index].startswith(_start_prompt ):
start_index += 1
start_index += 1
a__ = start_index
# Update the lines in the model list.
while not lines[index].startswith(_end_prompt ):
if lines[index].startswith("1." ):
a__ = lines[index].replace(
"https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , )
index += 1
with open(__lowerCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f:
f.writelines(__lowerCamelCase )
def _lowerCamelCase () -> Tuple:
with open(REPLACE_FILES["init"] , "r" ) as f:
a__ = f.read()
a__ = REPLACE_PATTERNS["init"][0].search(__lowerCamelCase ).groups()[0]
return packaging.version.parse(__lowerCamelCase )
def _lowerCamelCase (__lowerCamelCase : Any=False ) -> int:
a__ = get_version()
if patch and default_version.is_devrelease:
raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" )
if default_version.is_devrelease:
a__ = default_version.base_version
elif patch:
a__ = f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}'''
else:
a__ = f'''{default_version.major}.{default_version.minor + 1}.0'''
# Now let's ask nicely if that's the right one.
a__ = input(f'''Which version are you releasing? [{default_version}]''' )
if len(__lowerCamelCase ) == 0:
a__ = default_version
print(f'''Updating version to {version}.''' )
global_version_update(__lowerCamelCase , patch=__lowerCamelCase )
if not patch:
print("Cleaning main README, don't forget to run `make fix-copies`." )
clean_main_ref_in_model_list()
def _lowerCamelCase () -> Tuple:
a__ = get_version()
a__ = f'''{current_version.major}.{current_version.minor + 1}.0.dev0'''
a__ = current_version.base_version
# Check with the user we got that right.
a__ = input(f'''Which version are we developing now? [{dev_version}]''' )
if len(__lowerCamelCase ) == 0:
a__ = dev_version
print(f'''Updating version to {version}.''' )
global_version_update(__lowerCamelCase )
print("Cleaning main README, don't forget to run `make fix-copies`." )
clean_main_ref_in_model_list()
if __name__ == "__main__":
lowerCAmelCase_ : List[str] = argparse.ArgumentParser()
parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
lowerCAmelCase_ : int = parser.parse_args()
if not args.post_release:
pre_release_work(patch=args.patch)
elif args.patch:
print("Nothing to do after a patch :-)")
else:
post_release_work()
| 289 | 1 |
import os
from argparse import ArgumentParser
from typing import List
import torch.utils.data
from datasets import Dataset, IterableDataset
from datasets.distributed import split_dataset_by_node
lowerCamelCase_ = 4
lowerCamelCase_ = 3
class __a ( snake_case__ ):
"""simple docstring"""
pass
def UpperCAmelCase_ ( __UpperCamelCase ):
for shard in shards:
for i in range(__SCREAMING_SNAKE_CASE ):
yield {"i": i, "shard": shard}
def UpperCAmelCase_ ( ):
SCREAMING_SNAKE_CASE__ =int(os.environ["""RANK"""] )
SCREAMING_SNAKE_CASE__ =int(os.environ["""WORLD_SIZE"""] )
SCREAMING_SNAKE_CASE__ =ArgumentParser()
parser.add_argument("""--streaming""", type=__SCREAMING_SNAKE_CASE )
parser.add_argument("""--local_rank""", type=__SCREAMING_SNAKE_CASE )
parser.add_argument("""--num_workers""", type=__SCREAMING_SNAKE_CASE, default=0 )
SCREAMING_SNAKE_CASE__ =parser.parse_args()
SCREAMING_SNAKE_CASE__ =args.streaming
SCREAMING_SNAKE_CASE__ =args.num_workers
SCREAMING_SNAKE_CASE__ ={"""shards""": [f"""shard_{shard_idx}""" for shard_idx in range(__SCREAMING_SNAKE_CASE )]}
SCREAMING_SNAKE_CASE__ =IterableDataset.from_generator(__SCREAMING_SNAKE_CASE, gen_kwargs=__SCREAMING_SNAKE_CASE )
if not streaming:
SCREAMING_SNAKE_CASE__ =Dataset.from_list(list(__SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE__ =split_dataset_by_node(__SCREAMING_SNAKE_CASE, rank=__SCREAMING_SNAKE_CASE, world_size=__SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE__ =torch.utils.data.DataLoader(__SCREAMING_SNAKE_CASE, num_workers=__SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE__ =NUM_SHARDS * NUM_ITEMS_PER_SHARD
SCREAMING_SNAKE_CASE__ =full_size // world_size
expected_local_size += int(rank < (full_size % world_size) )
SCREAMING_SNAKE_CASE__ =sum(1 for _ in dataloader )
if local_size != expected_local_size:
raise FailedTestError(f"""local_size {local_size} != expected_local_size {expected_local_size}""" )
if __name__ == "__main__":
main()
| 151 |
'''simple docstring'''
from abc import ABC, abstractmethod
from typing import List, Optional
class lowerCAmelCase_ ( snake_case__ ):
"""simple docstring"""
def __init__( self : List[Any] ):
'''simple docstring'''
self.test()
def __a ( self : str ):
'''simple docstring'''
__a = 0
__a = False
while not completed:
if counter == 1:
self.reset()
__a = self.advance()
if not self.does_advance(SCREAMING_SNAKE_CASE__ ):
raise Exception(
"""Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.""" )
__a , __a , __a = self.update(SCREAMING_SNAKE_CASE__ )
counter += 1
if counter > 1_0_0_0_0:
raise Exception("""update() does not fulfill the constraint.""" )
if self.remaining() != 0:
raise Exception("""Custom Constraint is not defined correctly.""" )
@abstractmethod
def __a ( self : Any ):
'''simple docstring'''
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def __a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int ):
'''simple docstring'''
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def __a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ):
'''simple docstring'''
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def __a ( self : Optional[int] ):
'''simple docstring'''
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def __a ( self : Dict ):
'''simple docstring'''
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def __a ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ):
'''simple docstring'''
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
class lowerCAmelCase_ ( snake_case__ ):
"""simple docstring"""
def __init__( self : str , SCREAMING_SNAKE_CASE__ : List[int] ):
'''simple docstring'''
super(SCREAMING_SNAKE_CASE__ , self ).__init__()
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or len(SCREAMING_SNAKE_CASE__ ) == 0:
raise ValueError(f'''`token_ids` has to be a non-empty list, but is {token_ids}.''' )
if any((not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or token_id < 0) for token_id in token_ids ):
raise ValueError(f'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''' )
__a = token_ids
__a = len(self.token_ids )
__a = -1 # the index of the currently fulfilled step
__a = False
def __a ( self : Tuple ):
'''simple docstring'''
if self.completed:
return None
return self.token_ids[self.fulfilled_idx + 1]
def __a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int ):
'''simple docstring'''
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE__ )}''' )
if self.completed:
return False
return token_id == self.token_ids[self.fulfilled_idx + 1]
def __a ( self : Dict , SCREAMING_SNAKE_CASE__ : int ):
'''simple docstring'''
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE__ )}''' )
__a = False
__a = False
__a = False
if self.does_advance(SCREAMING_SNAKE_CASE__ ):
self.fulfilled_idx += 1
__a = True
if self.fulfilled_idx == (self.seqlen - 1):
__a = True
__a = completed
else:
# failed to make progress.
__a = True
self.reset()
return stepped, completed, reset
def __a ( self : Any ):
'''simple docstring'''
__a = False
__a = 0
def __a ( self : int ):
'''simple docstring'''
return self.seqlen - (self.fulfilled_idx + 1)
def __a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict=False ):
'''simple docstring'''
__a = PhrasalConstraint(self.token_ids )
if stateful:
__a = self.seqlen
__a = self.fulfilled_idx
__a = self.completed
return new_constraint
class lowerCAmelCase_ :
"""simple docstring"""
def __init__( self : str , SCREAMING_SNAKE_CASE__ : List[List[int]] , SCREAMING_SNAKE_CASE__ : Optional[int]=True ):
'''simple docstring'''
__a = max([len(SCREAMING_SNAKE_CASE__ ) for one in nested_token_ids] )
__a = {}
for token_ids in nested_token_ids:
__a = root
for tidx, token_id in enumerate(SCREAMING_SNAKE_CASE__ ):
if token_id not in level:
__a = {}
__a = level[token_id]
if no_subsets and self.has_subsets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError(
"""Each list in `nested_token_ids` can't be a complete subset of another list, but is"""
f''' {nested_token_ids}.''' )
__a = root
def __a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict ):
'''simple docstring'''
__a = self.trie
for current_token in current_seq:
__a = start[current_token]
__a = list(start.keys() )
return next_tokens
def __a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ):
'''simple docstring'''
__a = self.next_tokens(SCREAMING_SNAKE_CASE__ )
return len(SCREAMING_SNAKE_CASE__ ) == 0
def __a ( self : Any , SCREAMING_SNAKE_CASE__ : Dict ):
'''simple docstring'''
__a = list(root.values() )
if len(SCREAMING_SNAKE_CASE__ ) == 0:
return 1
else:
return sum([self.count_leaves(SCREAMING_SNAKE_CASE__ ) for nn in next_nodes] )
def __a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ):
'''simple docstring'''
__a = self.count_leaves(SCREAMING_SNAKE_CASE__ )
return len(SCREAMING_SNAKE_CASE__ ) != leaf_count
class lowerCAmelCase_ ( snake_case__ ):
"""simple docstring"""
def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : List[List[int]] ):
'''simple docstring'''
super(SCREAMING_SNAKE_CASE__ , self ).__init__()
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or len(SCREAMING_SNAKE_CASE__ ) == 0:
raise ValueError(f'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' )
if any(not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for token_ids in nested_token_ids ):
raise ValueError(f'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''' )
if any(
any((not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or token_id < 0) for token_id in token_ids )
for token_ids in nested_token_ids ):
raise ValueError(
f'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''' )
__a = DisjunctiveTrie(SCREAMING_SNAKE_CASE__ )
__a = nested_token_ids
__a = self.trie.max_height
__a = []
__a = False
def __a ( self : List[Any] ):
'''simple docstring'''
__a = self.trie.next_tokens(self.current_seq )
if len(SCREAMING_SNAKE_CASE__ ) == 0:
return None
else:
return token_list
def __a ( self : Dict , SCREAMING_SNAKE_CASE__ : int ):
'''simple docstring'''
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE__ )}''' )
__a = self.trie.next_tokens(self.current_seq )
return token_id in next_tokens
def __a ( self : Any , SCREAMING_SNAKE_CASE__ : int ):
'''simple docstring'''
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE__ )}''' )
__a = False
__a = False
__a = False
if self.does_advance(SCREAMING_SNAKE_CASE__ ):
self.current_seq.append(SCREAMING_SNAKE_CASE__ )
__a = True
else:
__a = True
self.reset()
__a = self.trie.reached_leaf(self.current_seq )
__a = completed
return stepped, completed, reset
def __a ( self : Tuple ):
'''simple docstring'''
__a = False
__a = []
def __a ( self : List[str] ):
'''simple docstring'''
if self.completed:
# since this can be completed without reaching max height
return 0
else:
return self.seqlen - len(self.current_seq )
def __a ( self : Any , SCREAMING_SNAKE_CASE__ : List[str]=False ):
'''simple docstring'''
__a = DisjunctiveConstraint(self.token_ids )
if stateful:
__a = self.seqlen
__a = self.current_seq
__a = self.completed
return new_constraint
class lowerCAmelCase_ :
"""simple docstring"""
def __init__( self : str , SCREAMING_SNAKE_CASE__ : List[Constraint] ):
'''simple docstring'''
__a = constraints
# max # of steps required to fulfill a given constraint
__a = max([c.seqlen for c in constraints] )
__a = len(SCREAMING_SNAKE_CASE__ )
__a = False
self.init_state()
def __a ( self : Optional[Any] ):
'''simple docstring'''
__a = []
__a = None
__a = [constraint.copy(stateful=SCREAMING_SNAKE_CASE__ ) for constraint in self.constraints]
def __a ( self : Optional[Any] ):
'''simple docstring'''
__a = 0
if self.inprogress_constraint:
# extra points for having a constraint mid-fulfilled
add += self.max_seqlen - self.inprogress_constraint.remaining()
return (len(self.complete_constraints ) * self.max_seqlen) + add
def __a ( self : int ):
'''simple docstring'''
__a = []
if self.inprogress_constraint is None:
for constraint in self.pending_constraints: # "pending" == "unfulfilled yet"
__a = constraint.advance()
if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
token_list.append(SCREAMING_SNAKE_CASE__ )
elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
token_list.extend(SCREAMING_SNAKE_CASE__ )
else:
__a = self.inprogress_constraint.advance()
if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
token_list.append(SCREAMING_SNAKE_CASE__ )
elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
token_list.extend(SCREAMING_SNAKE_CASE__ )
if len(SCREAMING_SNAKE_CASE__ ) == 0:
return None
else:
return token_list
def __a ( self : int , SCREAMING_SNAKE_CASE__ : Optional[List[int]] ):
'''simple docstring'''
self.init_state()
if token_ids is not None:
for token in token_ids:
# completes or steps **one** constraint
__a , __a = self.add(SCREAMING_SNAKE_CASE__ )
# the entire list of constraints are fulfilled
if self.completed:
break
def __a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ):
'''simple docstring'''
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError(f'''`token_id` should be an `int`, but is `{token_id}`.''' )
__a , __a = False, False
if self.completed:
__a = True
__a = False
return complete, stepped
if self.inprogress_constraint is not None:
# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
# job, simply update the state
__a , __a , __a = self.inprogress_constraint.update(SCREAMING_SNAKE_CASE__ )
if reset:
# 1. If the next token breaks the progress, then we must restart.
# e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".
# But that doesn't mean we self.init_state(), since we only reset the state for this particular
# constraint, not the full list of constraints.
self.pending_constraints.append(self.inprogress_constraint.copy(stateful=SCREAMING_SNAKE_CASE__ ) )
__a = None
if complete:
# 2. If the next token completes the constraint, move it to completed list, set
# inprogress to None. If there are no pending constraints either, then this full list of constraints
# is complete.
self.complete_constraints.append(self.inprogress_constraint )
__a = None
if len(self.pending_constraints ) == 0:
# we're done!
__a = True
else:
# Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
# of constraints?
for cidx, pending_constraint in enumerate(self.pending_constraints ):
if pending_constraint.does_advance(SCREAMING_SNAKE_CASE__ ):
__a , __a , __a = pending_constraint.update(SCREAMING_SNAKE_CASE__ )
if not stepped:
raise Exception(
"""`constraint.update(token_id)` is not yielding incremental progress, """
"""even though `constraint.does_advance(token_id)` is true.""" )
if complete:
self.complete_constraints.append(SCREAMING_SNAKE_CASE__ )
__a = None
if not complete and stepped:
__a = pending_constraint
if complete or stepped:
# If we made any progress at all, then it's at least not a "pending constraint".
__a = (
self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
)
if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None:
# If there's no longer any pending after this and no inprogress either, then we must be
# complete.
__a = True
break # prevent accidentally stepping through multiple constraints with just one token.
return complete, stepped
def __a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str]=True ):
'''simple docstring'''
__a = ConstraintListState(self.constraints ) # we actually never though self.constraints objects
# throughout this process. So it's at initialization state.
if stateful:
__a = [
constraint.copy(stateful=SCREAMING_SNAKE_CASE__ ) for constraint in self.complete_constraints
]
if self.inprogress_constraint is not None:
__a = self.inprogress_constraint.copy(stateful=SCREAMING_SNAKE_CASE__ )
__a = [constraint.copy() for constraint in self.pending_constraints]
return new_state
| 582 | 0 |
import unittest
import numpy as np
import torch
from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class UpperCamelCase_ ( unittest.TestCase ):
'''simple docstring'''
@property
def lowercase__ ( self):
torch.manual_seed(0)
lowerCAmelCase_ = UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , )
return model
def lowercase__ ( self):
lowerCAmelCase_ = self.dummy_uncond_unet
lowerCAmelCase_ = ScoreSdeVeScheduler()
lowerCAmelCase_ = ScoreSdeVePipeline(unet=_UpperCAmelCase , scheduler=_UpperCAmelCase)
sde_ve.to(_UpperCAmelCase)
sde_ve.set_progress_bar_config(disable=_UpperCAmelCase)
lowerCAmelCase_ = torch.manual_seed(0)
lowerCAmelCase_ = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=_UpperCAmelCase).images
lowerCAmelCase_ = torch.manual_seed(0)
lowerCAmelCase_ = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=_UpperCAmelCase , return_dict=_UpperCAmelCase)[
0
]
lowerCAmelCase_ = image[0, -3:, -3:, -1]
lowerCAmelCase_ = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
lowerCAmelCase_ = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1E-2
@slow
@require_torch
class UpperCamelCase_ ( unittest.TestCase ):
'''simple docstring'''
def lowercase__ ( self):
lowerCAmelCase_ = '''google/ncsnpp-church-256'''
lowerCAmelCase_ = UNetaDModel.from_pretrained(_UpperCAmelCase)
lowerCAmelCase_ = ScoreSdeVeScheduler.from_pretrained(_UpperCAmelCase)
lowerCAmelCase_ = ScoreSdeVePipeline(unet=_UpperCAmelCase , scheduler=_UpperCAmelCase)
sde_ve.to(_UpperCAmelCase)
sde_ve.set_progress_bar_config(disable=_UpperCAmelCase)
lowerCAmelCase_ = torch.manual_seed(0)
lowerCAmelCase_ = sde_ve(num_inference_steps=10 , output_type='''numpy''' , generator=_UpperCAmelCase).images
lowerCAmelCase_ = image[0, -3:, -3:, -1]
assert image.shape == (1, 256, 256, 3)
lowerCAmelCase_ = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
| 413 |
import unittest
from transformers.utils.backbone_utils import (
BackboneMixin,
get_aligned_output_features_output_indices,
verify_out_features_out_indices,
)
class UpperCamelCase_ ( unittest.TestCase ):
'''simple docstring'''
def lowercase__ ( self):
lowerCAmelCase_ = ['''a''', '''b''', '''c''']
# Defaults to last layer if both are None
lowerCAmelCase_ , lowerCAmelCase_ = get_aligned_output_features_output_indices(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase)
self.assertEqual(_UpperCAmelCase , ['''c'''])
self.assertEqual(_UpperCAmelCase , [2])
# Out indices set to match out features
lowerCAmelCase_ , lowerCAmelCase_ = get_aligned_output_features_output_indices(['''a''', '''c'''] , _UpperCAmelCase , _UpperCAmelCase)
self.assertEqual(_UpperCAmelCase , ['''a''', '''c'''])
self.assertEqual(_UpperCAmelCase , [0, 2])
# Out features set to match out indices
lowerCAmelCase_ , lowerCAmelCase_ = get_aligned_output_features_output_indices(_UpperCAmelCase , [0, 2] , _UpperCAmelCase)
self.assertEqual(_UpperCAmelCase , ['''a''', '''c'''])
self.assertEqual(_UpperCAmelCase , [0, 2])
# Out features selected from negative indices
lowerCAmelCase_ , lowerCAmelCase_ = get_aligned_output_features_output_indices(_UpperCAmelCase , [-3, -1] , _UpperCAmelCase)
self.assertEqual(_UpperCAmelCase , ['''a''', '''c'''])
self.assertEqual(_UpperCAmelCase , [-3, -1])
def lowercase__ ( self):
# Stage names must be set
with self.assertRaises(_UpperCAmelCase):
verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , _UpperCAmelCase)
# Out features must be a list
with self.assertRaises(_UpperCAmelCase):
verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''])
# Out features must be a subset of stage names
with self.assertRaises(_UpperCAmelCase):
verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''])
# Out indices must be a list or tuple
with self.assertRaises(_UpperCAmelCase):
verify_out_features_out_indices(_UpperCAmelCase , 0 , ['''a''', '''b'''])
# Out indices must be a subset of stage names
with self.assertRaises(_UpperCAmelCase):
verify_out_features_out_indices(_UpperCAmelCase , (0, 1) , ['''a'''])
# Out features and out indices must be the same length
with self.assertRaises(_UpperCAmelCase):
verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''])
# Out features should match out indices
with self.assertRaises(_UpperCAmelCase):
verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''])
# Out features and out indices should be in order
with self.assertRaises(_UpperCAmelCase):
verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''])
# Check passes with valid inputs
verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''])
def lowercase__ ( self):
lowerCAmelCase_ = BackboneMixin()
lowerCAmelCase_ = ['''a''', '''b''', '''c''']
lowerCAmelCase_ = ['''a''', '''c''']
lowerCAmelCase_ = [0, 2]
# Check that the output features and indices are set correctly
self.assertEqual(backbone.out_features , ['''a''', '''c'''])
self.assertEqual(backbone.out_indices , [0, 2])
# Check out features and indices are updated correctly
lowerCAmelCase_ = ['''a''', '''b''']
self.assertEqual(backbone.out_features , ['''a''', '''b'''])
self.assertEqual(backbone.out_indices , [0, 1])
lowerCAmelCase_ = [-3, -1]
self.assertEqual(backbone.out_features , ['''a''', '''c'''])
self.assertEqual(backbone.out_indices , [-3, -1])
| 413 | 1 |
'''simple docstring'''
import copy
import json
import os
import tempfile
from transformers import is_torch_available
from .test_configuration_utils import config_common_kwargs
class A ( _a ):
def __init__( self : Union[str, Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : Tuple=True , lowerCAmelCase_ : Union[str, Any]=None , **lowerCAmelCase_ : Optional[int] ) -> Dict:
"""simple docstring"""
_a = parent
_a = config_class
_a = has_text_modality
_a = kwargs
_a = common_properties
def __lowerCAmelCase ( self : Union[str, Any] ) -> Optional[Any]:
"""simple docstring"""
_a = self.config_class(**self.inputs_dict )
_a = (
['''hidden_size''', '''num_attention_heads''', '''num_hidden_layers''']
if self.common_properties is None
else self.common_properties
)
# Add common fields for text models
if self.has_text_modality:
common_properties.extend(['''vocab_size'''] )
# Test that config has the common properties as getters
for prop in common_properties:
self.parent.assertTrue(hasattr(lowerCAmelCase_ , lowerCAmelCase_ ) , msg=F'`{prop}` does not exist' )
# Test that config has the common properties as setter
for idx, name in enumerate(lowerCAmelCase_ ):
try:
setattr(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
self.parent.assertEqual(
getattr(lowerCAmelCase_ , lowerCAmelCase_ ) , lowerCAmelCase_ , msg=F'`{name} value {idx} expected, but was {getattr(lowerCAmelCase_ , lowerCAmelCase_ )}' )
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
# Test if config class can be called with Config(prop_name=..)
for idx, name in enumerate(lowerCAmelCase_ ):
try:
_a = self.config_class(**{name: idx} )
self.parent.assertEqual(
getattr(lowerCAmelCase_ , lowerCAmelCase_ ) , lowerCAmelCase_ , msg=F'`{name} value {idx} expected, but was {getattr(lowerCAmelCase_ , lowerCAmelCase_ )}' )
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
_a = self.config_class(**self.inputs_dict )
_a = json.loads(config.to_json_string() )
for key, value in self.inputs_dict.items():
self.parent.assertEqual(obj[key] , lowerCAmelCase_ )
def __lowerCAmelCase ( self : List[Any] ) -> Optional[Any]:
"""simple docstring"""
_a = self.config_class(**self.inputs_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
_a = os.path.join(lowerCAmelCase_ , '''config.json''' )
config_first.to_json_file(lowerCAmelCase_ )
_a = self.config_class.from_json_file(lowerCAmelCase_ )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def __lowerCAmelCase ( self : List[Any] ) -> Any:
"""simple docstring"""
_a = self.config_class(**self.inputs_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
config_first.save_pretrained(lowerCAmelCase_ )
_a = self.config_class.from_pretrained(lowerCAmelCase_ )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def __lowerCAmelCase ( self : Tuple ) -> int:
"""simple docstring"""
_a = self.config_class(**self.inputs_dict )
_a = '''test'''
with tempfile.TemporaryDirectory() as tmpdirname:
_a = os.path.join(lowerCAmelCase_ , lowerCAmelCase_ )
config_first.save_pretrained(lowerCAmelCase_ )
_a = self.config_class.from_pretrained(lowerCAmelCase_ , subfolder=lowerCAmelCase_ )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple:
"""simple docstring"""
_a = self.config_class(**self.inputs_dict , num_labels=5 )
self.parent.assertEqual(len(config.idalabel ) , 5 )
self.parent.assertEqual(len(config.labelaid ) , 5 )
_a = 3
self.parent.assertEqual(len(config.idalabel ) , 3 )
self.parent.assertEqual(len(config.labelaid ) , 3 )
def __lowerCAmelCase ( self : Optional[Any] ) -> str:
"""simple docstring"""
if self.config_class.is_composition:
return
_a = self.config_class()
self.parent.assertIsNotNone(lowerCAmelCase_ )
def __lowerCAmelCase ( self : List[Any] ) -> Tuple:
"""simple docstring"""
_a = copy.deepcopy(lowerCAmelCase_ )
_a = self.config_class(**lowerCAmelCase_ )
_a = []
for key, value in config_common_kwargs.items():
if key == "torch_dtype":
if not is_torch_available():
continue
else:
import torch
if config.torch_dtype != torch.floataa:
wrong_values.append(('''torch_dtype''', config.torch_dtype, torch.floataa) )
elif getattr(lowerCAmelCase_ , lowerCAmelCase_ ) != value:
wrong_values.append((key, getattr(lowerCAmelCase_ , lowerCAmelCase_ ), value) )
if len(lowerCAmelCase_ ) > 0:
_a = '''\n'''.join([F'- {v[0]}: got {v[1]} instead of {v[2]}' for v in wrong_values] )
raise ValueError(F'The following keys were not properly set in the config:\n{errors}' )
def __lowerCAmelCase ( self : int ) -> Union[str, Any]:
"""simple docstring"""
self.create_and_test_config_common_properties()
self.create_and_test_config_to_json_string()
self.create_and_test_config_to_json_file()
self.create_and_test_config_from_and_save_pretrained()
self.create_and_test_config_from_and_save_pretrained_subfolder()
self.create_and_test_config_with_num_labels()
self.check_config_can_be_init_without_params()
self.check_config_arguments_init()
| 22 |
def _lowercase ( __SCREAMING_SNAKE_CASE ) -> str:
return " ".join(
''.join(word[::-1] ) if len(__SCREAMING_SNAKE_CASE ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('''Hey wollef sroirraw'''))
| 410 | 0 |
from __future__ import annotations
import inspect
import unittest
from typing import List, Tuple
from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class __A:
def __init__( self : int , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Union[str, Any]=3 , __UpperCamelCase : int=3_2 , __UpperCamelCase : Any=3 , __UpperCamelCase : List[str]=1_0 , __UpperCamelCase : int=[1_0, 2_0, 3_0, 4_0] , __UpperCamelCase : List[str]=[1, 1, 2, 1] , __UpperCamelCase : str=True , __UpperCamelCase : List[str]=True , __UpperCamelCase : Dict="relu" , __UpperCamelCase : int=3 , __UpperCamelCase : Dict=None , ):
lowerCamelCase_ = parent
lowerCamelCase_ = batch_size
lowerCamelCase_ = image_size
lowerCamelCase_ = num_channels
lowerCamelCase_ = embeddings_size
lowerCamelCase_ = hidden_sizes
lowerCamelCase_ = depths
lowerCamelCase_ = is_training
lowerCamelCase_ = use_labels
lowerCamelCase_ = hidden_act
lowerCamelCase_ = num_labels
lowerCamelCase_ = scope
lowerCamelCase_ = len(__UpperCamelCase )
def lowercase__ ( self : Any ):
lowerCamelCase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowerCamelCase_ = None
if self.use_labels:
lowerCamelCase_ = ids_tensor([self.batch_size] , self.num_labels )
lowerCamelCase_ = self.get_config()
return config, pixel_values, labels
def lowercase__ ( self : str ):
return RegNetConfig(
num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , )
def lowercase__ ( self : Optional[int] , __UpperCamelCase : int , __UpperCamelCase : Tuple , __UpperCamelCase : Union[str, Any] ):
lowerCamelCase_ = TFRegNetModel(config=__UpperCamelCase )
lowerCamelCase_ = model(__UpperCamelCase , training=__UpperCamelCase )
# expected last hidden states: B, C, H // 32, W // 32
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , )
def lowercase__ ( self : Union[str, Any] , __UpperCamelCase : int , __UpperCamelCase : List[Any] , __UpperCamelCase : List[str] ):
lowerCamelCase_ = self.num_labels
lowerCamelCase_ = TFRegNetForImageClassification(__UpperCamelCase )
lowerCamelCase_ = model(__UpperCamelCase , labels=__UpperCamelCase , training=__UpperCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def lowercase__ ( self : int ):
lowerCamelCase_ = self.prepare_config_and_inputs()
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = config_and_inputs
lowerCamelCase_ = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_tf
class __A( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ):
SCREAMING_SNAKE_CASE = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
SCREAMING_SNAKE_CASE = (
{'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
if is_tf_available()
else {}
)
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
def lowercase__ ( self : Tuple ):
lowerCamelCase_ = TFRegNetModelTester(self )
lowerCamelCase_ = ConfigTester(self , config_class=__UpperCamelCase , has_text_modality=__UpperCamelCase )
def lowercase__ ( self : Union[str, Any] ):
return
@unittest.skip(reason="""RegNet does not use inputs_embeds""" )
def lowercase__ ( self : Optional[int] ):
pass
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , )
@slow
def lowercase__ ( self : Tuple ):
super().test_keras_fit()
@unittest.skip(reason="""RegNet does not support input and output embeddings""" )
def lowercase__ ( self : Optional[Any] ):
pass
def lowercase__ ( self : Dict ):
lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase_ = model_class(__UpperCamelCase )
lowerCamelCase_ = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowerCamelCase_ = [*signature.parameters.keys()]
lowerCamelCase_ = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , __UpperCamelCase )
def lowercase__ ( self : Any ):
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__UpperCamelCase )
def lowercase__ ( self : int ):
def check_hidden_states_output(__UpperCamelCase : Union[str, Any] , __UpperCamelCase : str , __UpperCamelCase : Any ):
lowerCamelCase_ = model_class(__UpperCamelCase )
lowerCamelCase_ = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) , training=__UpperCamelCase )
lowerCamelCase_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
lowerCamelCase_ = self.model_tester.num_stages
self.assertEqual(len(__UpperCamelCase ) , expected_num_stages + 1 )
# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , )
lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase_ = ["""basic""", """bottleneck"""]
for model_class in self.all_model_classes:
for layer_type in layers_type:
lowerCamelCase_ = layer_type
lowerCamelCase_ = True
check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowerCamelCase_ = True
check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
def lowercase__ ( self : Optional[Any] ):
lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
def check_equivalence(__UpperCamelCase : List[str] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Tuple , __UpperCamelCase : List[Any]={} ):
lowerCamelCase_ = model(__UpperCamelCase , return_dict=__UpperCamelCase , **__UpperCamelCase )
lowerCamelCase_ = model(__UpperCamelCase , return_dict=__UpperCamelCase , **__UpperCamelCase ).to_tuple()
def recursive_check(__UpperCamelCase : Union[str, Any] , __UpperCamelCase : Dict ):
if isinstance(__UpperCamelCase , (List, Tuple) ):
for tuple_iterable_value, dict_iterable_value in zip(__UpperCamelCase , __UpperCamelCase ):
recursive_check(__UpperCamelCase , __UpperCamelCase )
elif tuple_object is None:
return
else:
self.assertTrue(
all(tf.equal(__UpperCamelCase , __UpperCamelCase ) ) , msg=(
"""Tuple and dict output are not equal. Difference:"""
F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}'''
) , )
recursive_check(__UpperCamelCase , __UpperCamelCase )
for model_class in self.all_model_classes:
lowerCamelCase_ = model_class(__UpperCamelCase )
lowerCamelCase_ = self._prepare_for_class(__UpperCamelCase , __UpperCamelCase )
lowerCamelCase_ = self._prepare_for_class(__UpperCamelCase , __UpperCamelCase )
check_equivalence(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
lowerCamelCase_ = self._prepare_for_class(__UpperCamelCase , __UpperCamelCase , return_labels=__UpperCamelCase )
lowerCamelCase_ = self._prepare_for_class(__UpperCamelCase , __UpperCamelCase , return_labels=__UpperCamelCase )
check_equivalence(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
lowerCamelCase_ = self._prepare_for_class(__UpperCamelCase , __UpperCamelCase )
lowerCamelCase_ = self._prepare_for_class(__UpperCamelCase , __UpperCamelCase )
check_equivalence(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , {"""output_hidden_states""": True} )
lowerCamelCase_ = self._prepare_for_class(__UpperCamelCase , __UpperCamelCase , return_labels=__UpperCamelCase )
lowerCamelCase_ = self._prepare_for_class(__UpperCamelCase , __UpperCamelCase , return_labels=__UpperCamelCase )
check_equivalence(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , {"""output_hidden_states""": True} )
def lowercase__ ( self : Union[str, Any] ):
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase )
@slow
def lowercase__ ( self : List[Any] ):
for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCamelCase_ = TFRegNetModel.from_pretrained(__UpperCamelCase )
self.assertIsNotNone(__UpperCamelCase )
def __lowerCAmelCase ( ) -> Optional[int]:
lowerCamelCase_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_tf
@require_vision
class __A( unittest.TestCase ):
@cached_property
def lowercase__ ( self : Union[str, Any] ):
return (
AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
if is_vision_available()
else None
)
@slow
def lowercase__ ( self : List[str] ):
lowerCamelCase_ = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
lowerCamelCase_ = self.default_image_processor
lowerCamelCase_ = prepare_img()
lowerCamelCase_ = image_processor(images=__UpperCamelCase , return_tensors="""tf""" )
# forward pass
lowerCamelCase_ = model(**__UpperCamelCase , training=__UpperCamelCase )
# verify the logits
lowerCamelCase_ = tf.TensorShape((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , __UpperCamelCase )
lowerCamelCase_ = tf.constant([-0.4180, -1.5051, -3.4836] )
tf.debugging.assert_near(outputs.logits[0, :3] , __UpperCamelCase , atol=1E-4 )
| 103 |
import hashlib
import unittest
from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available
from transformers.pipelines import DepthEstimationPipeline, pipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_timm,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
else:
class __A:
@staticmethod
def lowercase__ ( *__UpperCamelCase : str , **__UpperCamelCase : Dict ):
pass
def __lowerCAmelCase ( UpperCAmelCase__ : Image ) -> str:
lowerCamelCase_ = hashlib.mda(image.tobytes() )
return m.hexdigest()
@is_pipeline_test
@require_vision
@require_timm
@require_torch
class __A( unittest.TestCase ):
SCREAMING_SNAKE_CASE = MODEL_FOR_DEPTH_ESTIMATION_MAPPING
def lowercase__ ( self : Union[str, Any] , __UpperCamelCase : int , __UpperCamelCase : Optional[int] , __UpperCamelCase : int ):
lowerCamelCase_ = DepthEstimationPipeline(model=__UpperCamelCase , image_processor=__UpperCamelCase )
return depth_estimator, [
"./tests/fixtures/tests_samples/COCO/000000039769.png",
"./tests/fixtures/tests_samples/COCO/000000039769.png",
]
def lowercase__ ( self : Any , __UpperCamelCase : List[str] , __UpperCamelCase : Union[str, Any] ):
lowerCamelCase_ = depth_estimator("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
self.assertEqual({"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )} , __UpperCamelCase )
import datasets
lowerCamelCase_ = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" )
lowerCamelCase_ = depth_estimator(
[
Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ),
"""http://images.cocodataset.org/val2017/000000039769.jpg""",
# RGBA
dataset[0]["""file"""],
# LA
dataset[1]["""file"""],
# L
dataset[2]["""file"""],
] )
self.assertEqual(
[
{"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )},
{"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )},
{"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )},
{"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )},
{"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )},
] , __UpperCamelCase , )
@require_tf
@unittest.skip("""Depth estimation is not implemented in TF""" )
def lowercase__ ( self : Optional[int] ):
pass
@slow
@require_torch
def lowercase__ ( self : List[Any] ):
lowerCamelCase_ = """Intel/dpt-large"""
lowerCamelCase_ = pipeline("""depth-estimation""" , model=__UpperCamelCase )
lowerCamelCase_ = depth_estimator("""http://images.cocodataset.org/val2017/000000039769.jpg""" )
lowerCamelCase_ = hashimage(outputs["""depth"""] )
# This seems flaky.
# self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977")
self.assertEqual(nested_simplify(outputs["""predicted_depth"""].max().item() ) , 29.304 )
self.assertEqual(nested_simplify(outputs["""predicted_depth"""].min().item() ) , 2.662 )
@require_torch
def lowercase__ ( self : Dict ):
# This is highly irregular to have no small tests.
self.skipTest("""There is not hf-internal-testing tiny model for either GLPN nor DPT""" )
| 103 | 1 |
'''simple docstring'''
from .constants import (
MODEL_NAME,
OPTIMIZER_NAME,
RNG_STATE_NAME,
SAFE_WEIGHTS_INDEX_NAME,
SAFE_WEIGHTS_NAME,
SCALER_NAME,
SCHEDULER_NAME,
TORCH_LAUNCH_PARAMS,
WEIGHTS_INDEX_NAME,
WEIGHTS_NAME,
)
from .dataclasses import (
BnbQuantizationConfig,
ComputeEnvironment,
CustomDtype,
DeepSpeedPlugin,
DistributedDataParallelKwargs,
DistributedType,
DynamoBackend,
FPaRecipeKwargs,
FullyShardedDataParallelPlugin,
GradientAccumulationPlugin,
GradScalerKwargs,
InitProcessGroupKwargs,
KwargsHandler,
LoggerType,
MegatronLMPlugin,
PrecisionType,
ProjectConfiguration,
RNGType,
SageMakerDistributedType,
TensorInformation,
TorchDynamoPlugin,
)
from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env
from .imports import (
get_ccl_version,
is_abit_bnb_available,
is_abit_bnb_available,
is_aim_available,
is_bfaa_available,
is_bnb_available,
is_botoa_available,
is_ccl_available,
is_comet_ml_available,
is_datasets_available,
is_deepspeed_available,
is_fpa_available,
is_ipex_available,
is_megatron_lm_available,
is_mlflow_available,
is_mps_available,
is_npu_available,
is_rich_available,
is_safetensors_available,
is_sagemaker_available,
is_tensorboard_available,
is_tpu_available,
is_transformers_available,
is_wandb_available,
is_xpu_available,
)
from .modeling import (
check_device_map,
check_tied_parameters_in_config,
check_tied_parameters_on_same_device,
compute_module_sizes,
convert_file_size_to_int,
dtype_byte_size,
find_tied_parameters,
get_balanced_memory,
get_max_layer_size,
get_max_memory,
get_mixed_precision_context_manager,
id_tensor_storage,
infer_auto_device_map,
load_checkpoint_in_model,
load_offloaded_weights,
load_state_dict,
named_module_tensors,
retie_parameters,
set_module_tensor_to_device,
shard_checkpoint,
)
from .offload import (
OffloadedWeightsLoader,
PrefixedDataset,
extract_submodules_state_dict,
load_offloaded_weight,
offload_state_dict,
offload_weight,
save_offload_index,
)
from .operations import (
broadcast,
broadcast_object_list,
concatenate,
convert_outputs_to_fpaa,
convert_to_fpaa,
find_batch_size,
find_device,
gather,
gather_object,
get_data_structure,
honor_type,
initialize_tensors,
is_namedtuple,
is_tensor_information,
is_torch_tensor,
listify,
pad_across_processes,
recursively_apply,
reduce,
send_to_device,
slice_tensors,
)
from .versions import compare_versions, is_torch_version
if is_deepspeed_available():
from .deepspeed import (
DeepSpeedEngineWrapper,
DeepSpeedOptimizerWrapper,
DeepSpeedSchedulerWrapper,
DummyOptim,
DummyScheduler,
HfDeepSpeedConfig,
)
from .bnb import has_abit_bnb_layers, load_and_quantize_model
from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer
from .launch import (
PrepareForLaunch,
_filter_args,
prepare_deepspeed_cmd_env,
prepare_multi_gpu_env,
prepare_sagemager_args_inputs,
prepare_simple_launcher_cmd_env,
prepare_tpu,
)
from .megatron_lm import (
AbstractTrainStep,
BertTrainStep,
GPTTrainStep,
MegatronEngine,
MegatronLMDummyDataLoader,
MegatronLMDummyScheduler,
MegatronLMOptimizerWrapper,
MegatronLMSchedulerWrapper,
TaTrainStep,
avg_losses_across_data_parallel_group,
gather_across_data_parallel_groups,
)
from .megatron_lm import initialize as megatron_lm_initialize
from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader
from .megatron_lm import prepare_model as megatron_lm_prepare_model
from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer
from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler
from .memory import find_executable_batch_size, release_memory
from .other import (
extract_model_from_parallel,
get_pretty_name,
is_port_in_use,
merge_dicts,
patch_environment,
save,
wait_for_everyone,
write_basic_config,
)
from .random import set_seed, synchronize_rng_state, synchronize_rng_states
from .torch_xla import install_xla
from .tqdm import tqdm
from .transformer_engine import convert_model, has_transformer_engine_layers
| 78 |
def __snake_case ( ) -> int:
return 1
def __snake_case ( lowerCAmelCase_ ) -> int:
return 0 if x < 0 else two_pence(x - 2 ) + one_pence()
def __snake_case ( lowerCAmelCase_ ) -> int:
return 0 if x < 0 else five_pence(x - 5 ) + two_pence(lowerCAmelCase_ )
def __snake_case ( lowerCAmelCase_ ) -> int:
return 0 if x < 0 else ten_pence(x - 1_0 ) + five_pence(lowerCAmelCase_ )
def __snake_case ( lowerCAmelCase_ ) -> int:
return 0 if x < 0 else twenty_pence(x - 2_0 ) + ten_pence(lowerCAmelCase_ )
def __snake_case ( lowerCAmelCase_ ) -> int:
return 0 if x < 0 else fifty_pence(x - 5_0 ) + twenty_pence(lowerCAmelCase_ )
def __snake_case ( lowerCAmelCase_ ) -> int:
return 0 if x < 0 else one_pound(x - 1_0_0 ) + fifty_pence(lowerCAmelCase_ )
def __snake_case ( lowerCAmelCase_ ) -> int:
return 0 if x < 0 else two_pound(x - 2_0_0 ) + one_pound(lowerCAmelCase_ )
def __snake_case ( lowerCAmelCase_ = 2_0_0 ) -> int:
return two_pound(lowerCAmelCase_ )
if __name__ == "__main__":
print(solution(int(input().strip())))
| 100 | 0 |
def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ):
A_ : Tuple = 1
A_ : str = 2
while i * i <= n:
A_ : Optional[Any] = 0
while n % i == 0:
n //= i
multiplicity += 1
n_divisors *= multiplicity + 1
i += 1
if n > 1:
n_divisors *= 2
return n_divisors
def _SCREAMING_SNAKE_CASE ( ):
A_ : Union[str, Any] = 1
A_ : Optional[int] = 1
while True:
i += 1
t_num += i
if count_divisors(SCREAMING_SNAKE_CASE ) > 500:
break
return t_num
if __name__ == "__main__":
print(solution())
| 708 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCamelCase = {
"""configuration_bigbird_pegasus""": [
"""BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""BigBirdPegasusConfig""",
"""BigBirdPegasusOnnxConfig""",
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase = [
"""BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""BigBirdPegasusForCausalLM""",
"""BigBirdPegasusForConditionalGeneration""",
"""BigBirdPegasusForQuestionAnswering""",
"""BigBirdPegasusForSequenceClassification""",
"""BigBirdPegasusModel""",
"""BigBirdPegasusPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_bigbird_pegasus import (
BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP,
BigBirdPegasusConfig,
BigBirdPegasusOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_bigbird_pegasus import (
BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST,
BigBirdPegasusForCausalLM,
BigBirdPegasusForConditionalGeneration,
BigBirdPegasusForQuestionAnswering,
BigBirdPegasusForSequenceClassification,
BigBirdPegasusModel,
BigBirdPegasusPreTrainedModel,
)
else:
import sys
UpperCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 152 | 0 |
import io
import json
import unittest
from parameterized import parameterized
from transformers import FSMTForConditionalGeneration, FSMTTokenizer
from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device
from utils import calculate_bleu
_lowerCamelCase : Dict = get_tests_dir() + '''/test_data/fsmt/fsmt_val_data.json'''
with io.open(filename, '''r''', encoding='''utf-8''') as f:
_lowerCamelCase : Tuple = json.load(f)
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
'''simple docstring'''
def A ( self : List[str] , lowercase : Optional[int] ):
'''simple docstring'''
return FSMTTokenizer.from_pretrained(lowercase )
def A ( self : Dict , lowercase : Any ):
'''simple docstring'''
_snake_case = FSMTForConditionalGeneration.from_pretrained(lowercase ).to(lowercase )
if torch_device == "cuda":
model.half()
return model
@parameterized.expand(
[
['en-ru', 26.0],
['ru-en', 22.0],
['en-de', 22.0],
['de-en', 29.0],
] )
@slow
def A ( self : Optional[int] , lowercase : Any , lowercase : int ):
'''simple docstring'''
_snake_case = f'''facebook/wmt19-{pair}'''
_snake_case = self.get_tokenizer(lowercase )
_snake_case = self.get_model(lowercase )
_snake_case = bleu_data[pair]['src']
_snake_case = bleu_data[pair]['tgt']
_snake_case = tokenizer(lowercase , return_tensors='pt' , truncation=lowercase , padding='longest' ).to(lowercase )
_snake_case = model.generate(
input_ids=batch.input_ids , num_beams=8 , )
_snake_case = tokenizer.batch_decode(
lowercase , skip_special_tokens=lowercase , clean_up_tokenization_spaces=lowercase )
_snake_case = calculate_bleu(lowercase , lowercase )
print(lowercase )
self.assertGreaterEqual(scores['bleu'] , lowercase ) | 686 |
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
_lowerCamelCase : Union[str, Any] = logging.get_logger(__name__)
_lowerCamelCase : Tuple = {
'''microsoft/resnet-50''': '''https://huggingface.co/microsoft/resnet-50/blob/main/config.json''',
}
class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ,UpperCAmelCase ):
'''simple docstring'''
_UpperCAmelCase : List[Any] = "resnet"
_UpperCAmelCase : Any = ["basic", "bottleneck"]
def __init__( self : Union[str, Any] , lowercase : Dict=3 , lowercase : Any=64 , lowercase : Any=[256, 512, 1_024, 2_048] , lowercase : Dict=[3, 4, 6, 3] , lowercase : Any="bottleneck" , lowercase : Optional[Any]="relu" , lowercase : Dict=False , lowercase : str=None , lowercase : Tuple=None , **lowercase : List[Any] , ):
'''simple docstring'''
super().__init__(**lowercase )
if layer_type not in self.layer_types:
raise ValueError(f'''layer_type={layer_type} is not one of {','.join(self.layer_types )}''' )
_snake_case = num_channels
_snake_case = embedding_size
_snake_case = hidden_sizes
_snake_case = depths
_snake_case = layer_type
_snake_case = hidden_act
_snake_case = downsample_in_first_stage
_snake_case = ['stem'] + [f'''stage{idx}''' for idx in range(1 , len(lowercase ) + 1 )]
_snake_case , _snake_case = get_aligned_output_features_output_indices(
out_features=lowercase , out_indices=lowercase , stage_names=self.stage_names )
class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ):
'''simple docstring'''
_UpperCAmelCase : Any = version.parse("1.11" )
@property
def A ( self : int ):
'''simple docstring'''
return OrderedDict(
[
('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
] )
@property
def A ( self : Optional[Any] ):
'''simple docstring'''
return 1E-3 | 686 | 1 |
'''simple docstring'''
import operator as op
def snake_case__ ( _A: Optional[Any] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase = []
lowerCAmelCase = lambda _A , _A : int(x / y ) # noqa: E731 integer division operation
lowerCAmelCase = {
"""^""": op.pow,
"""*""": op.mul,
"""/""": div,
"""+""": op.add,
"""-""": op.sub,
} # operators & their respective operation
# print table header
print("""Symbol""".center(8 ) , """Action""".center(12 ) , """Stack""" , sep=""" | """ )
print("""-""" * (30 + len(_A )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(_A ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ("""push(""" + x + """)""").ljust(12 ) , """,""".join(_A ) , sep=""" | """ )
else:
lowerCAmelCase = stack.pop() # pop stack
# output in tabular format
print("""""".rjust(8 ) , ("""pop(""" + b + """)""").ljust(12 ) , """,""".join(_A ) , sep=""" | """ )
lowerCAmelCase = stack.pop() # pop stack
# output in tabular format
print("""""".rjust(8 ) , ("""pop(""" + a + """)""").ljust(12 ) , """,""".join(_A ) , sep=""" | """ )
stack.append(
str(opr[x](int(_A ) , int(_A ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ("""push(""" + a + x + b + """)""").ljust(12 ) , """,""".join(_A ) , sep=""" | """ , )
return int(stack[0] )
if __name__ == "__main__":
__lowercase = input('''\n\nEnter a Postfix Equation (space separated) = ''').split(''' ''')
print('''\n\tResult = ''', solve(Postfix))
| 605 | '''simple docstring'''
from typing import Optional
import pyspark
from .. import Features, NamedSplit
from ..download import DownloadMode
from ..packaged_modules.spark.spark import Spark
from .abc import AbstractDatasetReader
class a__( lowerCAmelCase__ ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = True , __lowerCAmelCase = None , __lowerCAmelCase = False , __lowerCAmelCase = None , __lowerCAmelCase = True , __lowerCAmelCase = "arrow" , **__lowerCAmelCase , ):
"""simple docstring"""
super().__init__(
split=__lowerCAmelCase , features=__lowerCAmelCase , cache_dir=__lowerCAmelCase , keep_in_memory=__lowerCAmelCase , streaming=__lowerCAmelCase , **__lowerCAmelCase , )
lowerCAmelCase = load_from_cache_file
lowerCAmelCase = file_format
lowerCAmelCase = Spark(
df=__lowerCAmelCase , features=__lowerCAmelCase , cache_dir=__lowerCAmelCase , working_dir=__lowerCAmelCase , **__lowerCAmelCase , )
def a_ ( self):
"""simple docstring"""
if self.streaming:
return self.builder.as_streaming_dataset(split=self.split)
lowerCAmelCase = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD
self.builder.download_and_prepare(
download_mode=__lowerCAmelCase , file_format=self._file_format , )
return self.builder.as_dataset(split=self.split)
| 605 | 1 |
# limitations under the License.
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401
from .utils import deprecate
deprecate(
'''pipelines_utils''',
'''0.22.0''',
'''Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.''',
standard_warn=False,
stacklevel=3,
)
| 60 |
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_tf_available():
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING
if is_torch_available():
import torch
from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING
A : Dict = logging.get_logger(__name__)
@add_end_docstrings(a )
class __A( a ):
def __init__( self , *_snake_case , **_snake_case ) -> Optional[int]:
'''simple docstring'''
super().__init__(*_snake_case , **_snake_case )
requires_backends(self , '''vision''' )
self.check_model_type(
TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == '''tf''' else MODEL_FOR_VISION_2_SEQ_MAPPING )
def SCREAMING_SNAKE_CASE_ ( self , _snake_case=None , _snake_case=None , _snake_case=None ) -> Tuple:
'''simple docstring'''
__a = {}
__a = {}
if prompt is not None:
__a = prompt
if generate_kwargs is not None:
__a = generate_kwargs
if max_new_tokens is not None:
if "generate_kwargs" not in forward_kwargs:
__a = {}
if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
raise ValueError(
'''\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,'''
''' please use only one''' )
__a = max_new_tokens
return preprocess_params, forward_kwargs, {}
def __call__( self , _snake_case , **_snake_case ) -> List[Any]:
'''simple docstring'''
return super().__call__(_snake_case , **_snake_case )
def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case=None ) -> Optional[int]:
'''simple docstring'''
__a = load_image(_snake_case )
if prompt is not None:
if not isinstance(_snake_case , _snake_case ):
raise ValueError(
F"""Received an invalid text input, got - {type(_snake_case )} - but expected a single string. """
'''Note also that one single text can be provided for conditional image to text generation.''' )
__a = self.model.config.model_type
if model_type == "git":
__a = self.image_processor(images=_snake_case , return_tensors=self.framework )
__a = self.tokenizer(text=_snake_case , add_special_tokens=_snake_case ).input_ids
__a = [self.tokenizer.cls_token_id] + input_ids
__a = torch.tensor(_snake_case ).unsqueeze(0 )
model_inputs.update({'''input_ids''': input_ids} )
elif model_type == "pix2struct":
__a = self.image_processor(images=_snake_case , header_text=_snake_case , return_tensors=self.framework )
elif model_type != "vision-encoder-decoder":
# vision-encoder-decoder does not support conditional generation
__a = self.image_processor(images=_snake_case , return_tensors=self.framework )
__a = self.tokenizer(_snake_case , return_tensors=self.framework )
model_inputs.update(_snake_case )
else:
raise ValueError(F"""Model type {model_type} does not support conditional text generation""" )
else:
__a = self.image_processor(images=_snake_case , return_tensors=self.framework )
if self.model.config.model_type == "git" and prompt is None:
__a = None
return model_inputs
def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case=None ) -> str:
'''simple docstring'''
if (
"input_ids" in model_inputs
and isinstance(model_inputs['''input_ids'''] , _snake_case )
and all(x is None for x in model_inputs['''input_ids'''] )
):
__a = None
if generate_kwargs is None:
__a = {}
# FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
# parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
# the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
# in the `_prepare_model_inputs` method.
__a = model_inputs.pop(self.model.main_input_name )
__a = self.model.generate(_snake_case , **_snake_case , **_snake_case )
return model_outputs
def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> Dict:
'''simple docstring'''
__a = []
for output_ids in model_outputs:
__a = {
'''generated_text''': self.tokenizer.decode(
_snake_case , skip_special_tokens=_snake_case , )
}
records.append(_snake_case )
return records | 219 | 0 |
'''simple docstring'''
import json
import os
import unittest
from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class UpperCAmelCase ( lowercase_ , unittest.TestCase):
"""simple docstring"""
lowerCAmelCase_ = XLMTokenizer
lowerCAmelCase_ = False
def UpperCamelCase__ ( self : Optional[Any] ) -> Optional[Any]:
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_UpperCamelCase =[
'''l''',
'''o''',
'''w''',
'''e''',
'''r''',
'''s''',
'''t''',
'''i''',
'''d''',
'''n''',
'''w</w>''',
'''r</w>''',
'''t</w>''',
'''lo''',
'''low''',
'''er</w>''',
'''low</w>''',
'''lowest</w>''',
'''newer</w>''',
'''wider</w>''',
'''<unk>''',
]
_UpperCamelCase =dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) )
_UpperCamelCase =['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', '''''']
_UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
_UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] )
with open(self.vocab_file , '''w''' ) as fp:
fp.write(json.dumps(UpperCamelCase__ ) )
with open(self.merges_file , '''w''' ) as fp:
fp.write('''\n'''.join(UpperCamelCase__ ) )
def UpperCamelCase__ ( self : str , UpperCamelCase__ : str ) -> Optional[Any]:
_UpperCamelCase ='''lower newer'''
_UpperCamelCase ='''lower newer'''
return input_text, output_text
def UpperCamelCase__ ( self : List[str] ) -> int:
_UpperCamelCase =XLMTokenizer(self.vocab_file , self.merges_file )
_UpperCamelCase ='''lower'''
_UpperCamelCase =['''low''', '''er</w>''']
_UpperCamelCase =tokenizer.tokenize(UpperCamelCase__ )
self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ )
_UpperCamelCase =tokens + ['''<unk>''']
_UpperCamelCase =[14, 15, 20]
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , UpperCamelCase__ )
@slow
def UpperCamelCase__ ( self : Union[str, Any] ) -> int:
_UpperCamelCase =XLMTokenizer.from_pretrained('''xlm-mlm-en-2048''' )
_UpperCamelCase =tokenizer.encode('''sequence builders''' , add_special_tokens=UpperCamelCase__ )
_UpperCamelCase =tokenizer.encode('''multi-sequence build''' , add_special_tokens=UpperCamelCase__ )
_UpperCamelCase =tokenizer.build_inputs_with_special_tokens(UpperCamelCase__ )
_UpperCamelCase =tokenizer.build_inputs_with_special_tokens(UpperCamelCase__ , UpperCamelCase__ )
assert encoded_sentence == [0] + text + [1]
assert encoded_pair == [0] + text + [1] + text_a + [1]
| 271 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__lowerCamelCase : Union[str, Any] = logging.get_logger(__name__)
__lowerCamelCase : int = {
'google/mobilenet_v2_1.4_224': 'https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json',
'google/mobilenet_v2_1.0_224': 'https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json',
'google/mobilenet_v2_0.75_160': 'https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json',
'google/mobilenet_v2_0.35_96': 'https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json',
# See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2
}
class UpperCAmelCase ( lowercase_):
"""simple docstring"""
lowerCAmelCase_ = """mobilenet_v2"""
def __init__( self : Tuple , UpperCamelCase__ : Union[str, Any]=3 , UpperCamelCase__ : Dict=224 , UpperCamelCase__ : str=1.0 , UpperCamelCase__ : List[Any]=8 , UpperCamelCase__ : Union[str, Any]=8 , UpperCamelCase__ : str=6 , UpperCamelCase__ : str=32 , UpperCamelCase__ : str=True , UpperCamelCase__ : int=True , UpperCamelCase__ : str="relu6" , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : List[str]=0.8 , UpperCamelCase__ : List[str]=0.02 , UpperCamelCase__ : str=0.001 , UpperCamelCase__ : Dict=255 , **UpperCamelCase__ : Tuple , ) -> List[Any]:
super().__init__(**UpperCamelCase__ )
if depth_multiplier <= 0:
raise ValueError('''depth_multiplier must be greater than zero.''' )
_UpperCamelCase =num_channels
_UpperCamelCase =image_size
_UpperCamelCase =depth_multiplier
_UpperCamelCase =depth_divisible_by
_UpperCamelCase =min_depth
_UpperCamelCase =expand_ratio
_UpperCamelCase =output_stride
_UpperCamelCase =first_layer_is_expansion
_UpperCamelCase =finegrained_output
_UpperCamelCase =hidden_act
_UpperCamelCase =tf_padding
_UpperCamelCase =classifier_dropout_prob
_UpperCamelCase =initializer_range
_UpperCamelCase =layer_norm_eps
_UpperCamelCase =semantic_loss_ignore_index
class UpperCAmelCase ( lowercase_):
"""simple docstring"""
lowerCAmelCase_ = version.parse("""1.11""")
@property
def UpperCamelCase__ ( self : str ) -> Mapping[str, Mapping[int, str]]:
return OrderedDict([('''pixel_values''', {0: '''batch'''})] )
@property
def UpperCamelCase__ ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]:
if self.task == "image-classification":
return OrderedDict([('''logits''', {0: '''batch'''})] )
else:
return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] )
@property
def UpperCamelCase__ ( self : List[Any] ) -> float:
return 1E-4
| 271 | 1 |
import inspect
import os
import unittest
import torch
import accelerate
from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_multi_gpu
from accelerate.utils import patch_environment
class a ( unittest.TestCase ):
'''simple docstring'''
def lowerCamelCase_ ( self : Optional[Any] ):
UpperCAmelCase_ = inspect.getfile(accelerate.test_utils )
UpperCAmelCase_ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] )
UpperCAmelCase_ = os.path.sep.join(
mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] )
UpperCAmelCase_ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] )
@require_multi_gpu
def lowerCamelCase_ ( self : str ):
print(F'Found {torch.cuda.device_count()} devices.' )
UpperCAmelCase_ = ['''torchrun''', F'--nproc_per_node={torch.cuda.device_count()}', self.test_file_path]
with patch_environment(omp_num_threads=1 ):
execute_subprocess_async(__snake_case , env=os.environ.copy() )
@require_multi_gpu
def lowerCamelCase_ ( self : Tuple ):
print(F'Found {torch.cuda.device_count()} devices.' )
UpperCAmelCase_ = ['''torchrun''', F'--nproc_per_node={torch.cuda.device_count()}', self.operation_file_path]
print(F'Command: {cmd}' )
with patch_environment(omp_num_threads=1 ):
execute_subprocess_async(__snake_case , env=os.environ.copy() )
@require_multi_gpu
def lowerCamelCase_ ( self : List[str] ):
UpperCAmelCase_ = ['''torchrun''', F'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )]
with patch_environment(omp_num_threads=1 ):
execute_subprocess_async(__snake_case , env=os.environ.copy() )
@require_multi_gpu
def lowerCamelCase_ ( self : int ):
print(F'Found {torch.cuda.device_count()} devices, using 2 devices only' )
UpperCAmelCase_ = ['''torchrun''', F'--nproc_per_node={torch.cuda.device_count()}', self.data_loop_file_path]
with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ):
execute_subprocess_async(__snake_case , env=os.environ.copy() )
if __name__ == "__main__":
_lowerCamelCase = Accelerator()
_lowerCamelCase = (accelerator.state.process_index + 2, 10)
_lowerCamelCase = torch.randint(0, 10, shape).to(accelerator.device)
_lowerCamelCase = ''
_lowerCamelCase = accelerator.pad_across_processes(tensor)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0):
error_msg += "Padding was not done with the right value (0)."
_lowerCamelCase = accelerator.pad_across_processes(tensor, pad_first=True)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
_lowerCamelCase = accelerator.state.num_processes - accelerator.state.process_index - 1
if not torch.equal(tensora[index:], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[:index] == 0):
error_msg += "Padding was not done with the right value (0)."
# Raise error at the end to make sure we don't stop at the first failure.
if len(error_msg) > 0:
raise ValueError(error_msg)
| 144 |
# using dfs for finding eulerian path traversal
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : List[Any] , __UpperCamelCase : int , __UpperCamelCase : List[str] , __UpperCamelCase : List[str]=None ) -> Optional[Any]:
UpperCAmelCase_ = (path or []) + [u]
for v in graph[u]:
if visited_edge[u][v] is False:
UpperCAmelCase_ , UpperCAmelCase_ = True, True
UpperCAmelCase_ = dfs(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
return path
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Tuple , __UpperCamelCase : Optional[int] ) -> List[Any]:
UpperCAmelCase_ = 0
UpperCAmelCase_ = -1
for i in range(__UpperCamelCase ):
if i not in graph.keys():
continue
if len(graph[i] ) % 2 == 1:
odd_degree_nodes += 1
UpperCAmelCase_ = i
if odd_degree_nodes == 0:
return 1, odd_node
if odd_degree_nodes == 2:
return 2, odd_node
return 3, odd_node
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Any , __UpperCamelCase : Optional[Any] ) -> str:
UpperCAmelCase_ = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )]
UpperCAmelCase_ , UpperCAmelCase_ = check_circuit_or_path(__UpperCamelCase , __UpperCamelCase )
if check == 3:
print('''graph is not Eulerian''' )
print('''no path''' )
return
UpperCAmelCase_ = 1
if check == 2:
UpperCAmelCase_ = odd_node
print('''graph has a Euler path''' )
if check == 1:
print('''graph has a Euler cycle''' )
UpperCAmelCase_ = dfs(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
print(__UpperCamelCase )
def SCREAMING_SNAKE_CASE ( ) -> Tuple:
UpperCAmelCase_ = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]}
UpperCAmelCase_ = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]}
UpperCAmelCase_ = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]}
UpperCAmelCase_ = {1: [2, 3], 2: [1, 3], 3: [1, 2]}
UpperCAmelCase_ = {
1: [],
2: []
# all degree is zero
}
UpperCAmelCase_ = 10
check_euler(__UpperCamelCase , __UpperCamelCase )
check_euler(__UpperCamelCase , __UpperCamelCase )
check_euler(__UpperCamelCase , __UpperCamelCase )
check_euler(__UpperCamelCase , __UpperCamelCase )
check_euler(__UpperCamelCase , __UpperCamelCase )
if __name__ == "__main__":
main()
| 144 | 1 |
import argparse
import torch
from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert
from transformers.utils import logging
logging.set_verbosity_info()
def _lowerCAmelCase ( A__ , A__ , A__ ):
# Initialise PyTorch model
lowercase__ = RemBertConfig.from_json_file(A__ )
print('Building PyTorch model from configuration: {}'.format(str(A__ ) ) )
lowercase__ = RemBertModel(A__ )
# Load weights from tf checkpoint
load_tf_weights_in_rembert(A__ , A__ , A__ )
# Save pytorch-model
print('Save PyTorch model to {}'.format(A__ ) )
torch.save(model.state_dict() , A__ )
if __name__ == "__main__":
a__ : Optional[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
)
parser.add_argument(
"--rembert_config_file",
default=None,
type=str,
required=True,
help=(
"The config json file corresponding to the pre-trained RemBERT model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
a__ : Tuple = parser.parse_args()
convert_rembert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.rembert_config_file, args.pytorch_dump_path)
| 642 |
import math
import sys
def _lowerCAmelCase ( A__ ):
lowercase__ = ''
try:
with open(A__ , 'rb' ) as binary_file:
lowercase__ = binary_file.read()
for dat in data:
lowercase__ = F'''{dat:08b}'''
result += curr_byte
return result
except OSError:
print('File not accessible' )
sys.exit()
def _lowerCAmelCase ( A__ ):
lowercase__ = {'0': '0', '1': '1'}
lowercase__, lowercase__ = '', ''
lowercase__ = len(A__ )
for i in range(len(A__ ) ):
curr_string += data_bits[i]
if curr_string not in lexicon:
continue
lowercase__ = lexicon[curr_string]
result += last_match_id
lowercase__ = last_match_id + '0'
if math.loga(A__ ).is_integer():
lowercase__ = {}
for curr_key in list(A__ ):
lowercase__ = lexicon.pop(A__ )
lowercase__ = new_lex
lowercase__ = last_match_id + '1'
index += 1
lowercase__ = ''
return result
def _lowerCAmelCase ( A__ , A__ ):
lowercase__ = 8
try:
with open(A__ , 'wb' ) as opened_file:
lowercase__ = [
to_write[i : i + byte_length]
for i in range(0 , len(A__ ) , A__ )
]
if len(result_byte_array[-1] ) % byte_length == 0:
result_byte_array.append('10000000' )
else:
result_byte_array[-1] += "1" + "0" * (
byte_length - len(result_byte_array[-1] ) - 1
)
for elem in result_byte_array[:-1]:
opened_file.write(int(A__ , 2 ).to_bytes(1 , byteorder='big' ) )
except OSError:
print('File not accessible' )
sys.exit()
def _lowerCAmelCase ( A__ ):
lowercase__ = 0
for letter in data_bits:
if letter == "1":
break
counter += 1
lowercase__ = data_bits[counter:]
lowercase__ = data_bits[counter + 1 :]
return data_bits
def _lowerCAmelCase ( A__ , A__ ):
lowercase__ = read_file_binary(A__ )
lowercase__ = remove_prefix(A__ )
lowercase__ = decompress_data(A__ )
write_file_binary(A__ , A__ )
if __name__ == "__main__":
compress(sys.argv[1], sys.argv[2])
| 642 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
_lowercase : Any ={
"configuration_bloom": ["BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP", "BloomConfig", "BloomOnnxConfig"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase : List[str] =["BloomTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase : List[str] =[
"BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST",
"BloomForCausalLM",
"BloomModel",
"BloomPreTrainedModel",
"BloomForSequenceClassification",
"BloomForTokenClassification",
"BloomForQuestionAnswering",
]
if TYPE_CHECKING:
from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_bloom_fast import BloomTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_bloom import (
BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST,
BloomForCausalLM,
BloomForQuestionAnswering,
BloomForSequenceClassification,
BloomForTokenClassification,
BloomModel,
BloomPreTrainedModel,
)
else:
import sys
_lowercase : Tuple =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 364 | import math
import numpy as np
import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute
def _a ( lowercase__ : int = 3 ):
'''simple docstring'''
if isinstance(lowercase__ , lowercase__ ):
raise TypeError('number of qubits must be a integer.' )
if number_of_qubits <= 0:
raise ValueError('number of qubits must be > 0.' )
if math.floor(lowercase__ ) != number_of_qubits:
raise ValueError('number of qubits must be exact integer.' )
if number_of_qubits > 10:
raise ValueError('number of qubits too large to simulate(>10).' )
SCREAMING_SNAKE_CASE__ : Tuple = QuantumRegister(lowercase__ , 'qr' )
SCREAMING_SNAKE_CASE__ : int = ClassicalRegister(lowercase__ , 'cr' )
SCREAMING_SNAKE_CASE__ : Tuple = QuantumCircuit(lowercase__ , lowercase__ )
SCREAMING_SNAKE_CASE__ : Tuple = number_of_qubits
for i in range(lowercase__ ):
quantum_circuit.h(number_of_qubits - i - 1 )
counter -= 1
for j in range(lowercase__ ):
quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase__ , lowercase__ )
for k in range(number_of_qubits // 2 ):
quantum_circuit.swap(lowercase__ , number_of_qubits - k - 1 )
# measure all the qubits
quantum_circuit.measure(lowercase__ , lowercase__ )
# simulate with 10000 shots
SCREAMING_SNAKE_CASE__ : Optional[int] = Aer.get_backend('qasm_simulator' )
SCREAMING_SNAKE_CASE__ : Tuple = execute(lowercase__ , lowercase__ , shots=1_00_00 )
return job.result().get_counts(lowercase__ )
if __name__ == "__main__":
print(
F"""Total count for quantum fourier transform state is: \
{quantum_fourier_transform(3)}"""
)
| 85 | 0 |
import copy
import inspect
import unittest
import numpy as np
from huggingface_hub import hf_hub_download
from transformers import VideoMAEConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import (
MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
VideoMAEForPreTraining,
VideoMAEForVideoClassification,
VideoMAEModel,
)
from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from transformers import VideoMAEImageProcessor
class UpperCAmelCase :
"""simple docstring"""
def __init__( self : Dict , UpperCamelCase__ : str , UpperCamelCase__ : Optional[Any]=13 , UpperCamelCase__ : int=10 , UpperCamelCase__ : int=3 , UpperCamelCase__ : Any=2 , UpperCamelCase__ : List[Any]=2 , UpperCamelCase__ : Optional[int]=2 , UpperCamelCase__ : Dict=True , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=32 , UpperCamelCase__ : str=5 , UpperCamelCase__ : Union[str, Any]=4 , UpperCamelCase__ : Union[str, Any]=37 , UpperCamelCase__ : int="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Optional[int]=10 , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : str=0.9 , UpperCamelCase__ : Optional[Any]=None , ) -> int:
_UpperCamelCase =parent
_UpperCamelCase =batch_size
_UpperCamelCase =image_size
_UpperCamelCase =num_channels
_UpperCamelCase =patch_size
_UpperCamelCase =tubelet_size
_UpperCamelCase =num_frames
_UpperCamelCase =is_training
_UpperCamelCase =use_labels
_UpperCamelCase =hidden_size
_UpperCamelCase =num_hidden_layers
_UpperCamelCase =num_attention_heads
_UpperCamelCase =intermediate_size
_UpperCamelCase =hidden_act
_UpperCamelCase =hidden_dropout_prob
_UpperCamelCase =attention_probs_dropout_prob
_UpperCamelCase =type_sequence_label_size
_UpperCamelCase =initializer_range
_UpperCamelCase =mask_ratio
_UpperCamelCase =scope
# in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
_UpperCamelCase =(image_size // patch_size) ** 2
_UpperCamelCase =(num_frames // tubelet_size) * self.num_patches_per_frame
# use this variable to define bool_masked_pos
_UpperCamelCase =int(mask_ratio * self.seq_length )
def UpperCamelCase__ ( self : Any ) -> Tuple:
_UpperCamelCase =floats_tensor(
[self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] )
_UpperCamelCase =None
if self.use_labels:
_UpperCamelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size )
_UpperCamelCase =self.get_config()
return config, pixel_values, labels
def UpperCamelCase__ ( self : List[str] ) -> str:
return VideoMAEConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , tubelet_size=self.tubelet_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , )
def UpperCamelCase__ ( self : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] ) -> Dict:
_UpperCamelCase =VideoMAEModel(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCamelCase =model(__lowerCAmelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCamelCase__ ( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Any ) -> int:
_UpperCamelCase =VideoMAEForPreTraining(__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
# important: each video needs to have the same number of masked patches
# hence we define a single mask, which we then repeat for each example in the batch
_UpperCamelCase =torch.ones((self.num_masks,) )
_UpperCamelCase =torch.cat([mask, torch.zeros(self.seq_length - mask.size(0 ) )] )
_UpperCamelCase =mask.expand(self.batch_size , -1 ).bool()
_UpperCamelCase =model(__lowerCAmelCase , __lowerCAmelCase )
# model only returns predictions for masked patches
_UpperCamelCase =mask.sum().item()
_UpperCamelCase =3 * self.tubelet_size * self.patch_size**2
self.parent.assertEqual(result.logits.shape , (self.batch_size, num_masked_patches, decoder_num_labels) )
def UpperCamelCase__ ( self : Optional[int] ) -> Union[str, Any]:
_UpperCamelCase =self.prepare_config_and_inputs()
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase =config_and_inputs
_UpperCamelCase ={'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class UpperCAmelCase ( lowercase_ , lowercase_ , unittest.TestCase):
"""simple docstring"""
lowerCAmelCase_ = (
(VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
)
lowerCAmelCase_ = (
{"""feature-extraction""": VideoMAEModel, """video-classification""": VideoMAEForVideoClassification}
if is_torch_available()
else {}
)
lowerCAmelCase_ = False
lowerCAmelCase_ = False
lowerCAmelCase_ = False
lowerCAmelCase_ = False
def UpperCamelCase__ ( self : List[Any] ) -> List[Any]:
_UpperCamelCase =VideoMAEModelTester(self )
_UpperCamelCase =ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=37 )
def UpperCamelCase__ ( self : Optional[int] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : int , UpperCamelCase__ : Tuple=False ) -> Tuple:
_UpperCamelCase =copy.deepcopy(__lowerCAmelCase )
if model_class == VideoMAEForPreTraining:
# important: each video needs to have the same number of masked patches
# hence we define a single mask, which we then repeat for each example in the batch
_UpperCamelCase =torch.ones((self.model_tester.num_masks,) )
_UpperCamelCase =torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0 ) )] )
_UpperCamelCase =mask.expand(self.model_tester.batch_size , -1 ).bool()
_UpperCamelCase =bool_masked_pos.to(__lowerCAmelCase )
if return_labels:
if model_class in [
*get_values(__lowerCAmelCase ),
]:
_UpperCamelCase =torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=__lowerCAmelCase )
return inputs_dict
def UpperCamelCase__ ( self : str ) -> List[Any]:
self.config_tester.run_common_tests()
@unittest.skip(reason='''VideoMAE does not use inputs_embeds''' )
def UpperCamelCase__ ( self : List[Any] ) -> int:
pass
def UpperCamelCase__ ( self : List[Any] ) -> Optional[Any]:
_UpperCamelCase , _UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase =model_class(__lowerCAmelCase )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
_UpperCamelCase =model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__lowerCAmelCase , nn.Linear ) )
def UpperCamelCase__ ( self : Dict ) -> Optional[Any]:
_UpperCamelCase , _UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase =model_class(__lowerCAmelCase )
_UpperCamelCase =inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_UpperCamelCase =[*signature.parameters.keys()]
_UpperCamelCase =['''pixel_values''']
self.assertListEqual(arg_names[:1] , __lowerCAmelCase )
def UpperCamelCase__ ( self : Optional[Any] ) -> Tuple:
_UpperCamelCase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__lowerCAmelCase )
def UpperCamelCase__ ( self : List[str] ) -> int:
_UpperCamelCase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*__lowerCAmelCase )
@slow
def UpperCamelCase__ ( self : Any ) -> Union[str, Any]:
for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase =VideoMAEModel.from_pretrained(__lowerCAmelCase )
self.assertIsNotNone(__lowerCAmelCase )
def UpperCamelCase__ ( self : List[Any] ) -> Tuple:
if not self.has_attentions:
pass
else:
_UpperCamelCase , _UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common()
_UpperCamelCase =True
for model_class in self.all_model_classes:
_UpperCamelCase =self.model_tester.seq_length - self.model_tester.num_masks
_UpperCamelCase =(
num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
)
_UpperCamelCase =True
_UpperCamelCase =False
_UpperCamelCase =True
_UpperCamelCase =model_class(__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
with torch.no_grad():
_UpperCamelCase =model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) )
_UpperCamelCase =outputs.attentions
self.assertEqual(len(__lowerCAmelCase ) , self.model_tester.num_hidden_layers )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
_UpperCamelCase =True
_UpperCamelCase =model_class(__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
with torch.no_grad():
_UpperCamelCase =model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) )
_UpperCamelCase =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, seq_len, seq_len] , )
_UpperCamelCase =len(__lowerCAmelCase )
# Check attention is always last and order is fine
_UpperCamelCase =True
_UpperCamelCase =True
_UpperCamelCase =model_class(__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
with torch.no_grad():
_UpperCamelCase =model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) )
self.assertEqual(out_len + 1 , len(__lowerCAmelCase ) )
_UpperCamelCase =outputs.attentions
self.assertEqual(len(__lowerCAmelCase ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , )
def UpperCamelCase__ ( self : List[str] ) -> Tuple:
def check_hidden_states_output(UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] ):
_UpperCamelCase =model_class(__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
with torch.no_grad():
_UpperCamelCase =model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) )
_UpperCamelCase =outputs.hidden_states
_UpperCamelCase =self.model_tester.num_hidden_layers + 1
self.assertEqual(len(__lowerCAmelCase ) , __lowerCAmelCase )
_UpperCamelCase =self.model_tester.seq_length - self.model_tester.num_masks
_UpperCamelCase =num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , )
_UpperCamelCase , _UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase =True
check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
_UpperCamelCase =True
check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def UpperCamelCase__ ( self : List[str] ) -> str:
pass
def _a ():
"""simple docstring"""
_UpperCamelCase =hf_hub_download(
repo_id='''hf-internal-testing/spaghetti-video''' , filename='''eating_spaghetti.npy''' , repo_type='''dataset''' )
_UpperCamelCase =np.load(__snake_case )
return list(__snake_case )
@require_torch
@require_vision
class UpperCAmelCase ( unittest.TestCase):
"""simple docstring"""
@cached_property
def UpperCamelCase__ ( self : List[Any] ) -> List[str]:
return (
VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] )
if is_vision_available()
else None
)
@slow
def UpperCamelCase__ ( self : str ) -> Optional[int]:
_UpperCamelCase =VideoMAEForVideoClassification.from_pretrained('''MCG-NJU/videomae-base-finetuned-kinetics''' ).to(
__lowerCAmelCase )
_UpperCamelCase =self.default_image_processor
_UpperCamelCase =prepare_video()
_UpperCamelCase =image_processor(__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase )
# forward pass
with torch.no_grad():
_UpperCamelCase =model(**__lowerCAmelCase )
# verify the logits
_UpperCamelCase =torch.Size((1, 400) )
self.assertEqual(outputs.logits.shape , __lowerCAmelCase )
_UpperCamelCase =torch.tensor([0.3669, -0.0688, -0.2421] ).to(__lowerCAmelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) )
@slow
def UpperCamelCase__ ( self : Union[str, Any] ) -> Dict:
_UpperCamelCase =VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short''' ).to(__lowerCAmelCase )
_UpperCamelCase =self.default_image_processor
_UpperCamelCase =prepare_video()
_UpperCamelCase =image_processor(__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase )
# add boolean mask, indicating which patches to mask
_UpperCamelCase =hf_hub_download(repo_id='''hf-internal-testing/bool-masked-pos''' , filename='''bool_masked_pos.pt''' )
_UpperCamelCase =torch.load(__lowerCAmelCase )
# forward pass
with torch.no_grad():
_UpperCamelCase =model(**__lowerCAmelCase )
# verify the logits
_UpperCamelCase =torch.Size([1, 1408, 1536] )
_UpperCamelCase =torch.tensor(
[[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]] , device=__lowerCAmelCase )
self.assertEqual(outputs.logits.shape , __lowerCAmelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) )
# verify the loss (`config.norm_pix_loss` = `True`)
_UpperCamelCase =torch.tensor([0.5142] , device=__lowerCAmelCase )
self.assertTrue(torch.allclose(outputs.loss , __lowerCAmelCase , atol=1E-4 ) )
# verify the loss (`config.norm_pix_loss` = `False`)
_UpperCamelCase =VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short''' , norm_pix_loss=__lowerCAmelCase ).to(
__lowerCAmelCase )
with torch.no_grad():
_UpperCamelCase =model(**__lowerCAmelCase )
_UpperCamelCase =torch.tensor(torch.tensor([0.6469] ) , device=__lowerCAmelCase )
self.assertTrue(torch.allclose(outputs.loss , __lowerCAmelCase , atol=1E-4 ) )
| 707 |
'''simple docstring'''
from collections.abc import Generator
from math import sin
def _a (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if len(__SCREAMING_SNAKE_CASE ) != 32:
raise ValueError('''Input must be of length 32''' )
_UpperCamelCase =b''''''
for i in [3, 2, 1, 0]:
little_endian += string_aa[8 * i : 8 * i + 8]
return little_endian
def _a (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if i < 0:
raise ValueError('''Input must be non-negative''' )
_UpperCamelCase =format(__SCREAMING_SNAKE_CASE , '''08x''' )[-8:]
_UpperCamelCase =b''''''
for i in [3, 2, 1, 0]:
little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('''utf-8''' )
return little_endian_hex
def _a (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
_UpperCamelCase =b''''''
for char in message:
bit_string += format(__SCREAMING_SNAKE_CASE , '''08b''' ).encode('''utf-8''' )
_UpperCamelCase =format(len(__SCREAMING_SNAKE_CASE ) , '''064b''' ).encode('''utf-8''' )
# Pad bit_string to a multiple of 512 chars
bit_string += b"1"
while len(__SCREAMING_SNAKE_CASE ) % 512 != 448:
bit_string += b"0"
bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] )
return bit_string
def _a (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if len(__SCREAMING_SNAKE_CASE ) % 512 != 0:
raise ValueError('''Input must have length that\'s a multiple of 512''' )
for pos in range(0 , len(__SCREAMING_SNAKE_CASE ) , 512 ):
_UpperCamelCase =bit_string[pos : pos + 512]
_UpperCamelCase =[]
for i in range(0 , 512 , 32 ):
block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) )
yield block_words
def _a (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if i < 0:
raise ValueError('''Input must be non-negative''' )
_UpperCamelCase =format(__SCREAMING_SNAKE_CASE , '''032b''' )
_UpperCamelCase =''''''
for c in i_str:
new_str += "1" if c == "0" else "0"
return int(__SCREAMING_SNAKE_CASE , 2 )
def _a (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
return (a + b) % 2**32
def _a (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if i < 0:
raise ValueError('''Input must be non-negative''' )
if shift < 0:
raise ValueError('''Shift must be non-negative''' )
return ((i << shift) ^ (i >> (32 - shift))) % 2**32
def _a (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
_UpperCamelCase =preprocess(__SCREAMING_SNAKE_CASE )
_UpperCamelCase =[int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )]
# Starting states
_UpperCamelCase =0X6745_2301
_UpperCamelCase =0Xefcd_ab89
_UpperCamelCase =0X98ba_dcfe
_UpperCamelCase =0X1032_5476
_UpperCamelCase =[
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
]
# Process bit string in chunks, each with 16 32-char words
for block_words in get_block_words(__SCREAMING_SNAKE_CASE ):
_UpperCamelCase =aa
_UpperCamelCase =ba
_UpperCamelCase =ca
_UpperCamelCase =da
# Hash current chunk
for i in range(64 ):
if i <= 15:
# f = (b & c) | (not_32(b) & d) # Alternate definition for f
_UpperCamelCase =d ^ (b & (c ^ d))
_UpperCamelCase =i
elif i <= 31:
# f = (d & b) | (not_32(d) & c) # Alternate definition for f
_UpperCamelCase =c ^ (d & (b ^ c))
_UpperCamelCase =(5 * i + 1) % 16
elif i <= 47:
_UpperCamelCase =b ^ c ^ d
_UpperCamelCase =(3 * i + 5) % 16
else:
_UpperCamelCase =c ^ (b | not_aa(__SCREAMING_SNAKE_CASE ))
_UpperCamelCase =(7 * i) % 16
_UpperCamelCase =(f + a + added_consts[i] + block_words[g]) % 2**32
_UpperCamelCase =d
_UpperCamelCase =c
_UpperCamelCase =b
_UpperCamelCase =sum_aa(__SCREAMING_SNAKE_CASE , left_rotate_aa(__SCREAMING_SNAKE_CASE , shift_amounts[i] ) )
# Add hashed chunk to running total
_UpperCamelCase =sum_aa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
_UpperCamelCase =sum_aa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
_UpperCamelCase =sum_aa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
_UpperCamelCase =sum_aa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
_UpperCamelCase =reformat_hex(__SCREAMING_SNAKE_CASE ) + reformat_hex(__SCREAMING_SNAKE_CASE ) + reformat_hex(__SCREAMING_SNAKE_CASE ) + reformat_hex(__SCREAMING_SNAKE_CASE )
return digest
if __name__ == "__main__":
import doctest
doctest.testmod()
| 271 | 0 |
def lowerCAmelCase_ ( A_):
UpperCamelCase__: List[Any] = [0] * len(A_)
UpperCamelCase__: Any = []
UpperCamelCase__: str = []
UpperCamelCase__: Any = 0
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(A_)):
if indegree[i] == 0:
queue.append(A_)
while queue:
UpperCamelCase__: Dict = queue.pop(0)
cnt += 1
topo.append(A_)
for x in graph[vertex]:
indegree[x] -= 1
if indegree[x] == 0:
queue.append(A_)
if cnt != len(A_):
print("Cycle exists")
else:
print(A_)
# Adjacency List of Graph
A__: Dict = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
topological_sort(graph)
| 380 |
import math
def lowerCAmelCase_ ( A_ ,A_):
UpperCamelCase__: Dict = len(A_)
UpperCamelCase__: Optional[Any] = int(math.floor(math.sqrt(A_)))
UpperCamelCase__: Union[str, Any] = 0
while arr[min(A_ ,A_) - 1] < x:
UpperCamelCase__: Any = step
step += int(math.floor(math.sqrt(A_)))
if prev >= n:
return -1
while arr[prev] < x:
UpperCamelCase__: Dict = prev + 1
if prev == min(A_ ,A_):
return -1
if arr[prev] == x:
return prev
return -1
if __name__ == "__main__":
A__: Tuple = input('''Enter numbers separated by a comma:\n''').strip()
A__: List[Any] = [int(item) for item in user_input.split(''',''')]
A__: int = int(input('''Enter the number to be searched:\n'''))
A__: Any = jump_search(arr, x)
if res == -1:
print('''Number not found!''')
else:
print(f"Number {x} is at index {res}")
| 380 | 1 |
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ) -> bool:
if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ : Optional[Any] = f'Input value of [number={number}] must be an integer'
raise TypeError(SCREAMING_SNAKE_CASE )
if number < 0:
return False
SCREAMING_SNAKE_CASE_ : Tuple = number * number
while number > 0:
if number % 10 != number_square % 10:
return False
number //= 10
number_square //= 10
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
| 311 |
from string import ascii_lowercase, ascii_uppercase
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ) -> str:
if not sentence:
return ""
SCREAMING_SNAKE_CASE_ : int = dict(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) )
return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:]
if __name__ == "__main__":
from doctest import testmod
testmod()
| 311 | 1 |
"""simple docstring"""
from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
A_ = (3, 9, -11, 0, 7, 5, 1, -1)
A_ = (4, 6, 2, 0, 8, 10, 3, -2)
@dataclass
class __lowerCamelCase :
a__: int
a__: Node | None
class __lowerCamelCase :
def __init__( self , UpperCAmelCase ):
lowerCamelCase_ = None
for i in sorted(UpperCAmelCase , reverse=UpperCAmelCase ):
lowerCamelCase_ = Node(UpperCAmelCase , self.head )
def __iter__( self ):
lowerCamelCase_ = self.head
while node:
yield node.data
lowerCamelCase_ = node.next_node
def __len__( self ):
return sum(1 for _ in self )
def __str__( self ):
return " -> ".join([str(UpperCAmelCase ) for node in self] )
def lowercase ( lowerCAmelCase__ ,lowerCAmelCase__ ):
return SortedLinkedList(list(lowerCAmelCase__ ) + list(lowerCAmelCase__ ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
A_ = SortedLinkedList
print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
| 29 |
"""simple docstring"""
import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List
import git
import torch
from torch.utils.data import Dataset
from transformers import BartTokenizer, RagTokenizer, TaTokenizer
def lowerCamelCase (a_ :List[Any] , a_ :Union[str, Any] , a_ :Tuple , a_ :List[str] , a_ :str=True , a_ :str="pt") -> List[str]:
lowercase :Optional[int] = {'''add_prefix_space''': True} if isinstance(a_ , a_) and not line.startswith(''' ''') else {}
lowercase :Optional[int] = padding_side
return tokenizer(
[line] , max_length=a_ , padding='''max_length''' if pad_to_max_length else None , truncation=a_ , return_tensors=a_ , add_special_tokens=a_ , **a_ , )
def lowerCamelCase (a_ :str , a_ :Tuple , a_ :Optional[Any]=None , ) -> Tuple:
lowercase :Optional[Any] = input_ids.ne(a_).any(dim=0)
if attention_mask is None:
return input_ids[:, keep_column_mask]
else:
return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class __magic_name__ ( __UpperCAmelCase ):
def __init__( self : Union[str, Any] , snake_case__ : Union[str, Any] , snake_case__ : Optional[Any] , snake_case__ : Optional[Any] , snake_case__ : Optional[Any] , snake_case__ : str="train" , snake_case__ : Optional[Any]=None , snake_case__ : Tuple=None , snake_case__ : Any=None , snake_case__ : Dict="" , ):
'''simple docstring'''
super().__init__()
lowercase :Tuple = Path(snake_case__ ).joinpath(type_path + '''.source''' )
lowercase :Union[str, Any] = Path(snake_case__ ).joinpath(type_path + '''.target''' )
lowercase :List[Any] = self.get_char_lens(self.src_file )
lowercase :Tuple = max_source_length
lowercase :Optional[int] = max_target_length
assert min(self.src_lens ) > 0, f"""found empty line in {self.src_file}"""
lowercase :Any = tokenizer
lowercase :Tuple = prefix
if n_obs is not None:
lowercase :List[str] = self.src_lens[:n_obs]
lowercase :List[Any] = src_lang
lowercase :str = tgt_lang
def __len__( self : Any ):
'''simple docstring'''
return len(self.src_lens )
def __getitem__( self : str , snake_case__ : Any ):
'''simple docstring'''
lowercase :Optional[int] = index + 1 # linecache starts at 1
lowercase :Optional[Any] = self.prefix + linecache.getline(str(self.src_file ) , snake_case__ ).rstrip('''\n''' )
lowercase :Dict = linecache.getline(str(self.tgt_file ) , snake_case__ ).rstrip('''\n''' )
assert source_line, f"""empty source line for index {index}"""
assert tgt_line, f"""empty tgt line for index {index}"""
# Need to add eos token manually for T5
if isinstance(self.tokenizer , snake_case__ ):
source_line += self.tokenizer.eos_token
tgt_line += self.tokenizer.eos_token
# Pad source and target to the right
lowercase :Dict = (
self.tokenizer.question_encoder if isinstance(self.tokenizer , snake_case__ ) else self.tokenizer
)
lowercase :Optional[int] = self.tokenizer.generator if isinstance(self.tokenizer , snake_case__ ) else self.tokenizer
lowercase :Optional[int] = encode_line(snake_case__ , snake_case__ , self.max_source_length , '''right''' )
lowercase :Tuple = encode_line(snake_case__ , snake_case__ , self.max_target_length , '''right''' )
lowercase :List[str] = source_inputs['''input_ids'''].squeeze()
lowercase :Optional[Any] = target_inputs['''input_ids'''].squeeze()
lowercase :List[str] = source_inputs['''attention_mask'''].squeeze()
return {
"input_ids": source_ids,
"attention_mask": src_mask,
"decoder_input_ids": target_ids,
}
@staticmethod
def __snake_case ( snake_case__ : Optional[int] ):
'''simple docstring'''
return [len(snake_case__ ) for x in Path(snake_case__ ).open().readlines()]
def __snake_case ( self : Tuple , snake_case__ : Union[str, Any] ):
'''simple docstring'''
lowercase :Optional[Any] = torch.stack([x['''input_ids'''] for x in batch] )
lowercase :Tuple = torch.stack([x['''attention_mask'''] for x in batch] )
lowercase :Tuple = torch.stack([x['''decoder_input_ids'''] for x in batch] )
lowercase :str = (
self.tokenizer.generator.pad_token_id
if isinstance(self.tokenizer , snake_case__ )
else self.tokenizer.pad_token_id
)
lowercase :Optional[int] = (
self.tokenizer.question_encoder.pad_token_id
if isinstance(self.tokenizer , snake_case__ )
else self.tokenizer.pad_token_id
)
lowercase :List[Any] = trim_batch(snake_case__ , snake_case__ )
lowercase , lowercase :List[str] = trim_batch(snake_case__ , snake_case__ , attention_mask=snake_case__ )
lowercase :Optional[int] = {
'''input_ids''': source_ids,
'''attention_mask''': source_mask,
'''decoder_input_ids''': y,
}
return batch
UpperCAmelCase = getLogger(__name__)
def lowerCamelCase (a_ :List[List]) -> Tuple:
return list(itertools.chain.from_iterable(a_))
def lowerCamelCase (a_ :str) -> None:
lowercase :List[str] = get_git_info()
save_json(a_ , os.path.join(a_ , '''git_log.json'''))
def lowerCamelCase (a_ :Optional[int] , a_ :Optional[int] , a_ :Optional[Any]=4 , **a_ :Optional[Any]) -> str:
with open(a_ , '''w''') as f:
json.dump(a_ , a_ , indent=a_ , **a_)
def lowerCamelCase (a_ :Dict) -> Union[str, Any]:
with open(a_) as f:
return json.load(a_)
def lowerCamelCase () -> List[str]:
lowercase :Dict = git.Repo(search_parent_directories=a_)
lowercase :int = {
'''repo_id''': str(a_),
'''repo_sha''': str(repo.head.object.hexsha),
'''repo_branch''': str(repo.active_branch),
'''hostname''': str(socket.gethostname()),
}
return repo_infos
def lowerCamelCase (a_ :Callable , a_ :Iterable) -> List:
return list(map(a_ , a_))
def lowerCamelCase (a_ :Optional[Any] , a_ :str) -> Any:
with open(a_ , '''wb''') as f:
return pickle.dump(a_ , a_)
def lowerCamelCase (a_ :List[str]) -> List[str]:
def remove_articles(a_ :Union[str, Any]):
return re.sub(R'''\b(a|an|the)\b''' , ''' ''' , a_)
def white_space_fix(a_ :Tuple):
return " ".join(text.split())
def remove_punc(a_ :int):
lowercase :List[Any] = set(string.punctuation)
return "".join(ch for ch in text if ch not in exclude)
def lower(a_ :int):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(a_))))
def lowerCamelCase (a_ :List[str] , a_ :Any) -> List[str]:
lowercase :Dict = normalize_answer(a_).split()
lowercase :int = normalize_answer(a_).split()
lowercase :List[Any] = Counter(a_) & Counter(a_)
lowercase :Optional[int] = sum(common.values())
if num_same == 0:
return 0
lowercase :str = 1.0 * num_same / len(a_)
lowercase :Tuple = 1.0 * num_same / len(a_)
lowercase :Tuple = (2 * precision * recall) / (precision + recall)
return fa
def lowerCamelCase (a_ :Tuple , a_ :Optional[Any]) -> List[Any]:
return normalize_answer(a_) == normalize_answer(a_)
def lowerCamelCase (a_ :List[str] , a_ :List[str]) -> Dict:
assert len(a_) == len(a_)
lowercase :Any = 0
for hypo, pred in zip(a_ , a_):
em += exact_match_score(a_ , a_)
if len(a_) > 0:
em /= len(a_)
return {"em": em}
def lowerCamelCase (a_ :Union[str, Any]) -> Optional[Any]:
return model_prefix.startswith('''rag''')
def lowerCamelCase (a_ :List[str] , a_ :Tuple , a_ :List[str]) -> Any:
lowercase :List[str] = {p: p for p in extra_params}
# T5 models don't have `dropout` param, they have `dropout_rate` instead
lowercase :str = '''dropout_rate'''
for p in extra_params:
if getattr(a_ , a_ , a_):
if not hasattr(a_ , a_) and not hasattr(a_ , equivalent_param[p]):
logger.info('''config doesn\'t have a `{}` attribute'''.format(a_))
delattr(a_ , a_)
continue
lowercase :List[str] = p if hasattr(a_ , a_) else equivalent_param[p]
setattr(a_ , a_ , getattr(a_ , a_))
delattr(a_ , a_)
return hparams, config
| 677 | 0 |
from random import shuffle
import tensorflow as tf
from numpy import array
def _lowerCAmelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Optional[Any] = int(__lowerCamelCase )
assert noofclusters < len(__lowerCamelCase )
# Find out the dimensionality
__SCREAMING_SNAKE_CASE : List[str] = len(vectors[0] )
# Will help select random centroids from among the available vectors
__SCREAMING_SNAKE_CASE : List[Any] = list(range(len(__lowerCamelCase ) ) )
shuffle(__lowerCamelCase )
# GRAPH OF COMPUTATION
# We initialize a new graph and set it as the default during each run
# of this algorithm. This ensures that as this function is called
# multiple times, the default graph doesn't keep getting crowded with
# unused ops and Variables from previous function calls.
__SCREAMING_SNAKE_CASE : Optional[int] = tf.Graph()
with graph.as_default():
# SESSION OF COMPUTATION
__SCREAMING_SNAKE_CASE : str = tf.Session()
##CONSTRUCTING THE ELEMENTS OF COMPUTATION
##First lets ensure we have a Variable vector for each centroid,
##initialized to one of the vectors from the available data points
__SCREAMING_SNAKE_CASE : Union[str, Any] = [
tf.Variable(vectors[vector_indices[i]] ) for i in range(__lowerCamelCase )
]
##These nodes will assign the centroid Variables the appropriate
##values
__SCREAMING_SNAKE_CASE : List[Any] = tf.placeholder("float64" , [dim] )
__SCREAMING_SNAKE_CASE : int = []
for centroid in centroids:
cent_assigns.append(tf.assign(__lowerCamelCase , __lowerCamelCase ) )
##Variables for cluster assignments of individual vectors(initialized
##to 0 at first)
__SCREAMING_SNAKE_CASE : Dict = [tf.Variable(0 ) for i in range(len(__lowerCamelCase ) )]
##These nodes will assign an assignment Variable the appropriate
##value
__SCREAMING_SNAKE_CASE : Tuple = tf.placeholder("int32" )
__SCREAMING_SNAKE_CASE : str = []
for assignment in assignments:
cluster_assigns.append(tf.assign(__lowerCamelCase , __lowerCamelCase ) )
##Now lets construct the node that will compute the mean
# The placeholder for the input
__SCREAMING_SNAKE_CASE : Tuple = tf.placeholder("float" , [None, dim] )
# The Node/op takes the input and computes a mean along the 0th
# dimension, i.e. the list of input vectors
__SCREAMING_SNAKE_CASE : Any = tf.reduce_mean(__lowerCamelCase , 0 )
##Node for computing Euclidean distances
# Placeholders for input
__SCREAMING_SNAKE_CASE : List[Any] = tf.placeholder("float" , [dim] )
__SCREAMING_SNAKE_CASE : Optional[int] = tf.placeholder("float" , [dim] )
__SCREAMING_SNAKE_CASE : Any = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(__lowerCamelCase , __lowerCamelCase ) , 2 ) ) )
##This node will figure out which cluster to assign a vector to,
##based on Euclidean distances of the vector from the centroids.
# Placeholder for input
__SCREAMING_SNAKE_CASE : Tuple = tf.placeholder("float" , [noofclusters] )
__SCREAMING_SNAKE_CASE : Optional[int] = tf.argmin(__lowerCamelCase , 0 )
##INITIALIZING STATE VARIABLES
##This will help initialization of all Variables defined with respect
##to the graph. The Variable-initializer should be defined after
##all the Variables have been constructed, so that each of them
##will be included in the initialization.
__SCREAMING_SNAKE_CASE : Optional[int] = tf.initialize_all_variables()
# Initialize all variables
sess.run(__lowerCamelCase )
##CLUSTERING ITERATIONS
# Now perform the Expectation-Maximization steps of K-Means clustering
# iterations. To keep things simple, we will only do a set number of
# iterations, instead of using a Stopping Criterion.
__SCREAMING_SNAKE_CASE : Optional[Any] = 100
for _ in range(__lowerCamelCase ):
##EXPECTATION STEP
##Based on the centroid locations till last iteration, compute
##the _expected_ centroid assignments.
# Iterate over each vector
for vector_n in range(len(__lowerCamelCase ) ):
__SCREAMING_SNAKE_CASE : List[Any] = vectors[vector_n]
# Compute Euclidean distance between this vector and each
# centroid. Remember that this list cannot be named
#'centroid_distances', since that is the input to the
# cluster assignment node.
__SCREAMING_SNAKE_CASE : Tuple = [
sess.run(__lowerCamelCase , feed_dict={va: vect, va: sess.run(__lowerCamelCase )} )
for centroid in centroids
]
# Now use the cluster assignment node, with the distances
# as the input
__SCREAMING_SNAKE_CASE : Optional[Any] = sess.run(
__lowerCamelCase , feed_dict={centroid_distances: distances} )
# Now assign the value to the appropriate state variable
sess.run(
cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} )
##MAXIMIZATION STEP
# Based on the expected state computed from the Expectation Step,
# compute the locations of the centroids so as to maximize the
# overall objective of minimizing within-cluster Sum-of-Squares
for cluster_n in range(__lowerCamelCase ):
# Collect all the vectors assigned to this cluster
__SCREAMING_SNAKE_CASE : Any = [
vectors[i]
for i in range(len(__lowerCamelCase ) )
if sess.run(assignments[i] ) == cluster_n
]
# Compute new centroid location
__SCREAMING_SNAKE_CASE : Union[str, Any] = sess.run(
__lowerCamelCase , feed_dict={mean_input: array(__lowerCamelCase )} )
# Assign value to appropriate variable
sess.run(
cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} )
# Return centroids and assignments
__SCREAMING_SNAKE_CASE : List[Any] = sess.run(__lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = sess.run(__lowerCamelCase )
return centroids, assignments
| 447 |
from collections.abc import Generator
from math import sin
def _lowerCAmelCase ( __lowerCamelCase : bytes ):
"""simple docstring"""
if len(__lowerCamelCase ) != 32:
raise ValueError("Input must be of length 32" )
__SCREAMING_SNAKE_CASE : Union[str, Any] = b""
for i in [3, 2, 1, 0]:
little_endian += string_aa[8 * i : 8 * i + 8]
return little_endian
def _lowerCAmelCase ( __lowerCamelCase : int ):
"""simple docstring"""
if i < 0:
raise ValueError("Input must be non-negative" )
__SCREAMING_SNAKE_CASE : Any = format(__lowerCamelCase , "08x" )[-8:]
__SCREAMING_SNAKE_CASE : Optional[Any] = b""
for i in [3, 2, 1, 0]:
little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8" )
return little_endian_hex
def _lowerCAmelCase ( __lowerCamelCase : bytes ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Any = b""
for char in message:
bit_string += format(__lowerCamelCase , "08b" ).encode("utf-8" )
__SCREAMING_SNAKE_CASE : List[str] = format(len(__lowerCamelCase ) , "064b" ).encode("utf-8" )
# Pad bit_string to a multiple of 512 chars
bit_string += b"1"
while len(__lowerCamelCase ) % 512 != 448:
bit_string += b"0"
bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] )
return bit_string
def _lowerCAmelCase ( __lowerCamelCase : bytes ):
"""simple docstring"""
if len(__lowerCamelCase ) % 512 != 0:
raise ValueError("Input must have length that's a multiple of 512" )
for pos in range(0 , len(__lowerCamelCase ) , 512 ):
__SCREAMING_SNAKE_CASE : int = bit_string[pos : pos + 512]
__SCREAMING_SNAKE_CASE : Tuple = []
for i in range(0 , 512 , 32 ):
block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) )
yield block_words
def _lowerCAmelCase ( __lowerCamelCase : int ):
"""simple docstring"""
if i < 0:
raise ValueError("Input must be non-negative" )
__SCREAMING_SNAKE_CASE : Union[str, Any] = format(__lowerCamelCase , "032b" )
__SCREAMING_SNAKE_CASE : Union[str, Any] = ""
for c in i_str:
new_str += "1" if c == "0" else "0"
return int(__lowerCamelCase , 2 )
def _lowerCAmelCase ( __lowerCamelCase : int , __lowerCamelCase : int ):
"""simple docstring"""
return (a + b) % 2**32
def _lowerCAmelCase ( __lowerCamelCase : int , __lowerCamelCase : int ):
"""simple docstring"""
if i < 0:
raise ValueError("Input must be non-negative" )
if shift < 0:
raise ValueError("Shift must be non-negative" )
return ((i << shift) ^ (i >> (32 - shift))) % 2**32
def _lowerCAmelCase ( __lowerCamelCase : bytes ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Tuple = preprocess(__lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )]
# Starting states
__SCREAMING_SNAKE_CASE : Tuple = 0X67452301
__SCREAMING_SNAKE_CASE : Optional[Any] = 0Xefcdab89
__SCREAMING_SNAKE_CASE : Optional[int] = 0X98badcfe
__SCREAMING_SNAKE_CASE : Optional[Any] = 0X10325476
__SCREAMING_SNAKE_CASE : List[Any] = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
]
# Process bit string in chunks, each with 16 32-char words
for block_words in get_block_words(__lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Any = aa
__SCREAMING_SNAKE_CASE : Union[str, Any] = ba
__SCREAMING_SNAKE_CASE : str = ca
__SCREAMING_SNAKE_CASE : Dict = da
# Hash current chunk
for i in range(64 ):
if i <= 15:
# f = (b & c) | (not_32(b) & d) # Alternate definition for f
__SCREAMING_SNAKE_CASE : Union[str, Any] = d ^ (b & (c ^ d))
__SCREAMING_SNAKE_CASE : Optional[Any] = i
elif i <= 31:
# f = (d & b) | (not_32(d) & c) # Alternate definition for f
__SCREAMING_SNAKE_CASE : int = c ^ (d & (b ^ c))
__SCREAMING_SNAKE_CASE : int = (5 * i + 1) % 16
elif i <= 47:
__SCREAMING_SNAKE_CASE : List[str] = b ^ c ^ d
__SCREAMING_SNAKE_CASE : Union[str, Any] = (3 * i + 5) % 16
else:
__SCREAMING_SNAKE_CASE : Any = c ^ (b | not_aa(__lowerCamelCase ))
__SCREAMING_SNAKE_CASE : str = (7 * i) % 16
__SCREAMING_SNAKE_CASE : List[str] = (f + a + added_consts[i] + block_words[g]) % 2**32
__SCREAMING_SNAKE_CASE : Dict = d
__SCREAMING_SNAKE_CASE : str = c
__SCREAMING_SNAKE_CASE : Tuple = b
__SCREAMING_SNAKE_CASE : Optional[int] = sum_aa(__lowerCamelCase , left_rotate_aa(__lowerCamelCase , shift_amounts[i] ) )
# Add hashed chunk to running total
__SCREAMING_SNAKE_CASE : Dict = sum_aa(__lowerCamelCase , __lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = sum_aa(__lowerCamelCase , __lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = sum_aa(__lowerCamelCase , __lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = sum_aa(__lowerCamelCase , __lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = reformat_hex(__lowerCamelCase ) + reformat_hex(__lowerCamelCase ) + reformat_hex(__lowerCamelCase ) + reformat_hex(__lowerCamelCase )
return digest
if __name__ == "__main__":
import doctest
doctest.testmod()
| 447 | 1 |
'''simple docstring'''
from typing import List
import numpy as np
def A__ ( UpperCAmelCase_ ):
_UpperCamelCase : Any = {key: len(UpperCAmelCase_ ) for key, value in gen_kwargs.items() if isinstance(UpperCAmelCase_ , UpperCAmelCase_ )}
if len(set(lists_lengths.values() ) ) > 1:
raise RuntimeError(
(
'Sharding is ambiguous for this dataset: '
+ 'we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n'
+ '\n'.join(f'\t- key {key} has length {length}' for key, length in lists_lengths.items() )
+ '\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, '
+ 'and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.'
) )
_UpperCamelCase : Tuple = max(lists_lengths.values() , default=0 )
return max(1 , UpperCAmelCase_ )
def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ):
_UpperCamelCase : Dict = []
for group_idx in range(UpperCAmelCase_ ):
_UpperCamelCase : int = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs))
if num_shards_to_add == 0:
break
_UpperCamelCase : Tuple = shards_indices_per_group[-1].stop if shards_indices_per_group else 0
_UpperCamelCase : Tuple = range(UpperCAmelCase_ , start + num_shards_to_add )
shards_indices_per_group.append(UpperCAmelCase_ )
return shards_indices_per_group
def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ):
_UpperCamelCase : Tuple = _number_of_shards_in_gen_kwargs(UpperCAmelCase_ )
if num_shards == 1:
return [dict(UpperCAmelCase_ )]
else:
_UpperCamelCase : str = _distribute_shards(num_shards=UpperCAmelCase_ , max_num_jobs=UpperCAmelCase_ )
return [
{
key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]]
if isinstance(UpperCAmelCase_ , UpperCAmelCase_ )
else value
for key, value in gen_kwargs.items()
}
for group_idx in range(len(UpperCAmelCase_ ) )
]
def A__ ( UpperCAmelCase_ ):
return {
key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]]
if isinstance(gen_kwargs_list[0][key] , UpperCAmelCase_ )
else gen_kwargs_list[0][key]
for key in gen_kwargs_list[0]
}
def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ):
_UpperCamelCase : int = {len(UpperCAmelCase_ ) for value in gen_kwargs.values() if isinstance(UpperCAmelCase_ , UpperCAmelCase_ )}
_UpperCamelCase : Union[str, Any] = {}
for size in list_sizes:
_UpperCamelCase : str = list(range(UpperCAmelCase_ ) )
rng.shuffle(indices_per_size[size] )
# Now let's copy the gen_kwargs and shuffle the lists based on their sizes
_UpperCamelCase : Union[str, Any] = dict(UpperCAmelCase_ )
for key, value in shuffled_kwargs.items():
if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ):
_UpperCamelCase : Dict = [value[i] for i in indices_per_size[len(UpperCAmelCase_ )]]
return shuffled_kwargs
| 195 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
snake_case_ : Tuple = {
'configuration_layoutlmv2': ['LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv2Config'],
'processing_layoutlmv2': ['LayoutLMv2Processor'],
'tokenization_layoutlmv2': ['LayoutLMv2Tokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ : int = ['LayoutLMv2TokenizerFast']
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ : Union[str, Any] = ['LayoutLMv2FeatureExtractor']
snake_case_ : str = ['LayoutLMv2ImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ : Optional[int] = [
'LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST',
'LayoutLMv2ForQuestionAnswering',
'LayoutLMv2ForSequenceClassification',
'LayoutLMv2ForTokenClassification',
'LayoutLMv2Layer',
'LayoutLMv2Model',
'LayoutLMv2PreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig
from .processing_layoutlmva import LayoutLMvaProcessor
from .tokenization_layoutlmva import LayoutLMvaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_layoutlmva import (
LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST,
LayoutLMvaForQuestionAnswering,
LayoutLMvaForSequenceClassification,
LayoutLMvaForTokenClassification,
LayoutLMvaLayer,
LayoutLMvaModel,
LayoutLMvaPreTrainedModel,
)
else:
import sys
snake_case_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 195 | 1 |
'''simple docstring'''
from itertools import product
def SCREAMING_SNAKE_CASE__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
lowerCAmelCase_ : Tuple =sides_number
lowerCAmelCase_ : Tuple =max_face_number * dice_number
lowerCAmelCase_ : Tuple =[0] * (max_total + 1)
lowerCAmelCase_ : Any =1
lowerCAmelCase_ : Dict =range(_SCREAMING_SNAKE_CASE , max_face_number + 1 )
for dice_numbers in product(_SCREAMING_SNAKE_CASE , repeat=_SCREAMING_SNAKE_CASE ):
lowerCAmelCase_ : Union[str, Any] =sum(_SCREAMING_SNAKE_CASE )
totals_frequencies[total] += 1
return totals_frequencies
def SCREAMING_SNAKE_CASE__ ( ):
lowerCAmelCase_ : Dict =total_frequency_distribution(
sides_number=4 , dice_number=9 )
lowerCAmelCase_ : Any =total_frequency_distribution(
sides_number=6 , dice_number=6 )
lowerCAmelCase_ : str =0
lowerCAmelCase_ : Any =9
lowerCAmelCase_ : Tuple =4 * 9
lowerCAmelCase_ : Union[str, Any] =6
for peter_total in range(_SCREAMING_SNAKE_CASE , max_peter_total + 1 ):
peter_wins_count += peter_totals_frequencies[peter_total] * sum(
colin_totals_frequencies[min_colin_total:peter_total] )
lowerCAmelCase_ : List[Any] =(4**9) * (6**6)
lowerCAmelCase_ : Tuple =peter_wins_count / total_games_number
lowerCAmelCase_ : Optional[int] =round(_SCREAMING_SNAKE_CASE , ndigits=7 )
return rounded_peter_win_probability
if __name__ == "__main__":
print(f'{solution() = }')
| 305 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowercase = logging.get_logger(__name__)
__lowercase = {
'''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''',
}
class _snake_case ( lowerCAmelCase_ ):
"""simple docstring"""
_UpperCamelCase : str = '''gpt_bigcode'''
_UpperCamelCase : Optional[int] = ['''past_key_values''']
_UpperCamelCase : Any = {
'''hidden_size''': '''n_embd''',
'''max_position_embeddings''': '''n_positions''',
'''num_attention_heads''': '''n_head''',
'''num_hidden_layers''': '''n_layer''',
}
def __init__( self : List[Any] , UpperCamelCase_ : List[Any]=50257 , UpperCamelCase_ : List[Any]=1024 , UpperCamelCase_ : List[Any]=768 , UpperCamelCase_ : Tuple=12 , UpperCamelCase_ : List[str]=12 , UpperCamelCase_ : str=None , UpperCamelCase_ : Dict="gelu_pytorch_tanh" , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : Dict=0.1 , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : Any=1E-5 , UpperCamelCase_ : Dict=0.0_2 , UpperCamelCase_ : List[Any]=True , UpperCamelCase_ : Any=True , UpperCamelCase_ : Union[str, Any]=50256 , UpperCamelCase_ : List[str]=50256 , UpperCamelCase_ : Union[str, Any]=True , UpperCamelCase_ : List[str]=True , UpperCamelCase_ : Tuple=True , **UpperCamelCase_ : str , ):
lowerCAmelCase_ : Optional[Any] =vocab_size
lowerCAmelCase_ : Optional[int] =n_positions
lowerCAmelCase_ : Union[str, Any] =n_embd
lowerCAmelCase_ : str =n_layer
lowerCAmelCase_ : int =n_head
lowerCAmelCase_ : List[str] =n_inner
lowerCAmelCase_ : Tuple =activation_function
lowerCAmelCase_ : List[str] =resid_pdrop
lowerCAmelCase_ : List[str] =embd_pdrop
lowerCAmelCase_ : Any =attn_pdrop
lowerCAmelCase_ : int =layer_norm_epsilon
lowerCAmelCase_ : int =initializer_range
lowerCAmelCase_ : str =scale_attn_weights
lowerCAmelCase_ : Union[str, Any] =use_cache
lowerCAmelCase_ : int =attention_softmax_in_fpaa
lowerCAmelCase_ : List[Any] =scale_attention_softmax_in_fpaa
lowerCAmelCase_ : Optional[int] =multi_query
lowerCAmelCase_ : Optional[int] =bos_token_id
lowerCAmelCase_ : Any =eos_token_id
super().__init__(bos_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ )
| 305 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
lowerCAmelCase : List[str] = {
'''configuration_clap''': [
'''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ClapAudioConfig''',
'''ClapConfig''',
'''ClapTextConfig''',
],
'''processing_clap''': ['''ClapProcessor'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase : List[Any] = [
'''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ClapModel''',
'''ClapPreTrainedModel''',
'''ClapTextModel''',
'''ClapTextModelWithProjection''',
'''ClapAudioModel''',
'''ClapAudioModelWithProjection''',
]
lowerCAmelCase : Union[str, Any] = ['''ClapFeatureExtractor''']
if TYPE_CHECKING:
from .configuration_clap import (
CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
ClapAudioConfig,
ClapConfig,
ClapTextConfig,
)
from .processing_clap import ClapProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_clap import ClapFeatureExtractor
from .modeling_clap import (
CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
ClapAudioModel,
ClapAudioModelWithProjection,
ClapModel,
ClapPreTrainedModel,
ClapTextModel,
ClapTextModelWithProjection,
)
else:
import sys
lowerCAmelCase : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 543 |
"""simple docstring"""
import re
import string
from collections import Counter
import sacrebleu
import sacremoses
from packaging import version
import datasets
__SCREAMING_SNAKE_CASE : Optional[int] = '''
@inproceedings{xu-etal-2016-optimizing,
title = {Optimizing Statistical Machine Translation for Text Simplification},
authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},
journal = {Transactions of the Association for Computational Linguistics},
volume = {4},
year={2016},
url = {https://www.aclweb.org/anthology/Q16-1029},
pages = {401--415
},
@inproceedings{post-2018-call,
title = "A Call for Clarity in Reporting {BLEU} Scores",
author = "Post, Matt",
booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",
month = oct,
year = "2018",
address = "Belgium, Brussels",
publisher = "Association for Computational Linguistics",
url = "https://www.aclweb.org/anthology/W18-6319",
pages = "186--191",
}
'''
__SCREAMING_SNAKE_CASE : List[str] = '''\
WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU
It can be used to evaluate the quality of machine-generated texts.
'''
__SCREAMING_SNAKE_CASE : Optional[Any] = '''
Calculates sari score (between 0 and 100) given a list of source and predicted
sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.
Args:
sources: list of source sentences where each sentence should be a string.
predictions: list of predicted sentences where each sentence should be a string.
references: list of lists of reference sentences where each sentence should be a string.
Returns:
sari: sari score
sacrebleu: sacrebleu score
exact: exact score
Examples:
>>> sources=["About 95 species are currently accepted ."]
>>> predictions=["About 95 you now get in ."]
>>> references=[["About 95 species are currently known ."]]
>>> wiki_split = datasets.load_metric("wiki_split")
>>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)
>>> print(results)
{\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0}
'''
def lowerCAmelCase_( lowercase_ : Union[str, Any] ) -> str:
def remove_articles(lowercase_ : int ):
_lowerCamelCase = re.compile(r'''\b(a|an|the)\b''' , re.UNICODE )
return re.sub(lowercase_ , ''' ''' , lowercase_ )
def white_space_fix(lowercase_ : List[Any] ):
return " ".join(text.split() )
def remove_punc(lowercase_ : Dict ):
_lowerCamelCase = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowercase_ : Union[str, Any] ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) )
def lowerCAmelCase_( lowercase_ : List[str] , lowercase_ : Optional[Any] ) -> Union[str, Any]:
return int(normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) )
def lowerCAmelCase_( lowercase_ : Any , lowercase_ : Tuple ) -> Tuple:
_lowerCamelCase = [any(compute_exact(lowercase_ , lowercase_ ) for ref in refs ) for pred, refs in zip(lowercase_ , lowercase_ )]
return (sum(lowercase_ ) / len(lowercase_ )) * 1_00
def lowerCAmelCase_( lowercase_ : Tuple , lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : str ) -> Optional[int]:
_lowerCamelCase = [rgram for rgrams in rgramslist for rgram in rgrams]
_lowerCamelCase = Counter(lowercase_ )
_lowerCamelCase = Counter(lowercase_ )
_lowerCamelCase = Counter()
for sgram, scount in sgramcounter.items():
_lowerCamelCase = scount * numref
_lowerCamelCase = Counter(lowercase_ )
_lowerCamelCase = Counter()
for cgram, ccount in cgramcounter.items():
_lowerCamelCase = ccount * numref
# KEEP
_lowerCamelCase = sgramcounter_rep & cgramcounter_rep
_lowerCamelCase = keepgramcounter_rep & rgramcounter
_lowerCamelCase = sgramcounter_rep & rgramcounter
_lowerCamelCase = 0
_lowerCamelCase = 0
for keepgram in keepgramcountergood_rep:
keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram]
# Fix an alleged bug [2] in the keep score computation.
# keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram]
keeptmpscorea += keepgramcountergood_rep[keepgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
_lowerCamelCase = 1
_lowerCamelCase = 1
if len(lowercase_ ) > 0:
_lowerCamelCase = keeptmpscorea / len(lowercase_ )
if len(lowercase_ ) > 0:
# Fix an alleged bug [2] in the keep score computation.
# keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
_lowerCamelCase = keeptmpscorea / sum(keepgramcounterall_rep.values() )
_lowerCamelCase = 0
if keepscore_precision > 0 or keepscore_recall > 0:
_lowerCamelCase = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)
# DELETION
_lowerCamelCase = sgramcounter_rep - cgramcounter_rep
_lowerCamelCase = delgramcounter_rep - rgramcounter
_lowerCamelCase = sgramcounter_rep - rgramcounter
_lowerCamelCase = 0
_lowerCamelCase = 0
for delgram in delgramcountergood_rep:
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram]
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
_lowerCamelCase = 1
if len(lowercase_ ) > 0:
_lowerCamelCase = deltmpscorea / len(lowercase_ )
# ADDITION
_lowerCamelCase = set(lowercase_ ) - set(lowercase_ )
_lowerCamelCase = set(lowercase_ ) & set(lowercase_ )
_lowerCamelCase = set(lowercase_ ) - set(lowercase_ )
_lowerCamelCase = 0
for addgram in addgramcountergood:
addtmpscore += 1
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
_lowerCamelCase = 1
_lowerCamelCase = 1
if len(lowercase_ ) > 0:
_lowerCamelCase = addtmpscore / len(lowercase_ )
if len(lowercase_ ) > 0:
_lowerCamelCase = addtmpscore / len(lowercase_ )
_lowerCamelCase = 0
if addscore_precision > 0 or addscore_recall > 0:
_lowerCamelCase = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)
return (keepscore, delscore_precision, addscore)
def lowerCAmelCase_( lowercase_ : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : str ) -> List[str]:
_lowerCamelCase = len(lowercase_ )
_lowerCamelCase = ssent.split(''' ''' )
_lowerCamelCase = csent.split(''' ''' )
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
for rsent in rsents:
_lowerCamelCase = rsent.split(''' ''' )
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
ragramslist.append(lowercase_ )
for i in range(0 , len(lowercase_ ) - 1 ):
if i < len(lowercase_ ) - 1:
_lowerCamelCase = ragrams[i] + ''' ''' + ragrams[i + 1]
ragrams.append(lowercase_ )
if i < len(lowercase_ ) - 2:
_lowerCamelCase = ragrams[i] + ''' ''' + ragrams[i + 1] + ''' ''' + ragrams[i + 2]
ragrams.append(lowercase_ )
if i < len(lowercase_ ) - 3:
_lowerCamelCase = ragrams[i] + ''' ''' + ragrams[i + 1] + ''' ''' + ragrams[i + 2] + ''' ''' + ragrams[i + 3]
ragrams.append(lowercase_ )
ragramslist.append(lowercase_ )
ragramslist.append(lowercase_ )
ragramslist.append(lowercase_ )
for i in range(0 , len(lowercase_ ) - 1 ):
if i < len(lowercase_ ) - 1:
_lowerCamelCase = sagrams[i] + ''' ''' + sagrams[i + 1]
sagrams.append(lowercase_ )
if i < len(lowercase_ ) - 2:
_lowerCamelCase = sagrams[i] + ''' ''' + sagrams[i + 1] + ''' ''' + sagrams[i + 2]
sagrams.append(lowercase_ )
if i < len(lowercase_ ) - 3:
_lowerCamelCase = sagrams[i] + ''' ''' + sagrams[i + 1] + ''' ''' + sagrams[i + 2] + ''' ''' + sagrams[i + 3]
sagrams.append(lowercase_ )
for i in range(0 , len(lowercase_ ) - 1 ):
if i < len(lowercase_ ) - 1:
_lowerCamelCase = cagrams[i] + ''' ''' + cagrams[i + 1]
cagrams.append(lowercase_ )
if i < len(lowercase_ ) - 2:
_lowerCamelCase = cagrams[i] + ''' ''' + cagrams[i + 1] + ''' ''' + cagrams[i + 2]
cagrams.append(lowercase_ )
if i < len(lowercase_ ) - 3:
_lowerCamelCase = cagrams[i] + ''' ''' + cagrams[i + 1] + ''' ''' + cagrams[i + 2] + ''' ''' + cagrams[i + 3]
cagrams.append(lowercase_ )
((_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase)) = SARIngram(lowercase_ , lowercase_ , lowercase_ , lowercase_ )
((_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase)) = SARIngram(lowercase_ , lowercase_ , lowercase_ , lowercase_ )
((_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase)) = SARIngram(lowercase_ , lowercase_ , lowercase_ , lowercase_ )
((_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase)) = SARIngram(lowercase_ , lowercase_ , lowercase_ , lowercase_ )
_lowerCamelCase = sum([keepascore, keepascore, keepascore, keepascore] ) / 4
_lowerCamelCase = sum([delascore, delascore, delascore, delascore] ) / 4
_lowerCamelCase = sum([addascore, addascore, addascore, addascore] ) / 4
_lowerCamelCase = (avgkeepscore + avgdelscore + avgaddscore) / 3
return finalscore
def lowerCAmelCase_( lowercase_ : List[str] , lowercase_ : bool = True , lowercase_ : str = "13a" , lowercase_ : bool = True ) -> int:
# Normalization is requried for the ASSET dataset (one of the primary
# datasets in sentence simplification) to allow using space
# to split the sentence. Even though Wiki-Auto and TURK datasets,
# do not require normalization, we do it for consistency.
# Code adapted from the EASSE library [1] written by the authors of the ASSET dataset.
# [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7
if lowercase:
_lowerCamelCase = sentence.lower()
if tokenizer in ["13a", "intl"]:
if version.parse(sacrebleu.__version__ ).major >= 2:
_lowerCamelCase = sacrebleu.metrics.bleu._get_tokenizer(lowercase_ )()(lowercase_ )
else:
_lowerCamelCase = sacrebleu.TOKENIZERS[tokenizer]()(lowercase_ )
elif tokenizer == "moses":
_lowerCamelCase = sacremoses.MosesTokenizer().tokenize(lowercase_ , return_str=lowercase_ , escape=lowercase_ )
elif tokenizer == "penn":
_lowerCamelCase = sacremoses.MosesTokenizer().penn_tokenize(lowercase_ , return_str=lowercase_ )
else:
_lowerCamelCase = sentence
if not return_str:
_lowerCamelCase = normalized_sent.split()
return normalized_sent
def lowerCAmelCase_( lowercase_ : Any , lowercase_ : Any , lowercase_ : List[Any] ) -> Optional[int]:
if not (len(lowercase_ ) == len(lowercase_ ) == len(lowercase_ )):
raise ValueError('''Sources length must match predictions and references lengths.''' )
_lowerCamelCase = 0
for src, pred, refs in zip(lowercase_ , lowercase_ , lowercase_ ):
sari_score += SARIsent(normalize(lowercase_ ) , normalize(lowercase_ ) , [normalize(lowercase_ ) for sent in refs] )
_lowerCamelCase = sari_score / len(lowercase_ )
return 1_00 * sari_score
def lowerCAmelCase_( lowercase_ : Any , lowercase_ : Any , lowercase_ : List[Any]="exp" , lowercase_ : List[Any]=None , lowercase_ : Optional[Any]=False , lowercase_ : List[Any]=False , lowercase_ : List[Any]=False , ) -> Dict:
_lowerCamelCase = len(references[0] )
if any(len(lowercase_ ) != references_per_prediction for refs in references ):
raise ValueError('''Sacrebleu requires the same number of references for each prediction''' )
_lowerCamelCase = [[refs[i] for refs in references] for i in range(lowercase_ )]
_lowerCamelCase = sacrebleu.corpus_bleu(
lowercase_ , lowercase_ , smooth_method=lowercase_ , smooth_value=lowercase_ , force=lowercase_ , lowercase=lowercase_ , use_effective_order=lowercase_ , )
return output.score
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION )
class lowerCamelCase_( datasets.Metric ):
'''simple docstring'''
def snake_case__ ( self ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''string''' , id='''sequence''' ),
'''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ),
} ) , codebase_urls=[
'''https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py''',
'''https://github.com/cocoxu/simplification/blob/master/SARI.py''',
'''https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py''',
'''https://github.com/mjpost/sacreBLEU''',
] , reference_urls=[
'''https://www.aclweb.org/anthology/Q16-1029.pdf''',
'''https://github.com/mjpost/sacreBLEU''',
'''https://en.wikipedia.org/wiki/BLEU''',
'''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''',
] , )
def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
_lowerCamelCase = {}
result.update({'''sari''': compute_sari(sources=lowerCamelCase__ , predictions=lowerCamelCase__ , references=lowerCamelCase__ )} )
result.update({'''sacrebleu''': compute_sacrebleu(predictions=lowerCamelCase__ , references=lowerCamelCase__ )} )
result.update({'''exact''': compute_em(predictions=lowerCamelCase__ , references=lowerCamelCase__ )} )
return result
| 661 | 0 |
'''simple docstring'''
import os
from collections.abc import Iterator
def _lowerCAmelCase( UpperCAmelCase_ : str = "." ) -> Iterator[str]:
for dir_path, dir_names, filenames in os.walk(_lowerCamelCase ):
lowerCAmelCase__ = [d for d in dir_names if d != "scripts" and d[0] not in "._"]
for filename in filenames:
if filename == "__init__.py":
continue
if os.path.splitext(_lowerCamelCase )[1] in (".py", ".ipynb"):
yield os.path.join(_lowerCamelCase , _lowerCamelCase ).lstrip("""./""" )
def _lowerCAmelCase( UpperCAmelCase_ : List[str] ) -> Any:
return F'''{i * " "}*''' if i else "\n##"
def _lowerCAmelCase( UpperCAmelCase_ : str , UpperCAmelCase_ : str ) -> str:
lowerCAmelCase__ = old_path.split(os.sep )
for i, new_part in enumerate(new_path.split(os.sep ) ):
if (i + 1 > len(_lowerCamelCase ) or old_parts[i] != new_part) and new_part:
print(F'''{md_prefix(_lowerCamelCase )} {new_part.replace("_" , " " ).title()}''' )
return new_path
def _lowerCAmelCase( UpperCAmelCase_ : str = "." ) -> None:
lowerCAmelCase__ = ""
for filepath in sorted(good_file_paths(_lowerCamelCase ) ):
lowerCAmelCase__ = os.path.split(_lowerCamelCase )
if filepath != old_path:
lowerCAmelCase__ = print_path(_lowerCamelCase , _lowerCamelCase )
lowerCAmelCase__ = (filepath.count(os.sep ) + 1) if filepath else 0
lowerCAmelCase__ = F'''{filepath}/{filename}'''.replace(""" """ , """%20""" )
lowerCAmelCase__ = os.path.splitext(filename.replace("""_""" , """ """ ).title() )[0]
print(F'''{md_prefix(_lowerCamelCase )} [{filename}]({url})''' )
if __name__ == "__main__":
print_directory_md(""".""")
| 706 |
'''simple docstring'''
import argparse
import requests
import torch
from PIL import Image
from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor
def _lowerCAmelCase( UpperCAmelCase_ : List[Any] ) -> List[str]:
lowerCAmelCase__ = SwinConfig(image_size=192 )
if "base" in model_name:
lowerCAmelCase__ = 6
lowerCAmelCase__ = 128
lowerCAmelCase__ = (2, 2, 18, 2)
lowerCAmelCase__ = (4, 8, 16, 32)
elif "large" in model_name:
lowerCAmelCase__ = 12
lowerCAmelCase__ = 192
lowerCAmelCase__ = (2, 2, 18, 2)
lowerCAmelCase__ = (6, 12, 24, 48)
else:
raise ValueError("""Model not supported, only supports base and large variants""" )
lowerCAmelCase__ = window_size
lowerCAmelCase__ = embed_dim
lowerCAmelCase__ = depths
lowerCAmelCase__ = num_heads
return config
def _lowerCAmelCase( UpperCAmelCase_ : str ) -> List[str]:
if "encoder.mask_token" in name:
lowerCAmelCase__ = name.replace("""encoder.mask_token""" , """embeddings.mask_token""" )
if "encoder.patch_embed.proj" in name:
lowerCAmelCase__ = name.replace("""encoder.patch_embed.proj""" , """embeddings.patch_embeddings.projection""" )
if "encoder.patch_embed.norm" in name:
lowerCAmelCase__ = name.replace("""encoder.patch_embed.norm""" , """embeddings.norm""" )
if "attn.proj" in name:
lowerCAmelCase__ = name.replace("""attn.proj""" , """attention.output.dense""" )
if "attn" in name:
lowerCAmelCase__ = name.replace("""attn""" , """attention.self""" )
if "norm1" in name:
lowerCAmelCase__ = name.replace("""norm1""" , """layernorm_before""" )
if "norm2" in name:
lowerCAmelCase__ = name.replace("""norm2""" , """layernorm_after""" )
if "mlp.fc1" in name:
lowerCAmelCase__ = name.replace("""mlp.fc1""" , """intermediate.dense""" )
if "mlp.fc2" in name:
lowerCAmelCase__ = name.replace("""mlp.fc2""" , """output.dense""" )
if name == "encoder.norm.weight":
lowerCAmelCase__ = """layernorm.weight"""
if name == "encoder.norm.bias":
lowerCAmelCase__ = """layernorm.bias"""
if "decoder" in name:
pass
else:
lowerCAmelCase__ = """swin.""" + name
return name
def _lowerCAmelCase( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple ) -> Union[str, Any]:
for key in orig_state_dict.copy().keys():
lowerCAmelCase__ = orig_state_dict.pop(UpperCAmelCase_ )
if "attn_mask" in key:
pass
elif "qkv" in key:
lowerCAmelCase__ = key.split(""".""" )
lowerCAmelCase__ = int(key_split[2] )
lowerCAmelCase__ = int(key_split[4] )
lowerCAmelCase__ = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size
if "weight" in key:
lowerCAmelCase__ = val[:dim, :]
lowerCAmelCase__ = val[
dim : dim * 2, :
]
lowerCAmelCase__ = val[-dim:, :]
else:
lowerCAmelCase__ = val[
:dim
]
lowerCAmelCase__ = val[
dim : dim * 2
]
lowerCAmelCase__ = val[
-dim:
]
else:
lowerCAmelCase__ = val
return orig_state_dict
def _lowerCAmelCase( UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] ) -> Tuple:
lowerCAmelCase__ = torch.load(UpperCAmelCase_ , map_location="""cpu""" )["""model"""]
lowerCAmelCase__ = get_swin_config(UpperCAmelCase_ )
lowerCAmelCase__ = SwinForMaskedImageModeling(UpperCAmelCase_ )
model.eval()
lowerCAmelCase__ = convert_state_dict(UpperCAmelCase_ , UpperCAmelCase_ )
model.load_state_dict(UpperCAmelCase_ )
lowerCAmelCase__ = """http://images.cocodataset.org/val2017/000000039769.jpg"""
lowerCAmelCase__ = ViTImageProcessor(size={"""height""": 192, """width""": 192} )
lowerCAmelCase__ = Image.open(requests.get(UpperCAmelCase_ , stream=UpperCAmelCase_ ).raw )
lowerCAmelCase__ = image_processor(images=UpperCAmelCase_ , return_tensors="""pt""" )
with torch.no_grad():
lowerCAmelCase__ = model(**UpperCAmelCase_ ).logits
print(outputs.keys() )
print("""Looks ok!""" )
if pytorch_dump_folder_path is not None:
print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(UpperCAmelCase_ )
print(F'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(UpperCAmelCase_ )
if push_to_hub:
print(F'''Pushing model and image processor for {model_name} to hub''' )
model.push_to_hub(F'''microsoft/{model_name}''' )
image_processor.push_to_hub(F'''microsoft/{model_name}''' )
if __name__ == "__main__":
_UpperCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--model_name""",
default="""swin-base-simmim-window6-192""",
type=str,
choices=["""swin-base-simmim-window6-192""", """swin-large-simmim-window12-192"""],
help="""Name of the Swin SimMIM model you'd like to convert.""",
)
parser.add_argument(
"""--checkpoint_path""",
default="""/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth""",
type=str,
help="""Path to the original PyTorch checkpoint (.pth file).""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
parser.add_argument(
"""--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
)
_UpperCamelCase = parser.parse_args()
convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
| 211 | 0 |
'''simple docstring'''
import os
from dataclasses import dataclass, field
from io import BytesIO
from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union
import numpy as np
import pyarrow as pa
from .. import config
from ..download.streaming_download_manager import xopen, xsplitext
from ..table import array_cast
from ..utils.py_utils import no_op_if_value_is_null, string_to_dict
if TYPE_CHECKING:
from .features import FeatureType
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Any = False, False, False
@dataclass
class lowerCAmelCase :
__lowercase : List[str] = None
__lowercase : Dict = True
__lowercase : Tuple = True
__lowercase : Union[str, Any] = None
# Automatically constructed
__lowercase : List[str] = '''dict'''
__lowercase : Union[str, Any] = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()})
__lowercase : int = field(default='''Audio''' , init=__lowercase , repr=__lowercase)
def __call__( self ) -> Any:
'''simple docstring'''
return self.pa_type
def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> Dict:
'''simple docstring'''
try:
import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files.
except ImportError as err:
raise ImportError('''To support encoding audio data, please install \'soundfile\'.''' ) from err
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
return {"bytes": None, "path": value}
elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
return {"bytes": value, "path": None}
elif "array" in value:
# convert the audio array to wav bytes
__snake_case = BytesIO()
sf.write(_SCREAMING_SNAKE_CASE , value['''array'''] , value['''sampling_rate'''] , format='''wav''' )
return {"bytes": buffer.getvalue(), "path": None}
elif value.get('''path''' ) is not None and os.path.isfile(value['''path'''] ):
# we set "bytes": None to not duplicate the data if they're already available locally
if value["path"].endswith('''pcm''' ):
# "PCM" only has raw audio bytes
if value.get('''sampling_rate''' ) is None:
# At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate
raise KeyError('''To use PCM files, please specify a \'sampling_rate\' in Audio object''' )
if value.get('''bytes''' ):
# If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!)
__snake_case = np.frombuffer(value['''bytes'''] , dtype=np.intaa ).astype(np.floataa ) / 3_2767
else:
__snake_case = np.memmap(value['''path'''] , dtype='''h''' , mode='''r''' ).astype(np.floataa ) / 3_2767
__snake_case = BytesIO(bytes() )
sf.write(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , value['''sampling_rate'''] , format='''wav''' )
return {"bytes": buffer.getvalue(), "path": None}
else:
return {"bytes": None, "path": value.get('''path''' )}
elif value.get('''bytes''' ) is not None or value.get('''path''' ) is not None:
# store the audio bytes, and path is used to infer the audio format using the file extension
return {"bytes": value.get('''bytes''' ), "path": value.get('''path''' )}
else:
raise ValueError(
F'''An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' )
def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ) -> str:
'''simple docstring'''
if not self.decode:
raise RuntimeError('''Decoding is disabled for this feature. Please use Audio(decode=True) instead.''' )
__snake_case , __snake_case = (value['''path'''], BytesIO(value['''bytes'''] )) if value['''bytes'''] is not None else (value['''path'''], None)
if path is None and file is None:
raise ValueError(F'''An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.''' )
try:
import librosa
import soundfile as sf
except ImportError as err:
raise ImportError('''To support decoding audio files, please install \'librosa\' and \'soundfile\'.''' ) from err
__snake_case = xsplitext(_SCREAMING_SNAKE_CASE )[1][1:].lower() if path is not None else None
if not config.IS_OPUS_SUPPORTED and audio_format == "opus":
raise RuntimeError(
'''Decoding \'opus\' files requires system library \'libsndfile\'>=1.0.31, '''
'''You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. ''' )
elif not config.IS_MP3_SUPPORTED and audio_format == "mp3":
raise RuntimeError(
'''Decoding \'mp3\' files requires system library \'libsndfile\'>=1.1.0, '''
'''You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. ''' )
if file is None:
__snake_case = token_per_repo_id or {}
__snake_case = path.split('''::''' )[-1]
try:
__snake_case = string_to_dict(_SCREAMING_SNAKE_CASE , config.HUB_DATASETS_URL )['''repo_id''']
__snake_case = token_per_repo_id[repo_id]
except (ValueError, KeyError):
__snake_case = None
with xopen(_SCREAMING_SNAKE_CASE , '''rb''' , use_auth_token=_SCREAMING_SNAKE_CASE ) as f:
__snake_case , __snake_case = sf.read(_SCREAMING_SNAKE_CASE )
else:
__snake_case , __snake_case = sf.read(_SCREAMING_SNAKE_CASE )
__snake_case = array.T
if self.mono:
__snake_case = librosa.to_mono(_SCREAMING_SNAKE_CASE )
if self.sampling_rate and self.sampling_rate != sampling_rate:
__snake_case = librosa.resample(_SCREAMING_SNAKE_CASE , orig_sr=_SCREAMING_SNAKE_CASE , target_sr=self.sampling_rate )
__snake_case = self.sampling_rate
return {"path": path, "array": array, "sampling_rate": sampling_rate}
def lowerCAmelCase ( self ) -> int:
'''simple docstring'''
from .features import Value
if self.decode:
raise ValueError('''Cannot flatten a decoded Audio feature.''' )
return {
"bytes": Value('''binary''' ),
"path": Value('''string''' ),
}
def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> Optional[int]:
'''simple docstring'''
if pa.types.is_string(storage.type ):
__snake_case = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.binary() )
__snake_case = pa.StructArray.from_arrays([bytes_array, storage] , ['''bytes''', '''path'''] , mask=storage.is_null() )
elif pa.types.is_binary(storage.type ):
__snake_case = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.string() )
__snake_case = pa.StructArray.from_arrays([storage, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null() )
elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices('''array''' ):
__snake_case = pa.array([Audio().encode_example(_SCREAMING_SNAKE_CASE ) if x is not None else None for x in storage.to_pylist()] )
elif pa.types.is_struct(storage.type ):
if storage.type.get_field_index('''bytes''' ) >= 0:
__snake_case = storage.field('''bytes''' )
else:
__snake_case = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.binary() )
if storage.type.get_field_index('''path''' ) >= 0:
__snake_case = storage.field('''path''' )
else:
__snake_case = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.string() )
__snake_case = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null() )
return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type )
def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> Tuple:
'''simple docstring'''
@no_op_if_value_is_null
def path_to_bytes(__SCREAMING_SNAKE_CASE ):
with xopen(_SCREAMING_SNAKE_CASE , '''rb''' ) as f:
__snake_case = f.read()
return bytes_
__snake_case = pa.array(
[
(path_to_bytes(x['''path'''] ) if x['''bytes'''] is None else x['''bytes''']) if x is not None else None
for x in storage.to_pylist()
] , type=pa.binary() , )
__snake_case = pa.array(
[os.path.basename(_SCREAMING_SNAKE_CASE ) if path is not None else None for path in storage.field('''path''' ).to_pylist()] , type=pa.string() , )
__snake_case = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null() )
return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type )
| 24 |
from collections import OrderedDict
from ...utils import logging
from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
from .configuration_auto import CONFIG_MAPPING_NAMES
a = logging.get_logger(__name__)
a = OrderedDict(
[
# Base model mapping
("albert", "FlaxAlbertModel"),
("bart", "FlaxBartModel"),
("beit", "FlaxBeitModel"),
("bert", "FlaxBertModel"),
("big_bird", "FlaxBigBirdModel"),
("blenderbot", "FlaxBlenderbotModel"),
("blenderbot-small", "FlaxBlenderbotSmallModel"),
("clip", "FlaxCLIPModel"),
("distilbert", "FlaxDistilBertModel"),
("electra", "FlaxElectraModel"),
("gpt-sw3", "FlaxGPT2Model"),
("gpt2", "FlaxGPT2Model"),
("gpt_neo", "FlaxGPTNeoModel"),
("gptj", "FlaxGPTJModel"),
("longt5", "FlaxLongT5Model"),
("marian", "FlaxMarianModel"),
("mbart", "FlaxMBartModel"),
("mt5", "FlaxMT5Model"),
("opt", "FlaxOPTModel"),
("pegasus", "FlaxPegasusModel"),
("regnet", "FlaxRegNetModel"),
("resnet", "FlaxResNetModel"),
("roberta", "FlaxRobertaModel"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"),
("roformer", "FlaxRoFormerModel"),
("t5", "FlaxT5Model"),
("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"),
("vit", "FlaxViTModel"),
("wav2vec2", "FlaxWav2Vec2Model"),
("whisper", "FlaxWhisperModel"),
("xglm", "FlaxXGLMModel"),
("xlm-roberta", "FlaxXLMRobertaModel"),
]
)
a = OrderedDict(
[
# Model for pre-training mapping
("albert", "FlaxAlbertForPreTraining"),
("bart", "FlaxBartForConditionalGeneration"),
("bert", "FlaxBertForPreTraining"),
("big_bird", "FlaxBigBirdForPreTraining"),
("electra", "FlaxElectraForPreTraining"),
("longt5", "FlaxLongT5ForConditionalGeneration"),
("mbart", "FlaxMBartForConditionalGeneration"),
("mt5", "FlaxMT5ForConditionalGeneration"),
("roberta", "FlaxRobertaForMaskedLM"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"),
("roformer", "FlaxRoFormerForMaskedLM"),
("t5", "FlaxT5ForConditionalGeneration"),
("wav2vec2", "FlaxWav2Vec2ForPreTraining"),
("whisper", "FlaxWhisperForConditionalGeneration"),
("xlm-roberta", "FlaxXLMRobertaForMaskedLM"),
]
)
a = OrderedDict(
[
# Model for Masked LM mapping
("albert", "FlaxAlbertForMaskedLM"),
("bart", "FlaxBartForConditionalGeneration"),
("bert", "FlaxBertForMaskedLM"),
("big_bird", "FlaxBigBirdForMaskedLM"),
("distilbert", "FlaxDistilBertForMaskedLM"),
("electra", "FlaxElectraForMaskedLM"),
("mbart", "FlaxMBartForConditionalGeneration"),
("roberta", "FlaxRobertaForMaskedLM"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"),
("roformer", "FlaxRoFormerForMaskedLM"),
("xlm-roberta", "FlaxXLMRobertaForMaskedLM"),
]
)
a = OrderedDict(
[
# Model for Seq2Seq Causal LM mapping
("bart", "FlaxBartForConditionalGeneration"),
("blenderbot", "FlaxBlenderbotForConditionalGeneration"),
("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"),
("encoder-decoder", "FlaxEncoderDecoderModel"),
("longt5", "FlaxLongT5ForConditionalGeneration"),
("marian", "FlaxMarianMTModel"),
("mbart", "FlaxMBartForConditionalGeneration"),
("mt5", "FlaxMT5ForConditionalGeneration"),
("pegasus", "FlaxPegasusForConditionalGeneration"),
("t5", "FlaxT5ForConditionalGeneration"),
]
)
a = OrderedDict(
[
# Model for Image-classsification
("beit", "FlaxBeitForImageClassification"),
("regnet", "FlaxRegNetForImageClassification"),
("resnet", "FlaxResNetForImageClassification"),
("vit", "FlaxViTForImageClassification"),
]
)
a = OrderedDict(
[
("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"),
]
)
a = OrderedDict(
[
# Model for Causal LM mapping
("bart", "FlaxBartForCausalLM"),
("bert", "FlaxBertForCausalLM"),
("big_bird", "FlaxBigBirdForCausalLM"),
("electra", "FlaxElectraForCausalLM"),
("gpt-sw3", "FlaxGPT2LMHeadModel"),
("gpt2", "FlaxGPT2LMHeadModel"),
("gpt_neo", "FlaxGPTNeoForCausalLM"),
("gptj", "FlaxGPTJForCausalLM"),
("opt", "FlaxOPTForCausalLM"),
("roberta", "FlaxRobertaForCausalLM"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"),
("xglm", "FlaxXGLMForCausalLM"),
("xlm-roberta", "FlaxXLMRobertaForCausalLM"),
]
)
a = OrderedDict(
[
# Model for Sequence Classification mapping
("albert", "FlaxAlbertForSequenceClassification"),
("bart", "FlaxBartForSequenceClassification"),
("bert", "FlaxBertForSequenceClassification"),
("big_bird", "FlaxBigBirdForSequenceClassification"),
("distilbert", "FlaxDistilBertForSequenceClassification"),
("electra", "FlaxElectraForSequenceClassification"),
("mbart", "FlaxMBartForSequenceClassification"),
("roberta", "FlaxRobertaForSequenceClassification"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"),
("roformer", "FlaxRoFormerForSequenceClassification"),
("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"),
]
)
a = OrderedDict(
[
# Model for Question Answering mapping
("albert", "FlaxAlbertForQuestionAnswering"),
("bart", "FlaxBartForQuestionAnswering"),
("bert", "FlaxBertForQuestionAnswering"),
("big_bird", "FlaxBigBirdForQuestionAnswering"),
("distilbert", "FlaxDistilBertForQuestionAnswering"),
("electra", "FlaxElectraForQuestionAnswering"),
("mbart", "FlaxMBartForQuestionAnswering"),
("roberta", "FlaxRobertaForQuestionAnswering"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"),
("roformer", "FlaxRoFormerForQuestionAnswering"),
("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"),
]
)
a = OrderedDict(
[
# Model for Token Classification mapping
("albert", "FlaxAlbertForTokenClassification"),
("bert", "FlaxBertForTokenClassification"),
("big_bird", "FlaxBigBirdForTokenClassification"),
("distilbert", "FlaxDistilBertForTokenClassification"),
("electra", "FlaxElectraForTokenClassification"),
("roberta", "FlaxRobertaForTokenClassification"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"),
("roformer", "FlaxRoFormerForTokenClassification"),
("xlm-roberta", "FlaxXLMRobertaForTokenClassification"),
]
)
a = OrderedDict(
[
# Model for Multiple Choice mapping
("albert", "FlaxAlbertForMultipleChoice"),
("bert", "FlaxBertForMultipleChoice"),
("big_bird", "FlaxBigBirdForMultipleChoice"),
("distilbert", "FlaxDistilBertForMultipleChoice"),
("electra", "FlaxElectraForMultipleChoice"),
("roberta", "FlaxRobertaForMultipleChoice"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"),
("roformer", "FlaxRoFormerForMultipleChoice"),
("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"),
]
)
a = OrderedDict(
[
("bert", "FlaxBertForNextSentencePrediction"),
]
)
a = OrderedDict(
[
("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"),
("whisper", "FlaxWhisperForConditionalGeneration"),
]
)
a = OrderedDict(
[
("whisper", "FlaxWhisperForAudioClassification"),
]
)
a = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES)
a = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES)
a = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES)
a = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
)
a = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
)
a = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
a = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
a = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
)
a = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
)
a = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
)
a = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES
)
a = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
)
a = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
)
a = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
)
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_MAPPING
a = auto_class_update(FlaxAutoModel)
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_PRETRAINING_MAPPING
a = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining")
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING
a = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling")
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_MASKED_LM_MAPPING
a = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling")
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
a = auto_class_update(
FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base"
)
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
a = auto_class_update(
FlaxAutoModelForSequenceClassification, head_doc="sequence classification"
)
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING
a = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering")
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
a = auto_class_update(
FlaxAutoModelForTokenClassification, head_doc="token classification"
)
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING
a = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice")
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
a = auto_class_update(
FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction"
)
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
a = auto_class_update(
FlaxAutoModelForImageClassification, head_doc="image classification"
)
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING
a = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling")
class _A ( _BaseAutoModelClass ):
__a = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
a = auto_class_update(
FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling"
) | 518 | 0 |
import argparse
import json
import os
import pickle
import shutil
import numpy as np
import torch
from distiller import Distiller
from lm_seqs_dataset import LmSeqsDataset
from transformers import (
BertConfig,
BertForMaskedLM,
BertTokenizer,
DistilBertConfig,
DistilBertForMaskedLM,
DistilBertTokenizer,
GPTaConfig,
GPTaLMHeadModel,
GPTaTokenizer,
RobertaConfig,
RobertaForMaskedLM,
RobertaTokenizer,
)
from utils import git_log, init_gpu_params, logger, set_seed
lowerCamelCase_ = {
'''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer),
'''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer),
'''bert''': (BertConfig, BertForMaskedLM, BertTokenizer),
'''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer),
}
def __magic_name__ ( __a : Any ):
assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0)
assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0)
if args.mlm:
assert os.path.isfile(args.token_counts )
assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"])
else:
assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"])
assert args.teacher_type == args.student_type or (
args.student_type == "distilbert" and args.teacher_type == "bert"
)
assert os.path.isfile(args.student_config )
if args.student_pretrained_weights is not None:
assert os.path.isfile(args.student_pretrained_weights )
if args.freeze_token_type_embds:
assert args.student_type in ["roberta"]
assert args.alpha_ce >= 0.0
assert args.alpha_mlm >= 0.0
assert args.alpha_clm >= 0.0
assert args.alpha_mse >= 0.0
assert args.alpha_cos >= 0.0
assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0
def __magic_name__ ( __a : List[Any] , __a : Any ):
if args.student_type == "roberta":
UpperCamelCase__ = False
elif args.student_type == "gpt2":
UpperCamelCase__ = False
def __magic_name__ ( __a : int , __a : Dict ):
if args.student_type == "roberta":
UpperCamelCase__ = False
def __magic_name__ ( ):
UpperCamelCase__ = argparse.ArgumentParser(description="""Training""" )
parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" )
parser.add_argument(
"""--dump_path""" , type=__a , required=__a , help="""The output directory (log, checkpoints, parameters, etc.)""" )
parser.add_argument(
"""--data_file""" , type=__a , required=__a , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , )
parser.add_argument(
"""--student_type""" , type=__a , choices=["""distilbert""", """roberta""", """gpt2"""] , required=__a , help="""The student type (DistilBERT, RoBERTa).""" , )
parser.add_argument("""--student_config""" , type=__a , required=__a , help="""Path to the student configuration.""" )
parser.add_argument(
"""--student_pretrained_weights""" , default=__a , type=__a , help="""Load student initialization checkpoint.""" )
parser.add_argument(
"""--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=__a , help="""Teacher type (BERT, RoBERTa).""" )
parser.add_argument("""--teacher_name""" , type=__a , required=__a , help="""The teacher model.""" )
parser.add_argument("""--temperature""" , default=2.0 , type=__a , help="""Temperature for the softmax temperature.""" )
parser.add_argument(
"""--alpha_ce""" , default=0.5 , type=__a , help="""Linear weight for the distillation loss. Must be >=0.""" )
parser.add_argument(
"""--alpha_mlm""" , default=0.0 , type=__a , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , )
parser.add_argument("""--alpha_clm""" , default=0.5 , type=__a , help="""Linear weight for the CLM loss. Must be >=0.""" )
parser.add_argument("""--alpha_mse""" , default=0.0 , type=__a , help="""Linear weight of the MSE loss. Must be >=0.""" )
parser.add_argument(
"""--alpha_cos""" , default=0.0 , type=__a , help="""Linear weight of the cosine embedding loss. Must be >=0.""" )
parser.add_argument(
"""--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" )
parser.add_argument(
"""--mlm_mask_prop""" , default=0.15 , type=__a , help="""Proportion of tokens for which we need to make a prediction.""" , )
parser.add_argument("""--word_mask""" , default=0.8 , type=__a , help="""Proportion of tokens to mask out.""" )
parser.add_argument("""--word_keep""" , default=0.1 , type=__a , help="""Proportion of tokens to keep.""" )
parser.add_argument("""--word_rand""" , default=0.1 , type=__a , help="""Proportion of tokens to randomly replace.""" )
parser.add_argument(
"""--mlm_smoothing""" , default=0.7 , type=__a , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , )
parser.add_argument("""--token_counts""" , type=__a , help="""The token counts in the data_file for MLM.""" )
parser.add_argument(
"""--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , )
parser.add_argument(
"""--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , )
parser.add_argument(
"""--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , )
parser.add_argument("""--n_epoch""" , type=__a , default=3 , help="""Number of pass on the whole dataset.""" )
parser.add_argument("""--batch_size""" , type=__a , default=5 , help="""Batch size (for each process).""" )
parser.add_argument(
"""--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , )
parser.add_argument(
"""--gradient_accumulation_steps""" , type=__a , default=50 , help="""Gradient accumulation for larger training batches.""" , )
parser.add_argument("""--warmup_prop""" , default=0.05 , type=__a , help="""Linear warmup proportion.""" )
parser.add_argument("""--weight_decay""" , default=0.0 , type=__a , help="""Weight decay if we apply some.""" )
parser.add_argument("""--learning_rate""" , default=5E-4 , type=__a , help="""The initial learning rate for Adam.""" )
parser.add_argument("""--adam_epsilon""" , default=1E-6 , type=__a , help="""Epsilon for Adam optimizer.""" )
parser.add_argument("""--max_grad_norm""" , default=5.0 , type=__a , help="""Max gradient norm.""" )
parser.add_argument("""--initializer_range""" , default=0.02 , type=__a , help="""Random initialization range.""" )
parser.add_argument(
"""--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , )
parser.add_argument(
"""--fp16_opt_level""" , type=__a , default="""O1""" , help=(
"""For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."""
"""See details at https://nvidia.github.io/apex/amp.html"""
) , )
parser.add_argument("""--n_gpu""" , type=__a , default=1 , help="""Number of GPUs in the node.""" )
parser.add_argument("""--local_rank""" , type=__a , default=-1 , help="""Distributed training - Local rank""" )
parser.add_argument("""--seed""" , type=__a , default=56 , help="""Random seed""" )
parser.add_argument("""--log_interval""" , type=__a , default=500 , help="""Tensorboard logging interval.""" )
parser.add_argument("""--checkpoint_interval""" , type=__a , default=4_000 , help="""Checkpoint interval.""" )
UpperCamelCase__ = parser.parse_args()
sanity_checks(__a )
# ARGS #
init_gpu_params(__a )
set_seed(__a )
if args.is_master:
if os.path.exists(args.dump_path ):
if not args.force:
raise ValueError(
f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite"
""" itUse `--force` if you want to overwrite it""" )
else:
shutil.rmtree(args.dump_path )
if not os.path.exists(args.dump_path ):
os.makedirs(args.dump_path )
logger.info(f"Experiment will be dumped and logged in {args.dump_path}" )
# SAVE PARAMS #
logger.info(f"Param: {args}" )
with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f:
json.dump(vars(__a ) , __a , indent=4 )
git_log(args.dump_path )
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.student_type]
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.teacher_type]
# TOKENIZER #
UpperCamelCase__ = teacher_tokenizer_class.from_pretrained(args.teacher_name )
UpperCamelCase__ = {}
for tok_name, tok_symbol in tokenizer.special_tokens_map.items():
UpperCamelCase__ = tokenizer.all_special_tokens.index(__a )
UpperCamelCase__ = tokenizer.all_special_ids[idx]
logger.info(f"Special tokens {special_tok_ids}" )
UpperCamelCase__ = special_tok_ids
UpperCamelCase__ = tokenizer.max_model_input_sizes[args.teacher_name]
# DATA LOADER #
logger.info(f"Loading data from {args.data_file}" )
with open(args.data_file , """rb""" ) as fp:
UpperCamelCase__ = pickle.load(__a )
if args.mlm:
logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)" )
with open(args.token_counts , """rb""" ) as fp:
UpperCamelCase__ = pickle.load(__a )
UpperCamelCase__ = np.maximum(__a , 1 ) ** -args.mlm_smoothing
for idx in special_tok_ids.values():
UpperCamelCase__ = 0.0 # do not predict special tokens
UpperCamelCase__ = torch.from_numpy(__a )
else:
UpperCamelCase__ = None
UpperCamelCase__ = LmSeqsDataset(params=__a , data=__a )
logger.info("""Data loader created.""" )
# STUDENT #
logger.info(f"Loading student config from {args.student_config}" )
UpperCamelCase__ = student_config_class.from_pretrained(args.student_config )
UpperCamelCase__ = True
if args.student_pretrained_weights is not None:
logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}" )
UpperCamelCase__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=__a )
else:
UpperCamelCase__ = student_model_class(__a )
if args.n_gpu > 0:
student.to(f"cuda:{args.local_rank}" )
logger.info("""Student loaded.""" )
# TEACHER #
UpperCamelCase__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__a )
if args.n_gpu > 0:
teacher.to(f"cuda:{args.local_rank}" )
logger.info(f"Teacher loaded from {args.teacher_name}." )
# FREEZING #
if args.freeze_pos_embs:
freeze_pos_embeddings(__a , __a )
if args.freeze_token_type_embds:
freeze_token_type_embeddings(__a , __a )
# SANITY CHECKS #
assert student.config.vocab_size == teacher.config.vocab_size
assert student.config.hidden_size == teacher.config.hidden_size
assert student.config.max_position_embeddings == teacher.config.max_position_embeddings
if args.mlm:
assert token_probs.size(0 ) == stu_architecture_config.vocab_size
# DISTILLER #
torch.cuda.empty_cache()
UpperCamelCase__ = Distiller(
params=__a , dataset=__a , token_probs=__a , student=__a , teacher=__a )
distiller.train()
logger.info("""Let's go get some drinks.""" )
if __name__ == "__main__":
main()
| 704 |
lowerCamelCase_ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)]
def __magic_name__ ( __a : int ):
'''simple docstring'''
UpperCamelCase__ = 0
while number:
# Increased Speed Slightly by checking every 5 digits together.
sum_of_digits_squared += DIGITS_SQUARED[number % 100_000]
number //= 100_000
return sum_of_digits_squared
# There are 2 Chains made,
# One ends with 89 with the chain member 58 being the one which when declared first,
# there will be the least number of iterations for all the members to be checked.
# The other one ends with 1 and has only one element 1.
# So 58 and 1 are chosen to be declared at the starting.
# Changed dictionary to an array to quicken the solution
lowerCamelCase_ = [None] * 10_00_00_00
lowerCamelCase_ = True
lowerCamelCase_ = False
def __magic_name__ ( __a : int ):
'''simple docstring'''
if CHAINS[number - 1] is not None:
return CHAINS[number - 1] # type: ignore
UpperCamelCase__ = chain(next_number(__a ) )
UpperCamelCase__ = number_chain
while number < 10_000_000:
UpperCamelCase__ = number_chain
number *= 10
return number_chain
def __magic_name__ ( __a : int = 10_000_000 ):
'''simple docstring'''
for i in range(1 , __a ):
if CHAINS[i] is None:
chain(i + 1 )
return CHAINS[:number].count(__a )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f'{solution() = }')
| 86 | 0 |
from ..utils import DummyObject, requires_backends
class __a( metaclass=_a ):
"""simple docstring"""
lowerCAmelCase = ['''flax''', '''transformers''']
def __init__( self ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> List[Any]:
requires_backends(self ,['''flax''', '''transformers'''] )
@classmethod
def a__ ( cls ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> Dict:
requires_backends(cls ,['''flax''', '''transformers'''] )
@classmethod
def a__ ( cls ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> Dict:
requires_backends(cls ,['''flax''', '''transformers'''] )
class __a( metaclass=_a ):
"""simple docstring"""
lowerCAmelCase = ['''flax''', '''transformers''']
def __init__( self ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> Optional[Any]:
requires_backends(self ,['''flax''', '''transformers'''] )
@classmethod
def a__ ( cls ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> str:
requires_backends(cls ,['''flax''', '''transformers'''] )
@classmethod
def a__ ( cls ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> Optional[Any]:
requires_backends(cls ,['''flax''', '''transformers'''] )
class __a( metaclass=_a ):
"""simple docstring"""
lowerCAmelCase = ['''flax''', '''transformers''']
def __init__( self ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> Union[str, Any]:
requires_backends(self ,['''flax''', '''transformers'''] )
@classmethod
def a__ ( cls ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> Optional[Any]:
requires_backends(cls ,['''flax''', '''transformers'''] )
@classmethod
def a__ ( cls ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> Optional[Any]:
requires_backends(cls ,['''flax''', '''transformers'''] )
class __a( metaclass=_a ):
"""simple docstring"""
lowerCAmelCase = ['''flax''', '''transformers''']
def __init__( self ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> Any:
requires_backends(self ,['''flax''', '''transformers'''] )
@classmethod
def a__ ( cls ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> List[str]:
requires_backends(cls ,['''flax''', '''transformers'''] )
@classmethod
def a__ ( cls ,*_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> List[str]:
requires_backends(cls ,['''flax''', '''transformers'''] ) | 30 | from math import pow, sqrt
def snake_case (*__lowercase ) -> bool:
'''simple docstring'''
_snake_case : str = len(__lowercase ) > 0 and all(value > 0.0 for value in values )
return result
def snake_case (__lowercase , __lowercase ) -> float | ValueError:
'''simple docstring'''
return (
round(sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__lowercase , __lowercase )
else ValueError("Input Error: Molar mass values must greater than 0." )
)
def snake_case (__lowercase , __lowercase , __lowercase ) -> float | ValueError:
'''simple docstring'''
return (
round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__lowercase , __lowercase , __lowercase )
else ValueError(
"Input Error: Molar mass and effusion rate values must greater than 0." )
)
def snake_case (__lowercase , __lowercase , __lowercase ) -> float | ValueError:
'''simple docstring'''
return (
round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__lowercase , __lowercase , __lowercase )
else ValueError(
"Input Error: Molar mass and effusion rate values must greater than 0." )
)
def snake_case (__lowercase , __lowercase , __lowercase ) -> float | ValueError:
'''simple docstring'''
return (
round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 )
if validate(__lowercase , __lowercase , __lowercase )
else ValueError(
"Input Error: Molar mass and effusion rate values must greater than 0." )
)
def snake_case (__lowercase , __lowercase , __lowercase ) -> float | ValueError:
'''simple docstring'''
return (
round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 )
if validate(__lowercase , __lowercase , __lowercase )
else ValueError(
"Input Error: Molar mass and effusion rate values must greater than 0." )
) | 670 | 0 |
"""simple docstring"""
import unittest
import numpy as np
from transformers import is_flax_available
from transformers.testing_utils import require_flax
from ..test_modeling_flax_common import ids_tensor
if is_flax_available():
import jax
import jax.numpy as jnp
from transformers.generation import (
FlaxForcedBOSTokenLogitsProcessor,
FlaxForcedEOSTokenLogitsProcessor,
FlaxLogitsProcessorList,
FlaxMinLengthLogitsProcessor,
FlaxTemperatureLogitsWarper,
FlaxTopKLogitsWarper,
FlaxTopPLogitsWarper,
)
@require_flax
class a__ ( unittest.TestCase ):
def snake_case__ ( self, _UpperCAmelCase, _UpperCAmelCase ):
'''simple docstring'''
lowercase__ = jnp.ones((batch_size, length) ) / length
return scores
def snake_case__ ( self ):
'''simple docstring'''
lowercase__ = None
lowercase__ = 20
lowercase__ = self._get_uniform_logits(batch_size=2, length=_a )
# tweak scores to not be uniform anymore
lowercase__ = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch
lowercase__ = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch
# compute softmax
lowercase__ = jax.nn.softmax(_a, axis=-1 )
lowercase__ = FlaxTemperatureLogitsWarper(temperature=0.5 )
lowercase__ = FlaxTemperatureLogitsWarper(temperature=1.3 )
lowercase__ = jax.nn.softmax(temp_dist_warper_sharper(_a, scores.copy(), cur_len=_a ), axis=-1 )
lowercase__ = jax.nn.softmax(temp_dist_warper_smoother(_a, scores.copy(), cur_len=_a ), axis=-1 )
# uniform distribution stays uniform
self.assertTrue(jnp.allclose(probs[0, :], warped_prob_sharp[0, :], atol=1E-3 ) )
self.assertTrue(jnp.allclose(probs[0, :], warped_prob_smooth[0, :], atol=1E-3 ) )
# sharp peaks get higher, valleys get lower
self.assertLess(probs[1, :].max(), warped_prob_sharp[1, :].max() )
self.assertGreater(probs[1, :].min(), warped_prob_sharp[1, :].min() )
# smooth peaks get lower, valleys get higher
self.assertGreater(probs[1, :].max(), warped_prob_smooth[1, :].max() )
self.assertLess(probs[1, :].min(), warped_prob_smooth[1, :].min() )
def snake_case__ ( self ):
'''simple docstring'''
lowercase__ = None
lowercase__ = 10
lowercase__ = 2
# create ramp distribution
lowercase__ = np.broadcast_to(np.arange(_a )[None, :], (batch_size, vocab_size) ).copy()
lowercase__ = ramp_logits[1:, : vocab_size // 2] + vocab_size
lowercase__ = FlaxTopKLogitsWarper(3 )
lowercase__ = top_k_warp(_a, _a, cur_len=_a )
# check that correct tokens are filtered
self.assertListEqual(jnp.isinf(scores[0] ).tolist(), 7 * [True] + 3 * [False] )
self.assertListEqual(jnp.isinf(scores[1] ).tolist(), 2 * [True] + 3 * [False] + 5 * [True] )
# check special case
lowercase__ = 5
lowercase__ = FlaxTopKLogitsWarper(top_k=1, filter_value=0.0, min_tokens_to_keep=3 )
lowercase__ = np.broadcast_to(np.arange(_a )[None, :], (batch_size, length) ).copy()
lowercase__ = top_k_warp_safety_check(_a, _a, cur_len=_a )
# min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist(), [2, 2] )
def snake_case__ ( self ):
'''simple docstring'''
lowercase__ = None
lowercase__ = 10
lowercase__ = 2
# create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
lowercase__ = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) )
lowercase__ = FlaxTopPLogitsWarper(0.8 )
lowercase__ = np.exp(top_p_warp(_a, _a, cur_len=_a ) )
# dist should be filtered to keep min num values so that sum is >= top_p
# exp (-inf) => 0
lowercase__ = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] )
self.assertTrue(np.allclose(_a, _a, atol=1E-3 ) )
# check edge cases with negative and extreme logits
lowercase__ = np.broadcast_to(np.arange(_a )[None, :], (batch_size, vocab_size) ).copy() - (
vocab_size // 2
)
# make ramp_logits more extreme
lowercase__ = ramp_logits[1] * 100.0
# make sure at least 2 tokens are kept
lowercase__ = FlaxTopPLogitsWarper(0.9, min_tokens_to_keep=2, filter_value=0.0 )
lowercase__ = top_p_warp(_a, _a, cur_len=_a )
# first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist(), [3, 2] )
def snake_case__ ( self ):
'''simple docstring'''
lowercase__ = 20
lowercase__ = 4
lowercase__ = 0
lowercase__ = FlaxMinLengthLogitsProcessor(min_length=10, eos_token_id=_a )
# check that min length is applied at length 5
lowercase__ = ids_tensor((batch_size, 20), vocab_size=20 )
lowercase__ = 5
lowercase__ = self._get_uniform_logits(_a, _a )
lowercase__ = min_dist_processor(_a, _a, cur_len=_a )
self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist(), 4 * [-float("inf" )] )
# check that min length is not applied anymore at length 15
lowercase__ = self._get_uniform_logits(_a, _a )
lowercase__ = 15
lowercase__ = min_dist_processor(_a, _a, cur_len=_a )
self.assertFalse(jnp.isinf(_a ).any() )
def snake_case__ ( self ):
'''simple docstring'''
lowercase__ = 20
lowercase__ = 4
lowercase__ = 0
lowercase__ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_a )
# check that all scores are -inf except the bos_token_id score
lowercase__ = ids_tensor((batch_size, 1), vocab_size=20 )
lowercase__ = 1
lowercase__ = self._get_uniform_logits(_a, _a )
lowercase__ = logits_processor(_a, _a, cur_len=_a )
self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() )
self.assertListEqual(scores[:, bos_token_id].tolist(), 4 * [0] ) # score for bos_token_id shold be zero
# check that bos_token_id is not forced if current length is greater than 1
lowercase__ = 3
lowercase__ = self._get_uniform_logits(_a, _a )
lowercase__ = logits_processor(_a, _a, cur_len=_a )
self.assertFalse(jnp.isinf(_a ).any() )
def snake_case__ ( self ):
'''simple docstring'''
lowercase__ = 20
lowercase__ = 4
lowercase__ = 0
lowercase__ = 5
lowercase__ = FlaxForcedEOSTokenLogitsProcessor(max_length=_a, eos_token_id=_a )
# check that all scores are -inf except the eos_token_id when max_length is reached
lowercase__ = ids_tensor((batch_size, 4), vocab_size=20 )
lowercase__ = 4
lowercase__ = self._get_uniform_logits(_a, _a )
lowercase__ = logits_processor(_a, _a, cur_len=_a )
self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() )
self.assertListEqual(scores[:, eos_token_id].tolist(), 4 * [0] ) # score for eos_token_id should be zero
# check that eos_token_id is not forced if max_length is not reached
lowercase__ = 3
lowercase__ = self._get_uniform_logits(_a, _a )
lowercase__ = logits_processor(_a, _a, cur_len=_a )
self.assertFalse(jnp.isinf(_a ).any() )
def snake_case__ ( self ):
'''simple docstring'''
lowercase__ = 4
lowercase__ = 10
lowercase__ = 15
lowercase__ = 2
lowercase__ = 1
lowercase__ = 15
# dummy input_ids and scores
lowercase__ = ids_tensor((batch_size, sequence_length), _a )
lowercase__ = input_ids.copy()
lowercase__ = self._get_uniform_logits(_a, _a )
lowercase__ = scores.copy()
# instantiate all dist processors
lowercase__ = FlaxTemperatureLogitsWarper(temperature=0.5 )
lowercase__ = FlaxTopKLogitsWarper(3 )
lowercase__ = FlaxTopPLogitsWarper(0.8 )
# instantiate all logits processors
lowercase__ = FlaxMinLengthLogitsProcessor(min_length=10, eos_token_id=_a )
lowercase__ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_a )
lowercase__ = FlaxForcedEOSTokenLogitsProcessor(max_length=_a, eos_token_id=_a )
lowercase__ = 10
# no processor list
lowercase__ = temp_dist_warp(_a, _a, cur_len=_a )
lowercase__ = top_k_warp(_a, _a, cur_len=_a )
lowercase__ = top_p_warp(_a, _a, cur_len=_a )
lowercase__ = min_dist_proc(_a, _a, cur_len=_a )
lowercase__ = bos_dist_proc(_a, _a, cur_len=_a )
lowercase__ = eos_dist_proc(_a, _a, cur_len=_a )
# with processor list
lowercase__ = FlaxLogitsProcessorList(
[temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] )
lowercase__ = processor(_a, _a, cur_len=_a )
# scores should be equal
self.assertTrue(jnp.allclose(_a, _a, atol=1E-3 ) )
# input_ids should never be changed
self.assertListEqual(input_ids.tolist(), input_ids_comp.tolist() )
def snake_case__ ( self ):
'''simple docstring'''
lowercase__ = 4
lowercase__ = 10
lowercase__ = 15
lowercase__ = 2
lowercase__ = 1
lowercase__ = 15
# dummy input_ids and scores
lowercase__ = ids_tensor((batch_size, sequence_length), _a )
lowercase__ = input_ids.copy()
lowercase__ = self._get_uniform_logits(_a, _a )
lowercase__ = scores.copy()
# instantiate all dist processors
lowercase__ = FlaxTemperatureLogitsWarper(temperature=0.5 )
lowercase__ = FlaxTopKLogitsWarper(3 )
lowercase__ = FlaxTopPLogitsWarper(0.8 )
# instantiate all logits processors
lowercase__ = FlaxMinLengthLogitsProcessor(min_length=10, eos_token_id=_a )
lowercase__ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_a )
lowercase__ = FlaxForcedEOSTokenLogitsProcessor(max_length=_a, eos_token_id=_a )
lowercase__ = 10
# no processor list
def run_no_processor_list(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ):
lowercase__ = temp_dist_warp(_a, _a, cur_len=_a )
lowercase__ = top_k_warp(_a, _a, cur_len=_a )
lowercase__ = top_p_warp(_a, _a, cur_len=_a )
lowercase__ = min_dist_proc(_a, _a, cur_len=_a )
lowercase__ = bos_dist_proc(_a, _a, cur_len=_a )
lowercase__ = eos_dist_proc(_a, _a, cur_len=_a )
return scores
# with processor list
def run_processor_list(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase ):
lowercase__ = FlaxLogitsProcessorList(
[temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] )
lowercase__ = processor(_a, _a, cur_len=_a )
return scores
lowercase__ = jax.jit(_a )
lowercase__ = jax.jit(_a )
lowercase__ = jitted_run_no_processor_list(_a, _a, _a )
lowercase__ = jitted_run_processor_list(_a, _a, _a )
# scores should be equal
self.assertTrue(jnp.allclose(_a, _a, atol=1E-3 ) )
# input_ids should never be changed
self.assertListEqual(input_ids.tolist(), input_ids_comp.tolist() )
| 710 | """simple docstring"""
from sympy import diff, lambdify, symbols
from sympy.functions import * # noqa: F403
def __a ( A , A , A = "x" , A = 10**-10 , A = 1 , ):
'''simple docstring'''
lowercase__ = symbols(A )
lowercase__ = lambdify(A , A )
lowercase__ = lambdify(A , diff(A , A ) )
lowercase__ = starting_point
while True:
if diff_function(A ) != 0:
lowercase__ = prev_guess - multiplicity * func(A ) / diff_function(
A )
else:
raise ZeroDivisionError("Could not find root" ) from None
# Precision is checked by comparing the difference of consecutive guesses
if abs(next_guess - prev_guess ) < precision:
return next_guess
lowercase__ = next_guess
# Let's Execute
if __name__ == "__main__":
# Find root of trigonometric function
# Find value of pi
print(F'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}')
# Find root of polynomial
# Find fourth Root of 5
print(F'The root of x**4 - 5 = 0 is {newton_raphson("x**4 -5", 0.4 +5j)}')
# Find value of e
print(
"The root of log(y) - 1 = 0 is ",
F'{newton_raphson("log(y) - 1", 2, variable="y")}',
)
# Exponential Roots
print(
"The root of exp(x) - 1 = 0 is",
F'{newton_raphson("exp(x) - 1", 1_0, precision=0.005)}',
)
# Find root of cos(x)
print(F'The root of cos(x) = 0 is {newton_raphson("cos(x)", 0)}')
| 668 | 0 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import cached_download, hf_hub_download, hf_hub_url
from PIL import Image
from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig
from transformers.utils import logging
logging.set_verbosity_info()
__snake_case :str =logging.get_logger(__name__)
def lowerCamelCase_ ( lowerCAmelCase__ : Any ) -> str:
'''simple docstring'''
A = SwinConfig(
embed_dim=192 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=['stage2', 'stage3', 'stage4'] , )
A = DetaConfig(
backbone_config=__lowerCAmelCase , num_queries=900 , encoder_ffn_dim=2048 , decoder_ffn_dim=2048 , num_feature_levels=5 , assign_first_stage=__lowerCAmelCase , with_box_refine=__lowerCAmelCase , two_stage=__lowerCAmelCase , )
# set labels
A = 'huggingface/label-files'
if "o365" in model_name:
A = 366
A = 'object365-id2label.json'
else:
A = 91
A = 'coco-detection-id2label.json'
A = num_labels
A = json.load(open(cached_download(hf_hub_url(__lowerCAmelCase , __lowerCAmelCase , repo_type='dataset' ) ) , 'r' ) )
A = {int(__lowerCAmelCase ): v for k, v in idalabel.items()}
A = idalabel
A = {v: k for k, v in idalabel.items()}
return config
def lowerCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> List[str]:
'''simple docstring'''
A = []
# stem
# fmt: off
rename_keys.append(('backbone.0.body.patch_embed.proj.weight', 'model.backbone.model.embeddings.patch_embeddings.projection.weight') )
rename_keys.append(('backbone.0.body.patch_embed.proj.bias', 'model.backbone.model.embeddings.patch_embeddings.projection.bias') )
rename_keys.append(('backbone.0.body.patch_embed.norm.weight', 'model.backbone.model.embeddings.norm.weight') )
rename_keys.append(('backbone.0.body.patch_embed.norm.bias', 'model.backbone.model.embeddings.norm.bias') )
# stages
for i in range(len(config.backbone_config.depths ) ):
for j in range(config.backbone_config.depths[i] ):
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') )
if i < 3:
rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.reduction.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.reduction.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.bias''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.bias''') )
rename_keys.append(('backbone.0.body.norm1.weight', 'model.backbone.model.hidden_states_norms.stage2.weight') )
rename_keys.append(('backbone.0.body.norm1.bias', 'model.backbone.model.hidden_states_norms.stage2.bias') )
rename_keys.append(('backbone.0.body.norm2.weight', 'model.backbone.model.hidden_states_norms.stage3.weight') )
rename_keys.append(('backbone.0.body.norm2.bias', 'model.backbone.model.hidden_states_norms.stage3.bias') )
rename_keys.append(('backbone.0.body.norm3.weight', 'model.backbone.model.hidden_states_norms.stage4.weight') )
rename_keys.append(('backbone.0.body.norm3.bias', 'model.backbone.model.hidden_states_norms.stage4.bias') )
# transformer encoder
for i in range(config.encoder_layers ):
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.weight''', F'''model.encoder.layers.{i}.self_attn.attention_weights.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.bias''', F'''model.encoder.layers.{i}.self_attn.attention_weights.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.weight''', F'''model.encoder.layers.{i}.self_attn.value_proj.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.bias''', F'''model.encoder.layers.{i}.self_attn.value_proj.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.weight''', F'''model.encoder.layers.{i}.self_attn.output_proj.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.bias''', F'''model.encoder.layers.{i}.self_attn.output_proj.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.weight''', F'''model.encoder.layers.{i}.self_attn_layer_norm.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.bias''', F'''model.encoder.layers.{i}.self_attn_layer_norm.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''model.encoder.layers.{i}.fc1.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''model.encoder.layers.{i}.fc1.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''model.encoder.layers.{i}.fc2.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''model.encoder.layers.{i}.fc2.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.weight''', F'''model.encoder.layers.{i}.final_layer_norm.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''model.encoder.layers.{i}.final_layer_norm.bias''') )
# transformer decoder
for i in range(config.decoder_layers ):
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.weight''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.bias''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.weight''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.bias''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''model.decoder.layers.{i}.self_attn.out_proj.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''model.decoder.layers.{i}.self_attn.out_proj.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.weight''', F'''model.decoder.layers.{i}.self_attn_layer_norm.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.bias''', F'''model.decoder.layers.{i}.self_attn_layer_norm.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''model.decoder.layers.{i}.fc1.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''model.decoder.layers.{i}.fc1.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''model.decoder.layers.{i}.fc2.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''model.decoder.layers.{i}.fc2.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.weight''', F'''model.decoder.layers.{i}.final_layer_norm.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''model.decoder.layers.{i}.final_layer_norm.bias''') )
# fmt: on
return rename_keys
def lowerCamelCase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : Dict , lowerCAmelCase__ : str ) -> Tuple:
'''simple docstring'''
A = dct.pop(__lowerCAmelCase )
A = val
def lowerCamelCase_ ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Optional[Any] ) -> Dict:
'''simple docstring'''
A = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )]
for i in range(len(backbone_config.depths ) ):
A = num_features[i]
for j in range(backbone_config.depths[i] ):
# fmt: off
# read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
A = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight''' )
A = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias''' )
# next, add query, keys and values (in that order) to the state dict
A = in_proj_weight[:dim, :]
A = in_proj_bias[: dim]
A = in_proj_weight[
dim : dim * 2, :
]
A = in_proj_bias[
dim : dim * 2
]
A = in_proj_weight[
-dim :, :
]
A = in_proj_bias[-dim :]
# fmt: on
def lowerCamelCase_ ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any ) -> Any:
'''simple docstring'''
A = config.d_model
for i in range(config.decoder_layers ):
# read in weights + bias of input projection layer of self-attention
A = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_weight''' )
A = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_bias''' )
# next, add query, keys and values (in that order) to the state dict
A = in_proj_weight[:hidden_size, :]
A = in_proj_bias[:hidden_size]
A = in_proj_weight[
hidden_size : hidden_size * 2, :
]
A = in_proj_bias[hidden_size : hidden_size * 2]
A = in_proj_weight[-hidden_size:, :]
A = in_proj_bias[-hidden_size:]
def lowerCamelCase_ ( ) -> Tuple:
'''simple docstring'''
A = 'http://images.cocodataset.org/val2017/000000039769.jpg'
A = Image.open(requests.get(__lowerCAmelCase , stream=__lowerCAmelCase ).raw )
return im
@torch.no_grad()
def lowerCamelCase_ ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : int ) -> Optional[Any]:
'''simple docstring'''
A = get_deta_config(__lowerCAmelCase )
# load original state dict
if model_name == "deta-swin-large":
A = hf_hub_download(repo_id='nielsr/deta-checkpoints' , filename='adet_swin_ft.pth' )
elif model_name == "deta-swin-large-o365":
A = hf_hub_download(repo_id='jozhang97/deta-swin-l-o365' , filename='deta_swin_pt_o365.pth' )
else:
raise ValueError(F'''Model name {model_name} not supported''' )
A = torch.load(__lowerCAmelCase , map_location='cpu' )['model']
# original state dict
for name, param in state_dict.items():
print(__lowerCAmelCase , param.shape )
# rename keys
A = create_rename_keys(__lowerCAmelCase )
for src, dest in rename_keys:
rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
read_in_swin_q_k_v(__lowerCAmelCase , config.backbone_config )
read_in_decoder_q_k_v(__lowerCAmelCase , __lowerCAmelCase )
# fix some prefixes
for key in state_dict.copy().keys():
if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key:
A = state_dict.pop(__lowerCAmelCase )
A = val
if "input_proj" in key:
A = state_dict.pop(__lowerCAmelCase )
A = val
if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key:
A = state_dict.pop(__lowerCAmelCase )
A = val
# finally, create HuggingFace model and load state dict
A = DetaForObjectDetection(__lowerCAmelCase )
model.load_state_dict(__lowerCAmelCase )
model.eval()
A = 'cuda' if torch.cuda.is_available() else 'cpu'
model.to(__lowerCAmelCase )
# load image processor
A = DetaImageProcessor(format='coco_detection' )
# verify our conversion on image
A = prepare_img()
A = processor(images=__lowerCAmelCase , return_tensors='pt' )
A = encoding['pixel_values']
A = model(pixel_values.to(__lowerCAmelCase ) )
# verify logits
print('Logits:' , outputs.logits[0, :3, :3] )
print('Boxes:' , outputs.pred_boxes[0, :3, :3] )
if model_name == "deta-swin-large":
A = torch.tensor(
[[-7.6308, -2.8485, -5.3737], [-7.2037, -4.5505, -4.8027], [-7.2943, -4.2611, -4.6617]] )
A = torch.tensor([[0.4987, 0.4969, 0.9999], [0.2549, 0.5498, 0.4805], [0.5498, 0.2757, 0.0569]] )
elif model_name == "deta-swin-large-o365":
A = torch.tensor(
[[-8.0122, -3.5720, -4.9717], [-8.1547, -3.6886, -4.6389], [-7.6610, -3.6194, -5.0134]] )
A = torch.tensor([[0.2523, 0.5549, 0.4881], [0.7715, 0.4149, 0.4601], [0.5503, 0.2753, 0.0575]] )
assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(__lowerCAmelCase ) , atol=1E-4 )
assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(__lowerCAmelCase ) , atol=1E-4 )
print('Everything ok!' )
if pytorch_dump_folder_path:
# Save model and processor
logger.info(F'''Saving PyTorch model and processor to {pytorch_dump_folder_path}...''' )
Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase )
model.save_pretrained(__lowerCAmelCase )
processor.save_pretrained(__lowerCAmelCase )
# Push to hub
if push_to_hub:
print('Pushing model and processor to hub...' )
model.push_to_hub(F'''jozhang97/{model_name}''' )
processor.push_to_hub(F'''jozhang97/{model_name}''' )
if __name__ == "__main__":
__snake_case :List[str] =argparse.ArgumentParser()
parser.add_argument(
'--model_name',
type=str,
default='deta-swin-large',
choices=['deta-swin-large', 'deta-swin-large-o365'],
help='Name of the model you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default=None,
type=str,
help='Path to the folder to output PyTorch model.',
)
parser.add_argument(
'--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
)
__snake_case :Tuple =parser.parse_args()
convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub) | 106 |
"""simple docstring"""
from math import factorial
UpperCAmelCase : Tuple = {str(d): factorial(d) for d in range(10)}
def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> int:
'''simple docstring'''
return sum(DIGIT_FACTORIAL[d] for d in str(__lowerCAmelCase ) )
def _SCREAMING_SNAKE_CASE () -> int:
'''simple docstring'''
lowercase_ = 7 * factorial(9 ) + 1
return sum(i for i in range(3 , __lowerCAmelCase ) if sum_of_digit_factorial(__lowerCAmelCase ) == i )
if __name__ == "__main__":
print(F"{solution() = }")
| 567 | 0 |
'''simple docstring'''
def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Optional[int]:
if n == 0:
return 1
elif n % 2 == 1:
return (binary_exponentiation(__UpperCamelCase ,n - 1 ,__UpperCamelCase ) * a) % mod
else:
lowerCamelCase_ = binary_exponentiation(__UpperCamelCase ,n / 2 ,__UpperCamelCase )
return (b * b) % mod
# a prime number
A_ = 701
A_ = 1_000_000_000
A_ = 10
# using binary exponentiation function, O(log(p)):
print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p)
print((a / b) % p == (a * b ** (p - 2)) % p)
| 384 |
'''simple docstring'''
import hashlib
import unittest
from typing import Dict
import numpy as np
from transformers import (
MODEL_FOR_MASK_GENERATION_MAPPING,
TF_MODEL_FOR_MASK_GENERATION_MAPPING,
is_vision_available,
pipeline,
)
from transformers.pipelines import MaskGenerationPipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_torch,
require_vision,
slow,
)
if is_vision_available():
from PIL import Image
else:
class UpperCAmelCase :
'''simple docstring'''
@staticmethod
def UpperCamelCase( *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[str]:
'''simple docstring'''
pass
def _UpperCamelCase ( __UpperCamelCase ) -> str:
lowerCamelCase_ = hashlib.mda(image.tobytes() )
return m.hexdigest()[:10]
def _UpperCamelCase ( __UpperCamelCase ) -> Dict:
lowerCamelCase_ = np.array(__UpperCamelCase )
lowerCamelCase_ = npimg.shape
return {"hash": hashimage(__UpperCamelCase ), "shape": shape}
@is_pipeline_test
@require_vision
@require_torch
class UpperCAmelCase ( unittest.TestCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ = dict(
(list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) )
SCREAMING_SNAKE_CASE_ = dict(
(list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) )
def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase_ = MaskGenerationPipeline(model=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ )
return image_segmenter, [
"./tests/fixtures/tests_samples/COCO/000000039769.png",
"./tests/fixtures/tests_samples/COCO/000000039769.png",
]
def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str:
'''simple docstring'''
pass
@require_tf
@unittest.skip('Image segmentation not implemented in TF' )
def UpperCamelCase( self ) -> int:
'''simple docstring'''
pass
@slow
@require_torch
def UpperCamelCase( self ) -> Optional[int]:
'''simple docstring'''
lowerCamelCase_ = pipeline('mask-generation' , model='facebook/sam-vit-huge' )
lowerCamelCase_ = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 )
# Shortening by hashing
lowerCamelCase_ = []
for i, o in enumerate(outputs['masks'] ):
new_outupt += [{"mask": mask_to_test_readable(SCREAMING_SNAKE_CASE_ ), "scores": outputs["scores"][i]}]
# fmt: off
self.assertEqual(
nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [
{'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_444},
{'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.021},
{'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_167},
{'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_132},
{'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_053},
{'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9_967},
{'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.993},
{'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9_909},
{'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9_879},
{'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9_834},
{'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9_716},
{'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9_612},
{'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9_599},
{'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9_552},
{'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9_532},
{'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9_516},
{'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9_499},
{'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9_483},
{'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9_464},
{'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.943},
{'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.943},
{'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9_408},
{'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9_335},
{'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9_326},
{'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9_262},
{'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8_999},
{'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8_986},
{'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8_984},
{'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8_873},
{'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8_871}
] , )
# fmt: on
@require_torch
@slow
def UpperCamelCase( self ) -> Any:
'''simple docstring'''
lowerCamelCase_ = 'facebook/sam-vit-huge'
lowerCamelCase_ = pipeline('mask-generation' , model=SCREAMING_SNAKE_CASE_ )
lowerCamelCase_ = image_segmenter(
'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 )
# Shortening by hashing
lowerCamelCase_ = []
for i, o in enumerate(outputs['masks'] ):
new_outupt += [{"mask": mask_to_test_readable(SCREAMING_SNAKE_CASE_ ), "scores": outputs["scores"][i]}]
self.assertEqual(
nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [
{'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_444},
{'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_210},
{'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_167},
{'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_132},
{'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_053},
] , )
| 384 | 1 |
def __a ( A__ : int ):
if not isinstance(A__ , A__ ):
SCREAMING_SNAKE_CASE = F"Input value of [number={number}] must be an integer"
raise TypeError(A__ )
if number < 0:
return False
SCREAMING_SNAKE_CASE = number * number
while number > 0:
if number % 10 != number_square % 10:
return False
number //= 10
number_square //= 10
return True
if __name__ == "__main__":
import doctest
doctest.testmod() | 16 |
'''simple docstring'''
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class UpperCAmelCase ( a_ ):
"""simple docstring"""
A__ : str = ['image_processor', 'tokenizer']
A__ : Dict = 'CLIPImageProcessor'
A__ : str = ('XLMRobertaTokenizer', 'XLMRobertaTokenizerFast')
def __init__( self , _snake_case=None , _snake_case=None , **_snake_case ) -> List[Any]:
_UpperCamelCase : 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.''' , _snake_case , )
_UpperCamelCase : Optional[Any] = kwargs.pop('''feature_extractor''' )
_UpperCamelCase : List[str] = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''' )
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''' )
super().__init__(_snake_case , _snake_case )
def __call__( self , _snake_case=None , _snake_case=None , _snake_case=None , **_snake_case ) -> Dict:
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 : List[str] = self.tokenizer(_snake_case , return_tensors=_snake_case , **_snake_case )
if images is not None:
_UpperCamelCase : str = self.image_processor(_snake_case , return_tensors=_snake_case , **_snake_case )
if text is not None and images is not None:
_UpperCamelCase : Any = image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**_snake_case ) , tensor_type=_snake_case )
def _lowercase ( self , *_snake_case , **_snake_case ) -> Tuple:
return self.tokenizer.batch_decode(*_snake_case , **_snake_case )
def _lowercase ( self , *_snake_case , **_snake_case ) -> Any:
return self.tokenizer.decode(*_snake_case , **_snake_case )
@property
def _lowercase ( self ) -> int:
_UpperCamelCase : Optional[int] = self.tokenizer.model_input_names
_UpperCamelCase : List[str] = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 683 | 0 |
from __future__ import annotations
class __a :
def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[Any]:
'''simple docstring'''
lowercase__ , lowercase__: Dict = text, pattern
lowercase__ , lowercase__: List[str] = len(lowerCAmelCase__ ), len(lowerCAmelCase__ )
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> int:
'''simple docstring'''
for i in range(self.patLen - 1 , -1 , -1 ):
if char == self.pattern[i]:
return i
return -1
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> int:
'''simple docstring'''
for i in range(self.patLen - 1 , -1 , -1 ):
if self.pattern[i] != self.text[current_pos + i]:
return current_pos + i
return -1
def SCREAMING_SNAKE_CASE__ ( self ) -> list[int]:
'''simple docstring'''
# searches pattern in text and returns index positions
lowercase__: Optional[int] = []
for i in range(self.textLen - self.patLen + 1 ):
lowercase__: Optional[int] = self.mismatch_in_text(lowerCAmelCase__ )
if mismatch_index == -1:
positions.append(lowerCAmelCase__ )
else:
lowercase__: Any = self.match_in_pattern(self.text[mismatch_index] )
lowercase__: Tuple = (
mismatch_index - match_index
) # shifting index lgtm [py/multiple-definition]
return positions
__lowerCAmelCase = '''ABAABA'''
__lowerCAmelCase = '''AB'''
__lowerCAmelCase = BoyerMooreSearch(text, pattern)
__lowerCAmelCase = bms.bad_character_heuristic()
if len(positions) == 0:
print('''No match found''')
else:
print('''Pattern found in following positions: ''')
print(positions)
| 335 |
import json
import os
from functools import lru_cache
from typing import Dict, List, Optional, Tuple, Union
import regex as re
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding, EncodedInput
from ...utils import PaddingStrategy, logging
__lowerCAmelCase = logging.get_logger(__name__)
__lowerCAmelCase = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''}
# See all LED models at https://huggingface.co/models?filter=LED
__lowerCAmelCase = {
'''vocab_file''': {
'''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json''',
},
'''merges_file''': {
'''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt''',
},
'''tokenizer_file''': {
'''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json''',
},
}
__lowerCAmelCase = {
'''allenai/led-base-16384''': 1_63_84,
}
@lru_cache()
# Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode
def snake_case_ ( ) -> str:
lowercase__: Dict = (
list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) )
)
lowercase__: Any = bs[:]
lowercase__: int = 0
for b in range(2**8 ):
if b not in bs:
bs.append(snake_case )
cs.append(2**8 + n )
n += 1
lowercase__: Any = [chr(snake_case ) for n in cs]
return dict(zip(snake_case , snake_case ) )
def snake_case_ ( snake_case ) -> Optional[Any]:
lowercase__: Optional[int] = set()
lowercase__: List[Any] = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
lowercase__: Dict = char
return pairs
class __a ( __UpperCamelCase ):
__lowercase : str = VOCAB_FILES_NAMES
__lowercase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP
__lowercase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__lowercase : List[str] = ['input_ids', 'attention_mask']
def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__="replace" , lowerCAmelCase__="<s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__="<s>" , lowerCAmelCase__="<unk>" , lowerCAmelCase__="<pad>" , lowerCAmelCase__="<mask>" , lowerCAmelCase__=False , **lowerCAmelCase__ , ) -> Any:
'''simple docstring'''
lowercase__: Any = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else bos_token
lowercase__: Dict = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else eos_token
lowercase__: Optional[int] = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else sep_token
lowercase__: Optional[int] = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else cls_token
lowercase__: Dict = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else unk_token
lowercase__: Optional[int] = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
lowercase__: Optional[Any] = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else mask_token
super().__init__(
errors=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , **lowerCAmelCase__ , )
with open(lowerCAmelCase__ , encoding='utf-8' ) as vocab_handle:
lowercase__: int = json.load(lowerCAmelCase__ )
lowercase__: int = {v: k for k, v in self.encoder.items()}
lowercase__: Any = errors # how to handle errors in decoding
lowercase__: Optional[Any] = bytes_to_unicode()
lowercase__: Optional[int] = {v: k for k, v in self.byte_encoder.items()}
with open(lowerCAmelCase__ , encoding='utf-8' ) as merges_handle:
lowercase__: Any = merges_handle.read().split('\n' )[1:-1]
lowercase__: int = [tuple(merge.split() ) for merge in bpe_merges]
lowercase__: Optional[Any] = dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) )
lowercase__: Any = {}
lowercase__: str = add_prefix_space
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
lowercase__: Tuple = re.compile(R'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' )
@property
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size
def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]:
'''simple docstring'''
return len(self.encoder )
def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple:
'''simple docstring'''
return dict(self.encoder , **self.added_tokens_encoder )
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Any:
'''simple docstring'''
if token in self.cache:
return self.cache[token]
lowercase__: List[Any] = tuple(lowerCAmelCase__ )
lowercase__: str = get_pairs(lowerCAmelCase__ )
if not pairs:
return token
while True:
lowercase__: str = min(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : self.bpe_ranks.get(lowerCAmelCase__ , float('inf' ) ) )
if bigram not in self.bpe_ranks:
break
lowercase__ , lowercase__: Optional[Any] = bigram
lowercase__: str = []
lowercase__: Tuple = 0
while i < len(lowerCAmelCase__ ):
try:
lowercase__: Dict = word.index(lowerCAmelCase__ , lowerCAmelCase__ )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
lowercase__: Tuple = j
if word[i] == first and i < len(lowerCAmelCase__ ) - 1 and word[i + 1] == second:
new_word.append(first + second )
i += 2
else:
new_word.append(word[i] )
i += 1
lowercase__: Optional[int] = tuple(lowerCAmelCase__ )
lowercase__: List[Any] = new_word
if len(lowerCAmelCase__ ) == 1:
break
else:
lowercase__: List[str] = get_pairs(lowerCAmelCase__ )
lowercase__: Optional[int] = ' '.join(lowerCAmelCase__ )
lowercase__: Dict = word
return word
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Optional[int]:
'''simple docstring'''
lowercase__: List[Any] = []
for token in re.findall(self.pat , lowerCAmelCase__ ):
lowercase__: Optional[Any] = ''.join(
self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCAmelCase__ ).split(' ' ) )
return bpe_tokens
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Any:
'''simple docstring'''
return self.encoder.get(lowerCAmelCase__ , self.encoder.get(self.unk_token ) )
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> int:
'''simple docstring'''
return self.decoder.get(lowerCAmelCase__ )
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Optional[Any]:
'''simple docstring'''
lowercase__: Tuple = ''.join(lowerCAmelCase__ )
lowercase__: Tuple = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors )
return text
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]:
'''simple docstring'''
if not os.path.isdir(lowerCAmelCase__ ):
logger.error(F'Vocabulary path ({save_directory}) should be a directory' )
return
lowercase__: Any = os.path.join(
lowerCAmelCase__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
lowercase__: Any = os.path.join(
lowerCAmelCase__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] )
with open(lowerCAmelCase__ , 'w' , encoding='utf-8' ) as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase__ , ensure_ascii=lowerCAmelCase__ ) + '\n' )
lowercase__: Optional[Any] = 0
with open(lowerCAmelCase__ , 'w' , encoding='utf-8' ) as writer:
writer.write('#version: 0.2\n' )
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda lowerCAmelCase__ : kv[1] ):
if index != token_index:
logger.warning(
F'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'
' Please check that the tokenizer is not corrupted!' )
lowercase__: Optional[int] = token_index
writer.write(' '.join(lowerCAmelCase__ ) + '\n' )
index += 1
return vocab_file, merge_file
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]:
'''simple docstring'''
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
lowercase__: Union[str, Any] = [self.cls_token_id]
lowercase__: Optional[int] = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = False ) -> List[int]:
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=lowerCAmelCase__ , token_ids_a=lowerCAmelCase__ , already_has_special_tokens=lowerCAmelCase__ )
if token_ids_a is None:
return [1] + ([0] * len(lowerCAmelCase__ )) + [1]
return [1] + ([0] * len(lowerCAmelCase__ )) + [1, 1] + ([0] * len(lowerCAmelCase__ )) + [1]
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]:
'''simple docstring'''
lowercase__: Optional[int] = [self.sep_token_id]
lowercase__: Optional[Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__=False , **lowerCAmelCase__ ) -> str:
'''simple docstring'''
lowercase__: int = kwargs.pop('add_prefix_space' , self.add_prefix_space )
if (is_split_into_words or add_prefix_space) and (len(lowerCAmelCase__ ) > 0 and not text[0].isspace()):
lowercase__: List[str] = ' ' + text
return (text, kwargs)
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = PaddingStrategy.DO_NOT_PAD , lowerCAmelCase__ = None , lowerCAmelCase__ = None , ) -> dict:
'''simple docstring'''
lowercase__: Optional[Any] = super()._pad(
encoded_inputs=lowerCAmelCase__ , max_length=lowerCAmelCase__ , padding_strategy=lowerCAmelCase__ , pad_to_multiple_of=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , )
# Load from model defaults
if return_attention_mask is None:
lowercase__: Tuple = 'attention_mask' in self.model_input_names
if return_attention_mask and "global_attention_mask" in encoded_inputs:
lowercase__: int = encoded_inputs[self.model_input_names[0]]
# `global_attention_mask` need to have the same length as other (sequential) inputs.
lowercase__: Tuple = len(encoded_inputs['global_attention_mask'] ) != len(lowerCAmelCase__ )
if needs_to_be_padded:
lowercase__: Optional[Any] = len(lowerCAmelCase__ ) - len(encoded_inputs['global_attention_mask'] )
if self.padding_side == "right":
# Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
lowercase__: str = (
encoded_inputs['global_attention_mask'] + [-1] * difference
)
elif self.padding_side == "left":
lowercase__: Optional[Any] = [-1] * difference + encoded_inputs[
'global_attention_mask'
]
else:
raise ValueError('Invalid padding strategy:' + str(self.padding_side ) )
return encoded_inputs
| 335 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
UpperCAmelCase__ : Union[str, Any] = {
"configuration_conditional_detr": [
"CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP",
"ConditionalDetrConfig",
"ConditionalDetrOnnxConfig",
]
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ : Optional[Any] = ["ConditionalDetrFeatureExtractor"]
UpperCAmelCase__ : Dict = ["ConditionalDetrImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ : List[str] = [
"CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST",
"ConditionalDetrForObjectDetection",
"ConditionalDetrForSegmentation",
"ConditionalDetrModel",
"ConditionalDetrPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_conditional_detr import (
CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP,
ConditionalDetrConfig,
ConditionalDetrOnnxConfig,
)
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor
from .image_processing_conditional_detr import ConditionalDetrImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_conditional_detr import (
CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST,
ConditionalDetrForObjectDetection,
ConditionalDetrForSegmentation,
ConditionalDetrModel,
ConditionalDetrPreTrainedModel,
)
else:
import sys
UpperCAmelCase__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 48 |
from collections.abc import Sequence
def __lowerCAmelCase ( _UpperCamelCase : Sequence[int] | None = None ) -> int:
'''simple docstring'''
if nums is None or not nums:
raise ValueError('Input sequence should not be empty' )
SCREAMING_SNAKE_CASE = nums[0]
for i in range(1 , len(_UpperCamelCase ) ):
SCREAMING_SNAKE_CASE = nums[i]
SCREAMING_SNAKE_CASE = max(_UpperCamelCase , ans + num , _UpperCamelCase )
return ans
if __name__ == "__main__":
import doctest
doctest.testmod()
# Try on a sample input from the user
a_ : str = int(input("Enter number of elements : ").strip())
a_ : Any = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
print(max_subsequence_sum(array))
| 439 | 0 |
'''simple docstring'''
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging
if is_torch_available():
import torch
A__: Dict = logging.get_logger(__name__)
class A__ ( UpperCAmelCase__ ):
__UpperCamelCase : Tuple = ["pixel_values"]
def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Dict[str, int]] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Union[int, float] = 1 / 2_5_5 , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> None:
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE )
_a : int =size if size is not None else {"""shortest_edge""": 2_5_6}
_a : int =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE )
_a : Union[str, Any] =crop_size if crop_size is not None else {"""height""": 2_2_4, """width""": 2_2_4}
_a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE , param_name="""crop_size""" )
_a : Tuple =do_resize
_a : Optional[Any] =size
_a : Any =resample
_a : Any =do_center_crop
_a : Optional[int] =crop_size
_a : int =do_rescale
_a : Union[str, Any] =rescale_factor
_a : List[Any] =do_normalize
_a : Optional[int] =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
_a : int =image_std if image_std is not None else IMAGENET_STANDARD_STD
def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :int , ) -> np.ndarray:
'''simple docstring'''
_a : List[str] =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE )
if "shortest_edge" not in size:
raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" )
_a : Union[str, Any] =get_resize_output_image_size(SCREAMING_SNAKE_CASE , size=size["""shortest_edge"""] , default_to_square=SCREAMING_SNAKE_CASE )
return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :int , ) -> np.ndarray:
'''simple docstring'''
_a : str =get_size_dict(SCREAMING_SNAKE_CASE )
if "height" not in size or "width" not in size:
raise ValueError(f"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}" )
return center_crop(SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :float , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :List[Any] ) -> np.ndarray:
'''simple docstring'''
return rescale(SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Union[float, List[float]] , SCREAMING_SNAKE_CASE :Union[float, List[float]] , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray:
'''simple docstring'''
return normalize(SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :Optional[bool] = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :Optional[bool] = None , SCREAMING_SNAKE_CASE :Optional[float] = None , SCREAMING_SNAKE_CASE :Optional[bool] = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :Union[str, ChannelDimension] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :str , ) -> Tuple:
'''simple docstring'''
_a : Optional[Any] =do_resize if do_resize is not None else self.do_resize
_a : List[Any] =size if size is not None else self.size
_a : List[str] =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE )
_a : List[Any] =resample if resample is not None else self.resample
_a : Optional[Any] =do_center_crop if do_center_crop is not None else self.do_center_crop
_a : List[Any] =crop_size if crop_size is not None else self.crop_size
_a : int =get_size_dict(SCREAMING_SNAKE_CASE , param_name="""crop_size""" )
_a : Optional[Any] =do_rescale if do_rescale is not None else self.do_rescale
_a : Optional[int] =rescale_factor if rescale_factor is not None else self.rescale_factor
_a : Optional[Any] =do_normalize if do_normalize is not None else self.do_normalize
_a : List[Any] =image_mean if image_mean is not None else self.image_mean
_a : Any =image_std if image_std is not None else self.image_std
_a : Optional[int] =make_list_of_images(SCREAMING_SNAKE_CASE )
if not valid_images(SCREAMING_SNAKE_CASE ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None:
raise ValueError("""Size must be specified if do_resize is True.""" )
if do_center_crop and crop_size is None:
raise ValueError("""Crop size must be specified if do_center_crop is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# All transformations expect numpy arrays.
_a : str =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images]
if do_resize:
_a : Any =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images]
if do_center_crop:
_a : int =[self.center_crop(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE ) for image in images]
if do_rescale:
_a : Optional[int] =[self.rescale(image=SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE ) for image in images]
if do_normalize:
_a : Optional[int] =[self.normalize(image=SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE ) for image in images]
_a : Dict =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images]
_a : Dict ={"""pixel_values""": images}
return BatchFeature(data=SCREAMING_SNAKE_CASE , tensor_type=SCREAMING_SNAKE_CASE )
def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :List[Tuple] = None ) -> List[Any]:
'''simple docstring'''
_a : Any =outputs.logits
# Resize logits and compute semantic segmentation maps
if target_sizes is not None:
if len(SCREAMING_SNAKE_CASE ) != len(SCREAMING_SNAKE_CASE ):
raise ValueError(
"""Make sure that you pass in as many target sizes as the batch dimension of the logits""" )
if is_torch_tensor(SCREAMING_SNAKE_CASE ):
_a : List[str] =target_sizes.numpy()
_a : List[str] =[]
for idx in range(len(SCREAMING_SNAKE_CASE ) ):
_a : List[str] =torch.nn.functional.interpolate(
logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE )
_a : Any =resized_logits[0].argmax(dim=0 )
semantic_segmentation.append(SCREAMING_SNAKE_CASE )
else:
_a : Optional[int] =logits.argmax(dim=1 )
_a : List[str] =[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )]
return semantic_segmentation
| 710 |
'''simple docstring'''
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
A__: Any = logging.get_logger(__name__)
class A__ ( UpperCAmelCase__ ):
__UpperCamelCase : Dict = ["pixel_values"]
def __init__( self :List[Any] , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Dict[str, int]] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Union[int, float] = 1 / 2_5_5 , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE :Optional[int] , ) -> None:
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE )
_a : Any =size if size is not None else {"""shortest_edge""": 2_5_6}
_a : int =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE )
_a : Union[str, Any] =crop_size if crop_size is not None else {"""height""": 2_2_4, """width""": 2_2_4}
_a : Union[str, Any] =get_size_dict(SCREAMING_SNAKE_CASE )
_a : List[Any] =do_resize
_a : Optional[int] =size
_a : Union[str, Any] =resample
_a : List[Any] =do_center_crop
_a : Optional[Any] =crop_size
_a : List[Any] =do_rescale
_a : Optional[int] =rescale_factor
_a : int =do_normalize
_a : Tuple =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
_a : Any =image_std if image_std is not None else IMAGENET_STANDARD_STD
def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Any , ) -> np.ndarray:
'''simple docstring'''
_a : Any =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE )
if "shortest_edge" not in size:
raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" )
_a : Union[str, Any] =get_resize_output_image_size(SCREAMING_SNAKE_CASE , size=size["""shortest_edge"""] , default_to_square=SCREAMING_SNAKE_CASE )
return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> np.ndarray:
'''simple docstring'''
_a : List[str] =get_size_dict(SCREAMING_SNAKE_CASE )
return center_crop(SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :float , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Optional[Any] ) -> np.ndarray:
'''simple docstring'''
return rescale(SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Union[float, List[float]] , SCREAMING_SNAKE_CASE :Union[float, List[float]] , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :List[Any] , ) -> np.ndarray:
'''simple docstring'''
return normalize(SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :Optional[bool] = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :Optional[bool] = None , SCREAMING_SNAKE_CASE :Optional[float] = None , SCREAMING_SNAKE_CASE :Optional[bool] = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :Union[str, ChannelDimension] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> Optional[Any]:
'''simple docstring'''
_a : Optional[Any] =do_resize if do_resize is not None else self.do_resize
_a : int =size if size is not None else self.size
_a : str =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE )
_a : int =resample if resample is not None else self.resample
_a : Optional[int] =do_center_crop if do_center_crop is not None else self.do_center_crop
_a : Union[str, Any] =crop_size if crop_size is not None else self.crop_size
_a : Any =get_size_dict(SCREAMING_SNAKE_CASE )
_a : Any =do_rescale if do_rescale is not None else self.do_rescale
_a : List[Any] =rescale_factor if rescale_factor is not None else self.rescale_factor
_a : str =do_normalize if do_normalize is not None else self.do_normalize
_a : Union[str, Any] =image_mean if image_mean is not None else self.image_mean
_a : Optional[Any] =image_std if image_std is not None else self.image_std
_a : List[Any] =make_list_of_images(SCREAMING_SNAKE_CASE )
if not valid_images(SCREAMING_SNAKE_CASE ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None:
raise ValueError("""Size must be specified if do_resize is True.""" )
if do_center_crop and crop_size is None:
raise ValueError("""Crop size must be specified if do_center_crop is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# All transformations expect numpy arrays.
_a : int =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images]
if do_resize:
_a : Tuple =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images]
if do_center_crop:
_a : Union[str, Any] =[self.center_crop(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE ) for image in images]
if do_rescale:
_a : int =[self.rescale(image=SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE ) for image in images]
if do_normalize:
_a : Any =[self.normalize(image=SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE ) for image in images]
_a : Tuple =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images]
_a : Any ={"""pixel_values""": images}
return BatchFeature(data=SCREAMING_SNAKE_CASE , tensor_type=SCREAMING_SNAKE_CASE )
| 506 | 0 |
'''simple docstring'''
def lowerCAmelCase (__A = 4_000_000):
"""simple docstring"""
_a = []
_a , _a = 0, 1
while b <= n:
if b % 2 == 0:
even_fibs.append(__A)
_a , _a = b, a + b
return sum(__A)
if __name__ == "__main__":
print(F"""{solution() = }""")
| 11 |
"""simple docstring"""
import copy
import tempfile
import unittest
from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError
from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
class UpperCamelCase ( unittest.TestCase ):
@parameterized.expand([(None,), ("foo.json",)] )
def __SCREAMING_SNAKE_CASE ( self , snake_case__ ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE : Tuple = GenerationConfig(
do_sample=snake_case__ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , )
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(snake_case__ , config_name=snake_case__ )
_SCREAMING_SNAKE_CASE : List[str] = GenerationConfig.from_pretrained(snake_case__ , config_name=snake_case__ )
# Checks parameters that were specified
self.assertEqual(loaded_config.do_sample , snake_case__ )
self.assertEqual(loaded_config.temperature , 0.7 )
self.assertEqual(loaded_config.length_penalty , 1.0 )
self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] )
# Checks parameters that were not specified (defaults)
self.assertEqual(loaded_config.top_k , 50 )
self.assertEqual(loaded_config.max_length , 20 )
self.assertEqual(loaded_config.max_time , snake_case__ )
def __SCREAMING_SNAKE_CASE ( self ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained("gpt2" )
_SCREAMING_SNAKE_CASE : Union[str, Any] = GenerationConfig.from_model_config(snake_case__ )
_SCREAMING_SNAKE_CASE : Optional[int] = GenerationConfig()
# The generation config has loaded a few non-default parameters from the model config
self.assertNotEqual(snake_case__ , snake_case__ )
# One of those parameters is eos_token_id -- check if it matches
self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id )
self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id )
def __SCREAMING_SNAKE_CASE ( self ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE : Any = GenerationConfig()
_SCREAMING_SNAKE_CASE : str = {
"max_new_tokens": 1024,
"foo": "bar",
}
_SCREAMING_SNAKE_CASE : List[str] = copy.deepcopy(snake_case__ )
_SCREAMING_SNAKE_CASE : Optional[int] = generation_config.update(**snake_case__ )
# update_kwargs was not modified (no side effects)
self.assertEqual(snake_case__ , snake_case__ )
# update_kwargs was used to update the config on valid attributes
self.assertEqual(generation_config.max_new_tokens , 1024 )
# `.update()` returns a dictionary of unused kwargs
self.assertEqual(snake_case__ , {"foo": "bar"} )
def __SCREAMING_SNAKE_CASE ( self ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE : Any = GenerationConfig()
_SCREAMING_SNAKE_CASE : Dict = "bar"
with tempfile.TemporaryDirectory("test-generation-config" ) as tmp_dir:
generation_config.save_pretrained(snake_case__ )
_SCREAMING_SNAKE_CASE : List[Any] = GenerationConfig.from_pretrained(snake_case__ )
# update_kwargs was used to update the config on valid attributes
self.assertEqual(new_config.foo , "bar" )
_SCREAMING_SNAKE_CASE : Any = GenerationConfig.from_model_config(snake_case__ )
assert not hasattr(snake_case__ , "foo" ) # no new kwargs should be initialized if from config
def __SCREAMING_SNAKE_CASE ( self ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE : Optional[Any] = GenerationConfig()
self.assertEqual(default_config.temperature , 1.0 )
self.assertEqual(default_config.do_sample , snake_case__ )
self.assertEqual(default_config.num_beams , 1 )
_SCREAMING_SNAKE_CASE : Dict = GenerationConfig(
do_sample=snake_case__ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , )
self.assertEqual(config.temperature , 0.7 )
self.assertEqual(config.do_sample , snake_case__ )
self.assertEqual(config.num_beams , 1 )
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(snake_case__ )
_SCREAMING_SNAKE_CASE : Any = GenerationConfig.from_pretrained(snake_case__ , temperature=1.0 )
self.assertEqual(loaded_config.temperature , 1.0 )
self.assertEqual(loaded_config.do_sample , snake_case__ )
self.assertEqual(loaded_config.num_beams , 1 ) # default value
@is_staging_test
class UpperCamelCase ( unittest.TestCase ):
@classmethod
def __SCREAMING_SNAKE_CASE ( cls ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE : Any = TOKEN
HfFolder.save_token(snake_case__ )
@classmethod
def __SCREAMING_SNAKE_CASE ( cls ):
"""simple docstring"""
try:
delete_repo(token=cls._token , repo_id="test-generation-config" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-generation-config-org" )
except HTTPError:
pass
def __SCREAMING_SNAKE_CASE ( self ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE : str = GenerationConfig(
do_sample=snake_case__ , temperature=0.7 , length_penalty=1.0 , )
config.push_to_hub("test-generation-config" , use_auth_token=self._token )
_SCREAMING_SNAKE_CASE : Any = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(snake_case__ , getattr(snake_case__ , snake_case__ ) )
# Reset repo
delete_repo(token=self._token , repo_id="test-generation-config" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
snake_case__ , repo_id="test-generation-config" , push_to_hub=snake_case__ , use_auth_token=self._token )
_SCREAMING_SNAKE_CASE : Optional[int] = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(snake_case__ , getattr(snake_case__ , snake_case__ ) )
def __SCREAMING_SNAKE_CASE ( self ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE : Optional[int] = GenerationConfig(
do_sample=snake_case__ , temperature=0.7 , length_penalty=1.0 , )
config.push_to_hub("valid_org/test-generation-config-org" , use_auth_token=self._token )
_SCREAMING_SNAKE_CASE : Tuple = GenerationConfig.from_pretrained("valid_org/test-generation-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(snake_case__ , getattr(snake_case__ , snake_case__ ) )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-generation-config-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
snake_case__ , repo_id="valid_org/test-generation-config-org" , push_to_hub=snake_case__ , use_auth_token=self._token )
_SCREAMING_SNAKE_CASE : int = GenerationConfig.from_pretrained("valid_org/test-generation-config-org" )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(snake_case__ , getattr(snake_case__ , snake_case__ ) )
| 572 | 0 |
"""simple docstring"""
import inspect
from typing import Optional, Union
import numpy as np
import PIL
import torch
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
DPMSolverMultistepScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.utils import (
PIL_INTERPOLATION,
randn_tensor,
)
def _lowercase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Tuple ) -> List[str]:
'''simple docstring'''
if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ):
return image
elif isinstance(_SCREAMING_SNAKE_CASE , PIL.Image.Image ):
__A : Optional[Any] = [image]
if isinstance(image[0] , PIL.Image.Image ):
__A : Dict = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) )[None, :] for i in image]
__A : int = np.concatenate(_SCREAMING_SNAKE_CASE , axis=0 )
__A : Tuple = np.array(_SCREAMING_SNAKE_CASE ).astype(np.floataa ) / 2_55.0
__A : str = image.transpose(0 , 3 , 1 , 2 )
__A : Optional[Any] = 2.0 * image - 1.0
__A : List[Any] = torch.from_numpy(_SCREAMING_SNAKE_CASE )
elif isinstance(image[0] , torch.Tensor ):
__A : List[str] = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 )
return image
def _lowercase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[Any]=0.99_95 ) -> Any:
'''simple docstring'''
if not isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ):
__A : str = True
__A : Union[str, Any] = va.device
__A : List[Any] = va.cpu().numpy()
__A : Tuple = va.cpu().numpy()
__A : Any = np.sum(va * va / (np.linalg.norm(_SCREAMING_SNAKE_CASE ) * np.linalg.norm(_SCREAMING_SNAKE_CASE )) )
if np.abs(_SCREAMING_SNAKE_CASE ) > DOT_THRESHOLD:
__A : Union[str, Any] = (1 - t) * va + t * va
else:
__A : Optional[int] = np.arccos(_SCREAMING_SNAKE_CASE )
__A : List[Any] = np.sin(_SCREAMING_SNAKE_CASE )
__A : Optional[int] = theta_a * t
__A : Optional[Any] = np.sin(_SCREAMING_SNAKE_CASE )
__A : int = np.sin(theta_a - theta_t ) / sin_theta_a
__A : str = sin_theta_t / sin_theta_a
__A : Any = sa * va + sa * va
if inputs_are_torch:
__A : List[str] = torch.from_numpy(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE )
return va
def _lowercase ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Dict ) -> int:
'''simple docstring'''
__A : List[Any] = F.normalize(_SCREAMING_SNAKE_CASE , dim=-1 )
__A : str = F.normalize(_SCREAMING_SNAKE_CASE , dim=-1 )
return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 )
def _lowercase ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[Any]:
'''simple docstring'''
for param in model.parameters():
__A : Any = value
class __snake_case( A_ ):
'''simple docstring'''
def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , ):
'''simple docstring'''
super().__init__()
self.register_modules(
vae=__lowerCamelCase , text_encoder=__lowerCamelCase , clip_model=__lowerCamelCase , tokenizer=__lowerCamelCase , unet=__lowerCamelCase , scheduler=__lowerCamelCase , feature_extractor=__lowerCamelCase , coca_model=__lowerCamelCase , coca_tokenizer=__lowerCamelCase , coca_transform=__lowerCamelCase , )
__A : str = (
feature_extractor.size
if isinstance(feature_extractor.size , __lowerCamelCase )
else feature_extractor.size['shortest_edge']
)
__A : int = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std )
set_requires_grad(self.text_encoder , __lowerCamelCase )
set_requires_grad(self.clip_model , __lowerCamelCase )
def _a ( self , __lowerCamelCase = "auto" ):
'''simple docstring'''
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
__A : str = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(__lowerCamelCase )
def _a ( self ):
'''simple docstring'''
self.enable_attention_slicing(__lowerCamelCase )
def _a ( self ):
'''simple docstring'''
set_requires_grad(self.vae , __lowerCamelCase )
def _a ( self ):
'''simple docstring'''
set_requires_grad(self.vae , __lowerCamelCase )
def _a ( self ):
'''simple docstring'''
set_requires_grad(self.unet , __lowerCamelCase )
def _a ( self ):
'''simple docstring'''
set_requires_grad(self.unet , __lowerCamelCase )
def _a ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ):
'''simple docstring'''
__A : Optional[Any] = min(int(num_inference_steps * strength ) , __lowerCamelCase )
__A : int = max(num_inference_steps - init_timestep , 0 )
__A : Tuple = self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def _a ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None ):
'''simple docstring'''
if not isinstance(__lowerCamelCase , torch.Tensor ):
raise ValueError(F'`image` has to be of type `torch.Tensor` but is {type(__lowerCamelCase )}' )
__A : Union[str, Any] = image.to(device=__lowerCamelCase , dtype=__lowerCamelCase )
if isinstance(__lowerCamelCase , __lowerCamelCase ):
__A : Optional[Any] = [
self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(__lowerCamelCase )
]
__A : List[Any] = torch.cat(__lowerCamelCase , dim=0 )
else:
__A : Tuple = self.vae.encode(__lowerCamelCase ).latent_dist.sample(__lowerCamelCase )
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
__A : Optional[int] = 0.1_82_15 * init_latents
__A : Optional[int] = init_latents.repeat_interleave(__lowerCamelCase , dim=0 )
__A : List[Any] = randn_tensor(init_latents.shape , generator=__lowerCamelCase , device=__lowerCamelCase , dtype=__lowerCamelCase )
# get latents
__A : Optional[int] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
__A : Optional[int] = init_latents
return latents
def _a ( self , __lowerCamelCase ):
'''simple docstring'''
__A : int = self.coca_transform(__lowerCamelCase ).unsqueeze(0 )
with torch.no_grad(), torch.cuda.amp.autocast():
__A : List[Any] = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) )
__A : Optional[int] = self.coca_tokenizer.decode(generated[0].cpu().numpy() )
return generated.split('<end_of_text>' )[0].replace('<start_of_text>' , '' ).rstrip(' .,' )
def _a ( self , __lowerCamelCase , __lowerCamelCase ):
'''simple docstring'''
__A : Optional[Any] = self.feature_extractor.preprocess(__lowerCamelCase )
__A : List[str] = torch.from_numpy(clip_image_input['pixel_values'][0] ).unsqueeze(0 ).to(self.device ).half()
__A : int = self.clip_model.get_image_features(__lowerCamelCase )
__A : Tuple = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__lowerCamelCase )
__A : Dict = image_embeddings_clip.repeat_interleave(__lowerCamelCase , dim=0 )
return image_embeddings_clip
@torch.enable_grad()
def _a ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ):
'''simple docstring'''
__A : Dict = latents.detach().requires_grad_()
__A : Dict = self.scheduler.scale_model_input(__lowerCamelCase , __lowerCamelCase )
# predict the noise residual
__A : Optional[Any] = self.unet(__lowerCamelCase , __lowerCamelCase , encoder_hidden_states=__lowerCamelCase ).sample
if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ):
__A : Union[str, Any] = self.scheduler.alphas_cumprod[timestep]
__A : Any = 1 - alpha_prod_t
# compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__A : str = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5
__A : List[str] = torch.sqrt(__lowerCamelCase )
__A : int = pred_original_sample * (fac) + latents * (1 - fac)
elif isinstance(self.scheduler , __lowerCamelCase ):
__A : List[Any] = self.scheduler.sigmas[index]
__A : Union[str, Any] = latents - sigma * noise_pred
else:
raise ValueError(F'scheduler type {type(self.scheduler )} not supported' )
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
__A : Tuple = 1 / 0.1_82_15 * sample
__A : List[Any] = self.vae.decode(__lowerCamelCase ).sample
__A : Optional[int] = (image / 2 + 0.5).clamp(0 , 1 )
__A : Optional[Any] = transforms.Resize(self.feature_extractor_size )(__lowerCamelCase )
__A : Optional[int] = self.normalize(__lowerCamelCase ).to(latents.dtype )
__A : List[str] = self.clip_model.get_image_features(__lowerCamelCase )
__A : Tuple = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__lowerCamelCase )
__A : str = spherical_dist_loss(__lowerCamelCase , __lowerCamelCase ).mean() * clip_guidance_scale
__A : List[str] = -torch.autograd.grad(__lowerCamelCase , __lowerCamelCase )[0]
if isinstance(self.scheduler , __lowerCamelCase ):
__A : int = latents.detach() + grads * (sigma**2)
__A : Any = noise_pred_original
else:
__A : Any = noise_pred_original - torch.sqrt(__lowerCamelCase ) * grads
return noise_pred, latents
@torch.no_grad()
def __call__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 512 , __lowerCamelCase = 512 , __lowerCamelCase = 0.6 , __lowerCamelCase = 50 , __lowerCamelCase = 7.5 , __lowerCamelCase = 1 , __lowerCamelCase = 0.0 , __lowerCamelCase = 100 , __lowerCamelCase = None , __lowerCamelCase = "pil" , __lowerCamelCase = True , __lowerCamelCase = 0.8 , __lowerCamelCase = 0.1 , __lowerCamelCase = 0.1 , ):
'''simple docstring'''
if isinstance(__lowerCamelCase , __lowerCamelCase ) and len(__lowerCamelCase ) != batch_size:
raise ValueError(F'You have passed {batch_size} batch_size, but only {len(__lowerCamelCase )} generators.' )
if height % 8 != 0 or width % 8 != 0:
raise ValueError(F'`height` and `width` have to be divisible by 8 but are {height} and {width}.' )
if isinstance(__lowerCamelCase , torch.Generator ) and batch_size > 1:
__A : str = [generator] + [None] * (batch_size - 1)
__A : str = [
('model', self.coca_model is None),
('tokenizer', self.coca_tokenizer is None),
('transform', self.coca_transform is None),
]
__A : List[str] = [x[0] for x in coca_is_none if x[1]]
__A : Optional[int] = ', '.join(__lowerCamelCase )
# generate prompts with coca model if prompt is None
if content_prompt is None:
if len(__lowerCamelCase ):
raise ValueError(
F'Content prompt is None and CoCa [{coca_is_none_str}] is None.'
F'Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.' )
__A : int = self.get_image_description(__lowerCamelCase )
if style_prompt is None:
if len(__lowerCamelCase ):
raise ValueError(
F'Style prompt is None and CoCa [{coca_is_none_str}] is None.'
F' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.' )
__A : Dict = self.get_image_description(__lowerCamelCase )
# get prompt text embeddings for content and style
__A : int = self.tokenizer(
__lowerCamelCase , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__lowerCamelCase , return_tensors='pt' , )
__A : Union[str, Any] = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0]
__A : str = self.tokenizer(
__lowerCamelCase , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__lowerCamelCase , return_tensors='pt' , )
__A : List[Any] = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0]
__A : Tuple = slerp(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
# duplicate text embeddings for each generation per prompt
__A : Union[str, Any] = text_embeddings.repeat_interleave(__lowerCamelCase , dim=0 )
# set timesteps
__A : Optional[int] = 'offset' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() )
__A : Dict = {}
if accepts_offset:
__A : str = 1
self.scheduler.set_timesteps(__lowerCamelCase , **__lowerCamelCase )
# Some schedulers like PNDM have timesteps as arrays
# It's more optimized to move all timesteps to correct device beforehand
self.scheduler.timesteps.to(self.device )
__A , __A : Tuple = self.get_timesteps(__lowerCamelCase , __lowerCamelCase , self.device )
__A : List[Any] = timesteps[:1].repeat(__lowerCamelCase )
# Preprocess image
__A : Dict = preprocess(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
__A : Optional[Any] = self.prepare_latents(
__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , text_embeddings.dtype , self.device , __lowerCamelCase )
__A : str = preprocess(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
__A : Tuple = self.prepare_latents(
__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , text_embeddings.dtype , self.device , __lowerCamelCase )
__A : Optional[Any] = slerp(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
if clip_guidance_scale > 0:
__A : Dict = self.get_clip_image_embeddings(__lowerCamelCase , __lowerCamelCase )
__A : int = self.get_clip_image_embeddings(__lowerCamelCase , __lowerCamelCase )
__A : Union[str, Any] = slerp(
__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
# corresponds to doing no classifier free guidance.
__A : Any = guidance_scale > 1.0
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance:
__A : Any = content_text_input.input_ids.shape[-1]
__A : List[str] = self.tokenizer([''] , padding='max_length' , max_length=__lowerCamelCase , return_tensors='pt' )
__A : Optional[Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]
# duplicate unconditional embeddings for each generation per prompt
__A : Optional[Any] = uncond_embeddings.repeat_interleave(__lowerCamelCase , dim=0 )
# 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
__A : Dict = torch.cat([uncond_embeddings, text_embeddings] )
# get the initial random noise unless the user supplied it
# Unlike in other pipelines, latents need to be generated in the target device
# for 1-to-1 results reproducibility with the CompVis implementation.
# However this currently doesn't work in `mps`.
__A : List[str] = (batch_size, self.unet.config.in_channels, height // 8, width // 8)
__A : Optional[int] = text_embeddings.dtype
if latents is None:
if self.device.type == "mps":
# randn does not work reproducibly on mps
__A : List[str] = torch.randn(__lowerCamelCase , generator=__lowerCamelCase , device='cpu' , dtype=__lowerCamelCase ).to(
self.device )
else:
__A : Optional[Any] = torch.randn(__lowerCamelCase , generator=__lowerCamelCase , device=self.device , dtype=__lowerCamelCase )
else:
if latents.shape != latents_shape:
raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' )
__A : str = latents.to(self.device )
# scale the initial noise by the standard deviation required by the scheduler
__A : Optional[Any] = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
__A : Union[str, Any] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
__A : Optional[int] = {}
if accepts_eta:
__A : Any = eta
# check if the scheduler accepts generator
__A : Union[str, Any] = 'generator' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
if accepts_generator:
__A : Optional[Any] = generator
with self.progress_bar(total=__lowerCamelCase ):
for i, t in enumerate(__lowerCamelCase ):
# expand the latents if we are doing classifier free guidance
__A : List[str] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
__A : Optional[Any] = self.scheduler.scale_model_input(__lowerCamelCase , __lowerCamelCase )
# predict the noise residual
__A : Optional[Any] = self.unet(__lowerCamelCase , __lowerCamelCase , encoder_hidden_states=__lowerCamelCase ).sample
# perform classifier free guidance
if do_classifier_free_guidance:
__A , __A : str = noise_pred.chunk(2 )
__A : Tuple = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# perform clip guidance
if clip_guidance_scale > 0:
__A : Optional[int] = (
text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings
)
__A , __A : List[Any] = self.cond_fn(
__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , )
# compute the previous noisy sample x_t -> x_t-1
__A : List[str] = self.scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ).prev_sample
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
__A : Union[str, Any] = 1 / 0.1_82_15 * latents
__A : Dict = self.vae.decode(__lowerCamelCase ).sample
__A : Dict = (image / 2 + 0.5).clamp(0 , 1 )
__A : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
__A : List[str] = self.numpy_to_pil(__lowerCamelCase )
if not return_dict:
return (image, None)
return StableDiffusionPipelineOutput(images=__lowerCamelCase , nsfw_content_detected=__lowerCamelCase )
| 237 | """simple docstring"""
from __future__ import annotations
from random import random
from typing import Generic, TypeVar
lowerCamelCase : Tuple =TypeVar('''KT''')
lowerCamelCase : Dict =TypeVar('''VT''')
class __snake_case( Generic[KT, VT] ):
'''simple docstring'''
def __init__( self , __lowerCamelCase = "root" , __lowerCamelCase = None ):
'''simple docstring'''
__A : str = key
__A : int = value
__A : list[Node[KT, VT]] = []
def __repr__( self ):
'''simple docstring'''
return F'Node({self.key}: {self.value})'
@property
def _a ( self ):
'''simple docstring'''
return len(self.forward )
class __snake_case( Generic[KT, VT] ):
'''simple docstring'''
def __init__( self , __lowerCamelCase = 0.5 , __lowerCamelCase = 16 ):
'''simple docstring'''
__A : Node[KT, VT] = Node[KT, VT]()
__A : str = 0
__A : Tuple = p
__A : Union[str, Any] = max_level
def __str__( self ):
'''simple docstring'''
__A : List[Any] = list(self )
if len(__lowerCamelCase ) == 0:
return F'SkipList(level={self.level})'
__A : Any = max((len(str(__lowerCamelCase ) ) for item in items) , default=4 )
__A : int = max(__lowerCamelCase , 4 ) + 4
__A : Optional[int] = self.head
__A : Union[str, Any] = []
__A : int = node.forward.copy()
lines.append(F'[{node.key}]'.ljust(__lowerCamelCase , '-' ) + '* ' * len(__lowerCamelCase ) )
lines.append(' ' * label_size + '| ' * len(__lowerCamelCase ) )
while len(node.forward ) != 0:
__A : List[Any] = node.forward[0]
lines.append(
F'[{node.key}]'.ljust(__lowerCamelCase , '-' )
+ ' '.join(str(n.key ) if n.key == node.key else '|' for n in forwards ) )
lines.append(' ' * label_size + '| ' * len(__lowerCamelCase ) )
__A : Tuple = node.forward
lines.append('None'.ljust(__lowerCamelCase ) + '* ' * len(__lowerCamelCase ) )
return F'SkipList(level={self.level})\n' + "\n".join(__lowerCamelCase )
def __iter__( self ):
'''simple docstring'''
__A : Dict = self.head
while len(node.forward ) != 0:
yield node.forward[0].key
__A : Any = node.forward[0]
def _a ( self ):
'''simple docstring'''
__A : Tuple = 1
while random() < self.p and level < self.max_level:
level += 1
return level
def _a ( self , __lowerCamelCase ):
'''simple docstring'''
__A : Dict = []
__A : List[str] = self.head
for i in reversed(range(self.level ) ):
# i < node.level - When node level is lesser than `i` decrement `i`.
# node.forward[i].key < key - Jumping to node with key value higher
# or equal to searched key would result
# in skipping searched key.
while i < node.level and node.forward[i].key < key:
__A : Any = node.forward[i]
# Each leftmost node (relative to searched node) will potentially have to
# be updated.
update_vector.append(__lowerCamelCase )
update_vector.reverse() # Note that we were inserting values in reverse order.
# len(node.forward) != 0 - If current node doesn't contain any further
# references then searched key is not present.
# node.forward[0].key == key - Next node key should be equal to search key
# if key is present.
if len(node.forward ) != 0 and node.forward[0].key == key:
return node.forward[0], update_vector
else:
return None, update_vector
def _a ( self , __lowerCamelCase ):
'''simple docstring'''
__A , __A : Optional[int] = self._locate_node(__lowerCamelCase )
if node is not None:
for i, update_node in enumerate(__lowerCamelCase ):
# Remove or replace all references to removed node.
if update_node.level > i and update_node.forward[i].key == key:
if node.level > i:
__A : Any = node.forward[i]
else:
__A : int = update_node.forward[:i]
def _a ( self , __lowerCamelCase , __lowerCamelCase ):
'''simple docstring'''
__A , __A : Any = self._locate_node(__lowerCamelCase )
if node is not None:
__A : Optional[Any] = value
else:
__A : str = self.random_level()
if level > self.level:
# After level increase we have to add additional nodes to head.
for _ in range(self.level - 1 , __lowerCamelCase ):
update_vector.append(self.head )
__A : Union[str, Any] = level
__A : str = Node(__lowerCamelCase , __lowerCamelCase )
for i, update_node in enumerate(update_vector[:level] ):
# Change references to pass through new node.
if update_node.level > i:
new_node.forward.append(update_node.forward[i] )
if update_node.level < i + 1:
update_node.forward.append(__lowerCamelCase )
else:
__A : str = new_node
def _a ( self , __lowerCamelCase ):
'''simple docstring'''
__A , __A : str = self._locate_node(__lowerCamelCase )
if node is not None:
return node.value
return None
def _lowercase ( ) -> Any:
'''simple docstring'''
__A : int = SkipList()
skip_list.insert('Key1' , 3 )
skip_list.insert('Key2' , 12 )
skip_list.insert('Key3' , 41 )
skip_list.insert('Key4' , -19 )
__A : List[Any] = skip_list.head
__A : str = {}
while node.level != 0:
__A : Optional[Any] = node.forward[0]
__A : Optional[Any] = node.value
assert len(_SCREAMING_SNAKE_CASE ) == 4
assert all_values["Key1"] == 3
assert all_values["Key2"] == 12
assert all_values["Key3"] == 41
assert all_values["Key4"] == -19
def _lowercase ( ) -> Any:
'''simple docstring'''
__A : Tuple = SkipList()
skip_list.insert('Key1' , 10 )
skip_list.insert('Key1' , 12 )
skip_list.insert('Key5' , 7 )
skip_list.insert('Key7' , 10 )
skip_list.insert('Key10' , 5 )
skip_list.insert('Key7' , 7 )
skip_list.insert('Key5' , 5 )
skip_list.insert('Key10' , 10 )
__A : Union[str, Any] = skip_list.head
__A : Optional[Any] = {}
while node.level != 0:
__A : str = node.forward[0]
__A : Tuple = node.value
if len(_SCREAMING_SNAKE_CASE ) != 4:
print()
assert len(_SCREAMING_SNAKE_CASE ) == 4
assert all_values["Key1"] == 12
assert all_values["Key7"] == 7
assert all_values["Key5"] == 5
assert all_values["Key10"] == 10
def _lowercase ( ) -> int:
'''simple docstring'''
__A : Optional[Any] = SkipList()
assert skip_list.find('Some key' ) is None
def _lowercase ( ) -> Any:
'''simple docstring'''
__A : List[str] = SkipList()
skip_list.insert('Key2' , 20 )
assert skip_list.find('Key2' ) == 20
skip_list.insert('Some Key' , 10 )
skip_list.insert('Key2' , 8 )
skip_list.insert('V' , 13 )
assert skip_list.find('Y' ) is None
assert skip_list.find('Key2' ) == 8
assert skip_list.find('Some Key' ) == 10
assert skip_list.find('V' ) == 13
def _lowercase ( ) -> str:
'''simple docstring'''
__A : int = SkipList()
skip_list.delete('Some key' )
assert len(skip_list.head.forward ) == 0
def _lowercase ( ) -> Dict:
'''simple docstring'''
__A : Union[str, Any] = SkipList()
skip_list.insert('Key1' , 12 )
skip_list.insert('V' , 13 )
skip_list.insert('X' , 14 )
skip_list.insert('Key2' , 15 )
skip_list.delete('V' )
skip_list.delete('Key2' )
assert skip_list.find('V' ) is None
assert skip_list.find('Key2' ) is None
def _lowercase ( ) -> Dict:
'''simple docstring'''
__A : Dict = SkipList()
skip_list.insert('Key1' , 12 )
skip_list.insert('V' , 13 )
skip_list.insert('X' , 14 )
skip_list.insert('Key2' , 15 )
skip_list.delete('V' )
assert skip_list.find('V' ) is None
assert skip_list.find('X' ) == 14
assert skip_list.find('Key1' ) == 12
assert skip_list.find('Key2' ) == 15
skip_list.delete('X' )
assert skip_list.find('V' ) is None
assert skip_list.find('X' ) is None
assert skip_list.find('Key1' ) == 12
assert skip_list.find('Key2' ) == 15
skip_list.delete('Key1' )
assert skip_list.find('V' ) is None
assert skip_list.find('X' ) is None
assert skip_list.find('Key1' ) is None
assert skip_list.find('Key2' ) == 15
skip_list.delete('Key2' )
assert skip_list.find('V' ) is None
assert skip_list.find('X' ) is None
assert skip_list.find('Key1' ) is None
assert skip_list.find('Key2' ) is None
def _lowercase ( ) -> Union[str, Any]:
'''simple docstring'''
__A : int = SkipList()
skip_list.insert('Key1' , 12 )
skip_list.insert('V' , 13 )
skip_list.insert('X' , 142 )
skip_list.insert('Key2' , 15 )
skip_list.delete('X' )
def traverse_keys(_SCREAMING_SNAKE_CASE : Union[str, Any] ):
yield node.key
for forward_node in node.forward:
yield from traverse_keys(_SCREAMING_SNAKE_CASE )
assert len(set(traverse_keys(skip_list.head ) ) ) == 4
def _lowercase ( ) -> Tuple:
'''simple docstring'''
def is_sorted(_SCREAMING_SNAKE_CASE : Optional[int] ):
return all(next_item >= item for item, next_item in zip(_SCREAMING_SNAKE_CASE , lst[1:] ) )
__A : Tuple = SkipList()
for i in range(10 ):
skip_list.insert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
assert is_sorted(list(_SCREAMING_SNAKE_CASE ) )
skip_list.delete(5 )
skip_list.delete(8 )
skip_list.delete(2 )
assert is_sorted(list(_SCREAMING_SNAKE_CASE ) )
skip_list.insert(-12 , -12 )
skip_list.insert(77 , 77 )
assert is_sorted(list(_SCREAMING_SNAKE_CASE ) )
def _lowercase ( ) -> Optional[int]:
'''simple docstring'''
for _ in range(100 ):
# Repeat test 100 times due to the probabilistic nature of skip list
# random values == random bugs
test_insert()
test_insert_overrides_existing_value()
test_searching_empty_list_returns_none()
test_search()
test_deleting_item_from_empty_list_do_nothing()
test_deleted_items_are_not_founded_by_find_method()
test_delete_removes_only_given_key()
test_delete_doesnt_leave_dead_nodes()
test_iter_always_yields_sorted_values()
def _lowercase ( ) -> Any:
'''simple docstring'''
__A : Optional[int] = SkipList()
skip_list.insert(2 , '2' )
skip_list.insert(4 , '4' )
skip_list.insert(6 , '4' )
skip_list.insert(4 , '5' )
skip_list.insert(8 , '4' )
skip_list.insert(9 , '4' )
skip_list.delete(4 )
print(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 237 | 1 |
import os
import pytest
from datasets import (
get_dataset_config_info,
get_dataset_config_names,
get_dataset_infos,
get_dataset_split_names,
inspect_dataset,
inspect_metric,
)
_lowerCamelCase = pytest.mark.integration
@pytest.mark.parametrize("""path""" , ["""paws""", """csv"""] )
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: Any ):
inspect_dataset(UpperCamelCase__ , UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Union[str, Any] ):
inspect_metric(UpperCamelCase__ , UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] , UpperCamelCase__: List[str] , UpperCamelCase__: Any ):
SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: str , 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 SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: str ):
SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ):
SCREAMING_SNAKE_CASE__ = get_dataset_infos(UpperCamelCase__ )
assert list(infos.keys() ) == expected_configs
SCREAMING_SNAKE_CASE__ = expected_configs[0]
assert expected_config in infos
SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: int , UpperCamelCase__: str ):
SCREAMING_SNAKE_CASE__ = get_dataset_infos(UpperCamelCase__ )
assert expected_config in infos
SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple , UpperCamelCase__: int ):
with pytest.raises(UpperCamelCase__ ):
get_dataset_split_names(UpperCamelCase__ , config_name=UpperCamelCase__ ) | 6 |
import argparse
import requests
import torch
# pip3 install salesforce-lavis
# I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis
from lavis.models import load_model_and_preprocess
from PIL import Image
from transformers import (
AutoTokenizer,
BlipaConfig,
BlipaForConditionalGeneration,
BlipaProcessor,
BlipaVisionConfig,
BlipImageProcessor,
OPTConfig,
TaConfig,
)
from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
def lowerCAmelCase__ ( )-> List[str]:
A__ = '''https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png'''
A__ = Image.open(requests.get(UpperCamelCase_ , stream=UpperCamelCase_ ).raw ).convert('''RGB''' )
return image
def lowerCAmelCase__ ( UpperCamelCase_ : Dict )-> Any:
A__ = []
# fmt: off
# vision encoder
rename_keys.append(('''visual_encoder.cls_token''', '''vision_model.embeddings.class_embedding''') )
rename_keys.append(('''visual_encoder.pos_embed''', '''vision_model.embeddings.position_embedding''') )
rename_keys.append(('''visual_encoder.patch_embed.proj.weight''', '''vision_model.embeddings.patch_embedding.weight''') )
rename_keys.append(('''visual_encoder.patch_embed.proj.bias''', '''vision_model.embeddings.patch_embedding.bias''') )
rename_keys.append(('''ln_vision.weight''', '''vision_model.post_layernorm.weight''') )
rename_keys.append(('''ln_vision.bias''', '''vision_model.post_layernorm.bias''') )
for i in range(config.vision_config.num_hidden_layers ):
rename_keys.append((f"visual_encoder.blocks.{i}.norm1.weight", f"vision_model.encoder.layers.{i}.layer_norm1.weight") )
rename_keys.append((f"visual_encoder.blocks.{i}.norm1.bias", f"vision_model.encoder.layers.{i}.layer_norm1.bias") )
rename_keys.append((f"visual_encoder.blocks.{i}.norm2.weight", f"vision_model.encoder.layers.{i}.layer_norm2.weight") )
rename_keys.append((f"visual_encoder.blocks.{i}.norm2.bias", f"vision_model.encoder.layers.{i}.layer_norm2.bias") )
rename_keys.append((f"visual_encoder.blocks.{i}.attn.qkv.weight", f"vision_model.encoder.layers.{i}.self_attn.qkv.weight") )
rename_keys.append((f"visual_encoder.blocks.{i}.attn.proj.weight", f"vision_model.encoder.layers.{i}.self_attn.projection.weight",) )
rename_keys.append((f"visual_encoder.blocks.{i}.attn.proj.bias", f"vision_model.encoder.layers.{i}.self_attn.projection.bias") )
rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc1.weight", f"vision_model.encoder.layers.{i}.mlp.fc1.weight") )
rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc1.bias", f"vision_model.encoder.layers.{i}.mlp.fc1.bias") )
rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc2.weight", f"vision_model.encoder.layers.{i}.mlp.fc2.weight") )
rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc2.bias", f"vision_model.encoder.layers.{i}.mlp.fc2.bias") )
# QFormer
rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.weight''', '''qformer.layernorm.weight''') )
rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.bias''', '''qformer.layernorm.bias''') )
# fmt: on
return rename_keys
def lowerCAmelCase__ ( UpperCamelCase_ : int , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : int )-> List[Any]:
A__ = dct.pop(UpperCamelCase_ )
A__ = val
def lowerCAmelCase__ ( UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Optional[int] )-> Optional[int]:
for i in range(config.vision_config.num_hidden_layers ):
# read in original q and v biases
A__ = state_dict.pop(f"visual_encoder.blocks.{i}.attn.q_bias" )
A__ = state_dict.pop(f"visual_encoder.blocks.{i}.attn.v_bias" )
# next, set bias in the state dict
A__ = torch.cat((q_bias, torch.zeros_like(UpperCamelCase_ , requires_grad=UpperCamelCase_ ), v_bias) )
A__ = qkv_bias
def lowerCAmelCase__ ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[Any] )-> int:
A__ = 3_6_4 if '''coco''' in model_name else 2_2_4
A__ = BlipaVisionConfig(image_size=UpperCamelCase_ ).to_dict()
# make sure the models have proper bos_token_id and eos_token_id set (important for generation)
# seems like flan-T5 models don't have bos_token_id properly set?
if "opt-2.7b" in model_name:
A__ = OPTConfig.from_pretrained('''facebook/opt-2.7b''' , eos_token_id=UpperCamelCase_ ).to_dict()
elif "opt-6.7b" in model_name:
A__ = OPTConfig.from_pretrained('''facebook/opt-6.7b''' , eos_token_id=UpperCamelCase_ ).to_dict()
elif "t5-xl" in model_name:
A__ = TaConfig.from_pretrained('''google/flan-t5-xl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict()
elif "t5-xxl" in model_name:
A__ = TaConfig.from_pretrained('''google/flan-t5-xxl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict()
A__ = BlipaConfig(vision_config=UpperCamelCase_ , text_config=UpperCamelCase_ )
return config, image_size
@torch.no_grad()
def lowerCAmelCase__ ( UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[Any]=None , UpperCamelCase_ : Any=False )-> Optional[Any]:
A__ = (
AutoTokenizer.from_pretrained('''facebook/opt-2.7b''' )
if '''opt''' in model_name
else AutoTokenizer.from_pretrained('''google/flan-t5-xl''' )
)
A__ = tokenizer('''\n''' , add_special_tokens=UpperCamelCase_ ).input_ids[0]
A__ , A__ = get_blipa_config(UpperCamelCase_ , eos_token_id=UpperCamelCase_ )
A__ = BlipaForConditionalGeneration(UpperCamelCase_ ).eval()
A__ = {
'''blip2-opt-2.7b''': ('''blip2_opt''', '''pretrain_opt2.7b'''),
'''blip2-opt-6.7b''': ('''blip2_opt''', '''pretrain_opt6.7b'''),
'''blip2-opt-2.7b-coco''': ('''blip2_opt''', '''caption_coco_opt2.7b'''),
'''blip2-opt-6.7b-coco''': ('''blip2_opt''', '''caption_coco_opt6.7b'''),
'''blip2-flan-t5-xl''': ('''blip2_t5''', '''pretrain_flant5xl'''),
'''blip2-flan-t5-xl-coco''': ('''blip2_t5''', '''caption_coco_flant5xl'''),
'''blip2-flan-t5-xxl''': ('''blip2_t5''', '''pretrain_flant5xxl'''),
}
A__ , A__ = model_name_to_original[model_name]
# load original model
print('''Loading original model...''' )
A__ = '''cuda''' if torch.cuda.is_available() else '''cpu'''
A__ , A__ , A__ = load_model_and_preprocess(
name=UpperCamelCase_ , model_type=UpperCamelCase_ , is_eval=UpperCamelCase_ , device=UpperCamelCase_ )
original_model.eval()
print('''Done!''' )
# update state dict keys
A__ = original_model.state_dict()
A__ = create_rename_keys(UpperCamelCase_ )
for src, dest in rename_keys:
rename_key(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
# some keys can be renamed efficiently
for key, val in state_dict.copy().items():
A__ = state_dict.pop(UpperCamelCase_ )
if key.startswith('''Qformer.bert''' ):
A__ = key.replace('''Qformer.bert''' , '''qformer''' )
if "attention.self" in key:
A__ = key.replace('''self''' , '''attention''' )
if "opt_proj" in key:
A__ = key.replace('''opt_proj''' , '''language_projection''' )
if "t5_proj" in key:
A__ = key.replace('''t5_proj''' , '''language_projection''' )
if key.startswith('''opt''' ):
A__ = key.replace('''opt''' , '''language''' )
if key.startswith('''t5''' ):
A__ = key.replace('''t5''' , '''language''' )
A__ = val
# read in qv biases
read_in_q_v_bias(UpperCamelCase_ , UpperCamelCase_ )
A__ , A__ = hf_model.load_state_dict(UpperCamelCase_ , strict=UpperCamelCase_ )
assert len(UpperCamelCase_ ) == 0
assert unexpected_keys == ["qformer.embeddings.position_ids"]
A__ = load_demo_image()
A__ = vis_processors['''eval'''](UpperCamelCase_ ).unsqueeze(0 ).to(UpperCamelCase_ )
A__ = tokenizer(['''\n'''] , return_tensors='''pt''' ).input_ids.to(UpperCamelCase_ )
# create processor
A__ = BlipImageProcessor(
size={'''height''': image_size, '''width''': image_size} , image_mean=UpperCamelCase_ , image_std=UpperCamelCase_ )
A__ = BlipaProcessor(image_processor=UpperCamelCase_ , tokenizer=UpperCamelCase_ )
A__ = processor(images=UpperCamelCase_ , return_tensors='''pt''' ).pixel_values.to(UpperCamelCase_ )
# make sure processor creates exact same pixel values
assert torch.allclose(UpperCamelCase_ , UpperCamelCase_ )
original_model.to(UpperCamelCase_ )
hf_model.to(UpperCamelCase_ )
with torch.no_grad():
if "opt" in model_name:
A__ = original_model({'''image''': original_pixel_values, '''text_input''': ['''''']} ).logits
A__ = hf_model(UpperCamelCase_ , UpperCamelCase_ ).logits
else:
A__ = original_model(
{'''image''': original_pixel_values, '''text_input''': ['''\n'''], '''text_output''': ['''\n''']} ).logits
A__ = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -1_0_0 )
A__ = hf_model(UpperCamelCase_ , UpperCamelCase_ , labels=UpperCamelCase_ ).logits
assert original_logits.shape == logits.shape
print('''First values of original logits:''' , original_logits[0, :3, :3] )
print('''First values of HF logits:''' , logits[0, :3, :3] )
# assert values
if model_name == "blip2-flan-t5-xl":
A__ = torch.tensor(
[[-41.5850, -4.4440, -8.9922], [-47.4322, -5.9143, -1.7340]] , device=UpperCamelCase_ )
assert torch.allclose(logits[0, :3, :3] , UpperCamelCase_ , atol=1E-4 )
elif model_name == "blip2-flan-t5-xl-coco":
A__ = torch.tensor(
[[-57.0109, -9.8967, -12.6280], [-68.6578, -12.7191, -10.5065]] , device=UpperCamelCase_ )
else:
# cast to same type
A__ = logits.dtype
assert torch.allclose(original_logits.to(UpperCamelCase_ ) , UpperCamelCase_ , atol=1E-2 )
print('''Looks ok!''' )
print('''Generating a caption...''' )
A__ = ''''''
A__ = tokenizer(UpperCamelCase_ , return_tensors='''pt''' ).input_ids.to(UpperCamelCase_ )
A__ = original_model.generate({'''image''': original_pixel_values} )
A__ = hf_model.generate(
UpperCamelCase_ , UpperCamelCase_ , do_sample=UpperCamelCase_ , num_beams=5 , max_length=3_0 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , )
print('''Original generation:''' , UpperCamelCase_ )
A__ = input_ids.shape[1]
A__ = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=UpperCamelCase_ )
A__ = [text.strip() for text in output_text]
print('''HF generation:''' , UpperCamelCase_ )
if pytorch_dump_folder_path is not None:
processor.save_pretrained(UpperCamelCase_ )
hf_model.save_pretrained(UpperCamelCase_ )
if push_to_hub:
processor.push_to_hub(f"nielsr/{model_name}" )
hf_model.push_to_hub(f"nielsr/{model_name}" )
if __name__ == "__main__":
_lowercase = argparse.ArgumentParser()
_lowercase = [
"blip2-opt-2.7b",
"blip2-opt-6.7b",
"blip2-opt-2.7b-coco",
"blip2-opt-6.7b-coco",
"blip2-flan-t5-xl",
"blip2-flan-t5-xl-coco",
"blip2-flan-t5-xxl",
]
parser.add_argument(
"--model_name",
default="blip2-opt-2.7b",
choices=choices,
type=str,
help="Path to hf config.json of model to convert",
)
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
parser.add_argument(
"--push_to_hub",
action="store_true",
help="Whether to push the model and processor to the hub after converting",
)
_lowercase = parser.parse_args()
convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 632 | 0 |
import unittest
from queue import Empty
from threading import Thread
from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available
from transformers.testing_utils import CaptureStdout, require_torch, torch_device
from ..test_modeling_common import ids_tensor
if is_torch_available():
import torch
from transformers import AutoModelForCausalLM
@require_torch
class lowerCamelCase__ ( unittest.TestCase):
'''simple docstring'''
def _lowerCamelCase ( self :str ) -> Union[str, Any]:
__UpperCamelCase : int = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
__UpperCamelCase : List[Any] = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__snake_case )
__UpperCamelCase : Optional[Any] = -1
__UpperCamelCase : List[str] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__snake_case )
__UpperCamelCase : Tuple = model.generate(__snake_case , max_new_tokens=1_0 , do_sample=__snake_case )
__UpperCamelCase : str = tokenizer.decode(greedy_ids[0] )
with CaptureStdout() as cs:
__UpperCamelCase : str = TextStreamer(__snake_case )
model.generate(__snake_case , max_new_tokens=1_0 , do_sample=__snake_case , streamer=__snake_case )
# The greedy text should be printed to stdout, except for the final "\n" in the streamer
__UpperCamelCase : Optional[int] = cs.out[:-1]
self.assertEqual(__snake_case , __snake_case )
def _lowerCamelCase ( self :Dict ) -> Tuple:
__UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
__UpperCamelCase : int = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__snake_case )
__UpperCamelCase : List[Any] = -1
__UpperCamelCase : Dict = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__snake_case )
__UpperCamelCase : Tuple = model.generate(__snake_case , max_new_tokens=1_0 , do_sample=__snake_case )
__UpperCamelCase : List[Any] = tokenizer.decode(greedy_ids[0] )
__UpperCamelCase : List[str] = TextIteratorStreamer(__snake_case )
__UpperCamelCase : List[str] = {'''input_ids''': input_ids, '''max_new_tokens''': 1_0, '''do_sample''': False, '''streamer''': streamer}
__UpperCamelCase : Tuple = Thread(target=model.generate , kwargs=__snake_case )
thread.start()
__UpperCamelCase : Any = ''''''
for new_text in streamer:
streamer_text += new_text
self.assertEqual(__snake_case , __snake_case )
def _lowerCamelCase ( self :str ) -> Union[str, Any]:
__UpperCamelCase : int = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
__UpperCamelCase : Dict = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__snake_case )
__UpperCamelCase : List[str] = -1
__UpperCamelCase : Optional[Any] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__snake_case )
__UpperCamelCase : Optional[Any] = model.generate(__snake_case , max_new_tokens=1_0 , do_sample=__snake_case )
__UpperCamelCase : List[str] = greedy_ids[:, input_ids.shape[1] :]
__UpperCamelCase : Union[str, Any] = tokenizer.decode(new_greedy_ids[0] )
with CaptureStdout() as cs:
__UpperCamelCase : List[str] = TextStreamer(__snake_case , skip_prompt=__snake_case )
model.generate(__snake_case , max_new_tokens=1_0 , do_sample=__snake_case , streamer=__snake_case )
# The greedy text should be printed to stdout, except for the final "\n" in the streamer
__UpperCamelCase : int = cs.out[:-1]
self.assertEqual(__snake_case , __snake_case )
def _lowerCamelCase ( self :Optional[int] ) -> Optional[int]:
# Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested
# with actual models -- the dummy models' tokenizers are not aligned with their models, and
# `skip_special_tokens=True` has no effect on them
__UpperCamelCase : List[Any] = AutoTokenizer.from_pretrained("distilgpt2" )
__UpperCamelCase : Union[str, Any] = AutoModelForCausalLM.from_pretrained("distilgpt2" ).to(__snake_case )
__UpperCamelCase : Optional[int] = -1
__UpperCamelCase : Union[str, Any] = torch.ones((1, 5) , device=__snake_case ).long() * model.config.bos_token_id
with CaptureStdout() as cs:
__UpperCamelCase : Dict = TextStreamer(__snake_case , skip_special_tokens=__snake_case )
model.generate(__snake_case , max_new_tokens=1 , do_sample=__snake_case , streamer=__snake_case )
# The prompt contains a special token, so the streamer should not print it. As such, the output text, when
# re-tokenized, must only contain one token
__UpperCamelCase : Tuple = cs.out[:-1] # Remove the final "\n"
__UpperCamelCase : int = tokenizer(__snake_case , return_tensors="pt" )
self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) )
def _lowerCamelCase ( self :List[Any] ) -> Dict:
__UpperCamelCase : List[str] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
__UpperCamelCase : Optional[int] = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(__snake_case )
__UpperCamelCase : Optional[int] = -1
__UpperCamelCase : Tuple = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__snake_case )
__UpperCamelCase : List[Any] = TextIteratorStreamer(__snake_case , timeout=0.001 )
__UpperCamelCase : Dict = {'''input_ids''': input_ids, '''max_new_tokens''': 1_0, '''do_sample''': False, '''streamer''': streamer}
__UpperCamelCase : Tuple = Thread(target=model.generate , kwargs=__snake_case )
thread.start()
# The streamer will timeout after 0.001 seconds, so an exception will be raised
with self.assertRaises(__snake_case ):
__UpperCamelCase : Dict = ''''''
for new_text in streamer:
streamer_text += new_text | 705 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
lowercase : Optional[Any] = {
'configuration_blip_2': [
'BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP',
'Blip2Config',
'Blip2QFormerConfig',
'Blip2VisionConfig',
],
'processing_blip_2': ['Blip2Processor'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase : Tuple = [
'BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST',
'Blip2Model',
'Blip2QFormerModel',
'Blip2PreTrainedModel',
'Blip2ForConditionalGeneration',
'Blip2VisionModel',
]
if TYPE_CHECKING:
from .configuration_blip_a import (
BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
BlipaConfig,
BlipaQFormerConfig,
BlipaVisionConfig,
)
from .processing_blip_a import BlipaProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blip_a import (
BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST,
BlipaForConditionalGeneration,
BlipaModel,
BlipaPreTrainedModel,
BlipaQFormerModel,
BlipaVisionModel,
)
else:
import sys
lowercase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__) | 94 | 0 |
import tempfile
import torch
from diffusers import (
DEISMultistepScheduler,
DPMSolverMultistepScheduler,
DPMSolverSinglestepScheduler,
UniPCMultistepScheduler,
)
from .test_schedulers import SchedulerCommonTest
class lowerCamelCase__ ( A__ ):
__lowerCamelCase = (DPMSolverSinglestepScheduler,)
__lowerCamelCase = (("""num_inference_steps""", 25),)
def lowerCamelCase_ ( self : Union[str, Any] , **__a : List[Any] ):
'''simple docstring'''
lowerCamelCase__: List[str] = {
"""num_train_timesteps""": 1000,
"""beta_start""": 0.0_001,
"""beta_end""": 0.02,
"""beta_schedule""": """linear""",
"""solver_order""": 2,
"""prediction_type""": """epsilon""",
"""thresholding""": False,
"""sample_max_value""": 1.0,
"""algorithm_type""": """dpmsolver++""",
"""solver_type""": """midpoint""",
"""lambda_min_clipped""": -float("""inf""" ),
"""variance_type""": None,
}
config.update(**__a )
return config
def lowerCamelCase_ ( self : Union[str, Any] , __a : str=0 , **__a : Optional[Any] ):
'''simple docstring'''
lowerCamelCase__: List[Any] = dict(self.forward_default_kwargs )
lowerCamelCase__: Optional[int] = kwargs.pop("""num_inference_steps""" , __a )
lowerCamelCase__: Tuple = self.dummy_sample
lowerCamelCase__: Dict = 0.1 * sample
lowerCamelCase__: Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
lowerCamelCase__: Optional[Any] = self.get_scheduler_config(**__a )
lowerCamelCase__: Dict = scheduler_class(**__a )
scheduler.set_timesteps(__a )
# copy over dummy past residuals
lowerCamelCase__: List[Any] = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(__a )
lowerCamelCase__: Dict = scheduler_class.from_pretrained(__a )
new_scheduler.set_timesteps(__a )
# copy over dummy past residuals
lowerCamelCase__: Optional[int] = dummy_past_residuals[: new_scheduler.config.solver_order]
lowerCamelCase__ , lowerCamelCase__: List[str] = sample, sample
for t in range(__a , time_step + scheduler.config.solver_order + 1 ):
lowerCamelCase__: int = scheduler.step(__a , __a , __a , **__a ).prev_sample
lowerCamelCase__: List[str] = new_scheduler.step(__a , __a , __a , **__a ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def lowerCamelCase_ ( self : List[str] ):
'''simple docstring'''
pass
def lowerCamelCase_ ( self : Union[str, Any] , __a : int=0 , **__a : Optional[Any] ):
'''simple docstring'''
lowerCamelCase__: int = dict(self.forward_default_kwargs )
lowerCamelCase__: Optional[int] = kwargs.pop("""num_inference_steps""" , __a )
lowerCamelCase__: Tuple = self.dummy_sample
lowerCamelCase__: List[Any] = 0.1 * sample
lowerCamelCase__: Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
lowerCamelCase__: Optional[int] = self.get_scheduler_config()
lowerCamelCase__: Tuple = scheduler_class(**__a )
scheduler.set_timesteps(__a )
# copy over dummy past residuals (must be after setting timesteps)
lowerCamelCase__: Tuple = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(__a )
lowerCamelCase__: Any = scheduler_class.from_pretrained(__a )
# copy over dummy past residuals
new_scheduler.set_timesteps(__a )
# copy over dummy past residual (must be after setting timesteps)
lowerCamelCase__: Tuple = dummy_past_residuals[: new_scheduler.config.solver_order]
lowerCamelCase__: Any = scheduler.step(__a , __a , __a , **__a ).prev_sample
lowerCamelCase__: Optional[Any] = new_scheduler.step(__a , __a , __a , **__a ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def lowerCamelCase_ ( self : List[str] , __a : str=None , **__a : Optional[Any] ):
'''simple docstring'''
if scheduler is None:
lowerCamelCase__: List[Any] = self.scheduler_classes[0]
lowerCamelCase__: Optional[int] = self.get_scheduler_config(**__a )
lowerCamelCase__: Optional[Any] = scheduler_class(**__a )
lowerCamelCase__: Optional[Any] = self.scheduler_classes[0]
lowerCamelCase__: str = self.get_scheduler_config(**__a )
lowerCamelCase__: Tuple = scheduler_class(**__a )
lowerCamelCase__: Optional[Any] = 10
lowerCamelCase__: str = self.dummy_model()
lowerCamelCase__: int = self.dummy_sample_deter
scheduler.set_timesteps(__a )
for i, t in enumerate(scheduler.timesteps ):
lowerCamelCase__: Any = model(__a , __a )
lowerCamelCase__: Any = scheduler.step(__a , __a , __a ).prev_sample
return sample
def lowerCamelCase_ ( self : str ):
'''simple docstring'''
lowerCamelCase__: int = DPMSolverSinglestepScheduler(**self.get_scheduler_config() )
lowerCamelCase__: str = 50
lowerCamelCase__: str = self.dummy_model()
lowerCamelCase__: str = self.dummy_sample_deter
scheduler.set_timesteps(__a )
# make sure that the first t is uneven
for i, t in enumerate(scheduler.timesteps[3:] ):
lowerCamelCase__: Optional[Any] = model(__a , __a )
lowerCamelCase__: Union[str, Any] = scheduler.step(__a , __a , __a ).prev_sample
lowerCamelCase__: List[Any] = torch.mean(torch.abs(__a ) )
assert abs(result_mean.item() - 0.2_574 ) < 1e-3
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
for timesteps in [25, 50, 100, 999, 1000]:
self.check_over_configs(num_train_timesteps=__a )
def lowerCamelCase_ ( self : str ):
'''simple docstring'''
lowerCamelCase__: Dict = DPMSolverSinglestepScheduler(**self.get_scheduler_config() )
lowerCamelCase__: List[str] = self.full_loop(scheduler=__a )
lowerCamelCase__: Dict = torch.mean(torch.abs(__a ) )
assert abs(result_mean.item() - 0.2_791 ) < 1e-3
lowerCamelCase__: Dict = DEISMultistepScheduler.from_config(scheduler.config )
lowerCamelCase__: int = DPMSolverMultistepScheduler.from_config(scheduler.config )
lowerCamelCase__: Optional[int] = UniPCMultistepScheduler.from_config(scheduler.config )
lowerCamelCase__: int = DPMSolverSinglestepScheduler.from_config(scheduler.config )
lowerCamelCase__: int = self.full_loop(scheduler=__a )
lowerCamelCase__: Tuple = torch.mean(torch.abs(__a ) )
assert abs(result_mean.item() - 0.2_791 ) < 1e-3
def lowerCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
self.check_over_configs(thresholding=__a )
for order in [1, 2, 3]:
for solver_type in ["midpoint", "heun"]:
for threshold in [0.5, 1.0, 2.0]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
thresholding=__a , prediction_type=__a , sample_max_value=__a , algorithm_type="""dpmsolver++""" , solver_order=__a , solver_type=__a , )
def lowerCamelCase_ ( self : Any ):
'''simple docstring'''
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=__a )
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
for algorithm_type in ["dpmsolver", "dpmsolver++"]:
for solver_type in ["midpoint", "heun"]:
for order in [1, 2, 3]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
solver_order=__a , solver_type=__a , prediction_type=__a , algorithm_type=__a , )
lowerCamelCase__: Dict = self.full_loop(
solver_order=__a , solver_type=__a , prediction_type=__a , algorithm_type=__a , )
assert not torch.isnan(__a ).any(), "Samples have nan numbers"
def lowerCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
self.check_over_configs(lower_order_final=__a )
self.check_over_configs(lower_order_final=__a )
def lowerCamelCase_ ( self : str ):
'''simple docstring'''
self.check_over_configs(lambda_min_clipped=-float("""inf""" ) )
self.check_over_configs(lambda_min_clipped=-5.1 )
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
self.check_over_configs(variance_type=__a )
self.check_over_configs(variance_type="""learned_range""" )
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]:
self.check_over_forward(num_inference_steps=__a , time_step=0 )
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
lowerCamelCase__: List[str] = self.full_loop()
lowerCamelCase__: List[Any] = torch.mean(torch.abs(__a ) )
assert abs(result_mean.item() - 0.2_791 ) < 1e-3
def lowerCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
lowerCamelCase__: Optional[int] = self.full_loop(use_karras_sigmas=__a )
lowerCamelCase__: Optional[Any] = torch.mean(torch.abs(__a ) )
assert abs(result_mean.item() - 0.2_248 ) < 1e-3
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
lowerCamelCase__: List[Any] = self.full_loop(prediction_type="""v_prediction""" )
lowerCamelCase__: Tuple = torch.mean(torch.abs(__a ) )
assert abs(result_mean.item() - 0.1_453 ) < 1e-3
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
lowerCamelCase__: Dict = self.full_loop(prediction_type="""v_prediction""" , use_karras_sigmas=__a )
lowerCamelCase__: Union[str, Any] = torch.mean(torch.abs(__a ) )
assert abs(result_mean.item() - 0.0_649 ) < 1e-3
def lowerCamelCase_ ( self : List[str] ):
'''simple docstring'''
lowerCamelCase__: Optional[Any] = self.scheduler_classes[0]
lowerCamelCase__: Optional[Any] = self.get_scheduler_config(thresholding=__a , dynamic_thresholding_ratio=0 )
lowerCamelCase__: int = scheduler_class(**__a )
lowerCamelCase__: List[str] = 10
lowerCamelCase__: Union[str, Any] = self.dummy_model()
lowerCamelCase__: str = self.dummy_sample_deter.half()
scheduler.set_timesteps(__a )
for i, t in enumerate(scheduler.timesteps ):
lowerCamelCase__: str = model(__a , __a )
lowerCamelCase__: Optional[Any] = scheduler.step(__a , __a , __a ).prev_sample
assert sample.dtype == torch.floataa
| 306 |
import argparse
import pathlib
import fairseq
import torch
from fairseq.models.roberta import RobertaModel as FairseqRobertaModel
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version
from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertSelfAttention,
BertSelfOutput,
)
from transformers.models.roberta.modeling_roberta import RobertaAttention
from transformers.utils import logging
if version.parse(fairseq.__version__) < version.parse('1.0.0a'):
raise Exception('requires fairseq >= 1.0.0a')
logging.set_verbosity_info()
_lowercase = logging.get_logger(__name__)
_lowercase = 'Hello world! cécé herlolip'
def __lowerCAmelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple:
'''simple docstring'''
lowerCamelCase__: Any = FairseqRobertaModel.from_pretrained(_UpperCamelCase )
roberta.eval() # disable dropout
lowerCamelCase__: Any = roberta.model.encoder.sentence_encoder
lowerCamelCase__: Any = XLMRobertaConfig(
vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1E-5 , )
if classification_head:
lowerCamelCase__: Union[str, Any] = roberta.model.classification_heads["""mnli"""].out_proj.weight.shape[0]
print("""Our RoBERTa config:""" , _UpperCamelCase )
lowerCamelCase__: str = XLMRobertaXLForSequenceClassification(_UpperCamelCase ) if classification_head else XLMRobertaXLForMaskedLM(_UpperCamelCase )
model.eval()
# Now let's copy all the weights.
# Embeddings
lowerCamelCase__: Union[str, Any] = roberta_sent_encoder.embed_tokens.weight
lowerCamelCase__: List[str] = roberta_sent_encoder.embed_positions.weight
lowerCamelCase__: Optional[int] = torch.zeros_like(
model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them.
lowerCamelCase__: Any = roberta_sent_encoder.layer_norm.weight
lowerCamelCase__: Tuple = roberta_sent_encoder.layer_norm.bias
for i in range(config.num_hidden_layers ):
# Encoder: start of layer
lowerCamelCase__: BertLayer = model.roberta.encoder.layer[i]
lowerCamelCase__: TransformerSentenceEncoderLayer = roberta_sent_encoder.layers[i]
lowerCamelCase__: RobertaAttention = layer.attention
lowerCamelCase__: Union[str, Any] = roberta_layer.self_attn_layer_norm.weight
lowerCamelCase__: Any = roberta_layer.self_attn_layer_norm.bias
# self attention
lowerCamelCase__: BertSelfAttention = layer.attention.self
assert (
roberta_layer.self_attn.k_proj.weight.data.shape
== roberta_layer.self_attn.q_proj.weight.data.shape
== roberta_layer.self_attn.v_proj.weight.data.shape
== torch.Size((config.hidden_size, config.hidden_size) )
)
lowerCamelCase__: Tuple = roberta_layer.self_attn.q_proj.weight
lowerCamelCase__: Optional[int] = roberta_layer.self_attn.q_proj.bias
lowerCamelCase__: Optional[int] = roberta_layer.self_attn.k_proj.weight
lowerCamelCase__: int = roberta_layer.self_attn.k_proj.bias
lowerCamelCase__: Union[str, Any] = roberta_layer.self_attn.v_proj.weight
lowerCamelCase__: List[str] = roberta_layer.self_attn.v_proj.bias
# self-attention output
lowerCamelCase__: BertSelfOutput = layer.attention.output
assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape
lowerCamelCase__: int = roberta_layer.self_attn.out_proj.weight
lowerCamelCase__: Tuple = roberta_layer.self_attn.out_proj.bias
# this one is final layer norm
lowerCamelCase__: Any = roberta_layer.final_layer_norm.weight
lowerCamelCase__: Optional[int] = roberta_layer.final_layer_norm.bias
# intermediate
lowerCamelCase__: BertIntermediate = layer.intermediate
assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape
lowerCamelCase__: Tuple = roberta_layer.fca.weight
lowerCamelCase__: Tuple = roberta_layer.fca.bias
# output
lowerCamelCase__: BertOutput = layer.output
assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape
lowerCamelCase__: Any = roberta_layer.fca.weight
lowerCamelCase__: Optional[int] = roberta_layer.fca.bias
# end of layer
if classification_head:
lowerCamelCase__: Dict = roberta.model.classification_heads["""mnli"""].dense.weight
lowerCamelCase__: Union[str, Any] = roberta.model.classification_heads["""mnli"""].dense.bias
lowerCamelCase__: str = roberta.model.classification_heads["""mnli"""].out_proj.weight
lowerCamelCase__: List[str] = roberta.model.classification_heads["""mnli"""].out_proj.bias
else:
# LM Head
lowerCamelCase__: List[Any] = roberta.model.encoder.lm_head.dense.weight
lowerCamelCase__: List[Any] = roberta.model.encoder.lm_head.dense.bias
lowerCamelCase__: Optional[Any] = roberta.model.encoder.lm_head.layer_norm.weight
lowerCamelCase__: Optional[int] = roberta.model.encoder.lm_head.layer_norm.bias
lowerCamelCase__: List[Any] = roberta.model.encoder.lm_head.weight
lowerCamelCase__: Dict = roberta.model.encoder.lm_head.bias
# Let's check that we get the same results.
lowerCamelCase__: torch.Tensor = roberta.encode(_UpperCamelCase ).unsqueeze(0 ) # batch of size 1
lowerCamelCase__: Dict = model(_UpperCamelCase )[0]
if classification_head:
lowerCamelCase__: Optional[int] = roberta.model.classification_heads["""mnli"""](roberta.extract_features(_UpperCamelCase ) )
else:
lowerCamelCase__: List[Any] = roberta.model(_UpperCamelCase )[0]
print(our_output.shape , their_output.shape )
lowerCamelCase__: Optional[int] = torch.max(torch.abs(our_output - their_output ) ).item()
print(f"""max_absolute_diff = {max_absolute_diff}""" ) # ~ 1e-7
lowerCamelCase__: List[Any] = torch.allclose(_UpperCamelCase , _UpperCamelCase , atol=1E-3 )
print("""Do both models output the same tensors?""" , """🔥""" if success else """💩""" )
if not success:
raise Exception("""Something went wRoNg""" )
pathlib.Path(_UpperCamelCase ).mkdir(parents=_UpperCamelCase , exist_ok=_UpperCamelCase )
print(f"""Saving model to {pytorch_dump_folder_path}""" )
model.save_pretrained(_UpperCamelCase )
if __name__ == "__main__":
_lowercase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--roberta_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.'
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
parser.add_argument(
'--classification_head', action='store_true', help='Whether to convert a final classification head.'
)
_lowercase = parser.parse_args()
convert_xlm_roberta_xl_checkpoint_to_pytorch(
args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
)
| 306 | 1 |
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
if is_torch_available():
from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
@require_torch
@require_sentencepiece
@require_tokenizers
class A__ ( unittest.TestCase ):
'''simple docstring'''
@slow
def _SCREAMING_SNAKE_CASE ( self : Tuple ):
"""simple docstring"""
UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained('google/mt5-small' , return_dict=_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE )
UpperCamelCase = AutoTokenizer.from_pretrained('google/mt5-small' )
UpperCamelCase = tokenizer('Hello there' , return_tensors='pt' ).input_ids
UpperCamelCase = tokenizer('Hi I am' , return_tensors='pt' ).input_ids
UpperCamelCase = model(input_ids.to(_SCREAMING_SNAKE_CASE ) , labels=labels.to(_SCREAMING_SNAKE_CASE ) ).loss
UpperCamelCase = -(labels.shape[-1] * loss.item())
UpperCamelCase = -8_4.9_1_2_7
self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
| 410 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_realm import RealmTokenizer
__magic_name__ : Optional[Any] = logging.get_logger(__name__)
__magic_name__ : Optional[int] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}
__magic_name__ : str = {
'''vocab_file''': {
'''google/realm-cc-news-pretrained-embedder''': (
'''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt'''
),
'''google/realm-cc-news-pretrained-encoder''': (
'''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt'''
),
'''google/realm-cc-news-pretrained-scorer''': (
'''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt'''
),
'''google/realm-cc-news-pretrained-openqa''': (
'''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt'''
),
'''google/realm-orqa-nq-openqa''': '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt''',
'''google/realm-orqa-nq-reader''': '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt''',
'''google/realm-orqa-wq-openqa''': '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt''',
'''google/realm-orqa-wq-reader''': '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt''',
},
'''tokenizer_file''': {
'''google/realm-cc-news-pretrained-embedder''': (
'''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont'''
),
'''google/realm-cc-news-pretrained-encoder''': (
'''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json'''
),
'''google/realm-cc-news-pretrained-scorer''': (
'''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json'''
),
'''google/realm-cc-news-pretrained-openqa''': (
'''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json'''
),
'''google/realm-orqa-nq-openqa''': (
'''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json'''
),
'''google/realm-orqa-nq-reader''': (
'''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json'''
),
'''google/realm-orqa-wq-openqa''': (
'''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json'''
),
'''google/realm-orqa-wq-reader''': (
'''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json'''
),
},
}
__magic_name__ : Any = {
'''google/realm-cc-news-pretrained-embedder''': 512,
'''google/realm-cc-news-pretrained-encoder''': 512,
'''google/realm-cc-news-pretrained-scorer''': 512,
'''google/realm-cc-news-pretrained-openqa''': 512,
'''google/realm-orqa-nq-openqa''': 512,
'''google/realm-orqa-nq-reader''': 512,
'''google/realm-orqa-wq-openqa''': 512,
'''google/realm-orqa-wq-reader''': 512,
}
__magic_name__ : Any = {
'''google/realm-cc-news-pretrained-embedder''': {'''do_lower_case''': True},
'''google/realm-cc-news-pretrained-encoder''': {'''do_lower_case''': True},
'''google/realm-cc-news-pretrained-scorer''': {'''do_lower_case''': True},
'''google/realm-cc-news-pretrained-openqa''': {'''do_lower_case''': True},
'''google/realm-orqa-nq-openqa''': {'''do_lower_case''': True},
'''google/realm-orqa-nq-reader''': {'''do_lower_case''': True},
'''google/realm-orqa-wq-openqa''': {'''do_lower_case''': True},
'''google/realm-orqa-wq-reader''': {'''do_lower_case''': True},
}
class A__ ( __snake_case ):
'''simple docstring'''
snake_case__ = VOCAB_FILES_NAMES
snake_case__ = PRETRAINED_VOCAB_FILES_MAP
snake_case__ = PRETRAINED_INIT_CONFIGURATION
snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case__ = RealmTokenizer
def __init__( self : str , _SCREAMING_SNAKE_CASE : Union[str, Any]=None , _SCREAMING_SNAKE_CASE : Tuple=None , _SCREAMING_SNAKE_CASE : Optional[Any]=True , _SCREAMING_SNAKE_CASE : Tuple="[UNK]" , _SCREAMING_SNAKE_CASE : Optional[int]="[SEP]" , _SCREAMING_SNAKE_CASE : Dict="[PAD]" , _SCREAMING_SNAKE_CASE : Any="[CLS]" , _SCREAMING_SNAKE_CASE : int="[MASK]" , _SCREAMING_SNAKE_CASE : int=True , _SCREAMING_SNAKE_CASE : List[str]=None , **_SCREAMING_SNAKE_CASE : int , ):
"""simple docstring"""
super().__init__(
_SCREAMING_SNAKE_CASE , tokenizer_file=_SCREAMING_SNAKE_CASE , do_lower_case=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , tokenize_chinese_chars=_SCREAMING_SNAKE_CASE , strip_accents=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get('lowercase' , _SCREAMING_SNAKE_CASE ) != do_lower_case
or normalizer_state.get('strip_accents' , _SCREAMING_SNAKE_CASE ) != strip_accents
or normalizer_state.get('handle_chinese_chars' , _SCREAMING_SNAKE_CASE ) != tokenize_chinese_chars
):
UpperCamelCase = getattr(_SCREAMING_SNAKE_CASE , normalizer_state.pop('type' ) )
UpperCamelCase = do_lower_case
UpperCamelCase = strip_accents
UpperCamelCase = tokenize_chinese_chars
UpperCamelCase = normalizer_class(**_SCREAMING_SNAKE_CASE )
UpperCamelCase = do_lower_case
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , _SCREAMING_SNAKE_CASE : str , **_SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
UpperCamelCase = PaddingStrategy.MAX_LENGTH
UpperCamelCase = text
UpperCamelCase = kwargs.pop('text_pair' , _SCREAMING_SNAKE_CASE )
UpperCamelCase = kwargs.pop('return_tensors' , _SCREAMING_SNAKE_CASE )
UpperCamelCase = {
'input_ids': [],
'attention_mask': [],
'token_type_ids': [],
}
for idx, candidate_text in enumerate(_SCREAMING_SNAKE_CASE ):
if batch_text_pair is not None:
UpperCamelCase = batch_text_pair[idx]
else:
UpperCamelCase = None
UpperCamelCase = super().__call__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
UpperCamelCase = encoded_candidates.get('input_ids' )
UpperCamelCase = encoded_candidates.get('attention_mask' )
UpperCamelCase = encoded_candidates.get('token_type_ids' )
if encoded_input_ids is not None:
output_data["input_ids"].append(_SCREAMING_SNAKE_CASE )
if encoded_attention_mask is not None:
output_data["attention_mask"].append(_SCREAMING_SNAKE_CASE )
if encoded_token_type_ids is not None:
output_data["token_type_ids"].append(_SCREAMING_SNAKE_CASE )
UpperCamelCase = {key: item for key, item in output_data.items() if len(_SCREAMING_SNAKE_CASE ) != 0}
return BatchEncoding(_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Any , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any]=None ):
"""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 _SCREAMING_SNAKE_CASE ( self : int , _SCREAMING_SNAKE_CASE : List[int] , _SCREAMING_SNAKE_CASE : Optional[List[int]] = None ):
"""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 _SCREAMING_SNAKE_CASE ( self : int , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[str] = None ):
"""simple docstring"""
UpperCamelCase = self._tokenizer.model.save(_SCREAMING_SNAKE_CASE , name=_SCREAMING_SNAKE_CASE )
return tuple(_SCREAMING_SNAKE_CASE )
| 410 | 1 |
import qiskit
def __SCREAMING_SNAKE_CASE ( a__ : int = 2 ) -> Optional[int]:
__A : str = qubits
# Using Aer's simulator
__A : List[Any] = qiskit.Aer.get_backend("""aer_simulator""" )
# Creating a Quantum Circuit acting on the q register
__A : Tuple = qiskit.QuantumCircuit(a__ ,a__ )
# Adding a H gate on qubit 0 (now q0 in superposition)
circuit.h(0 )
for i in range(1 ,a__ ):
# Adding CX (CNOT) gate
circuit.cx(i - 1 ,a__ )
# Mapping the quantum measurement to the classical bits
circuit.measure(list(range(a__ ) ) ,list(range(a__ ) ) )
# Now measuring any one qubit would affect other qubits to collapse
# their super position and have same state as the measured one.
# Executing the circuit on the simulator
__A : Tuple = qiskit.execute(a__ ,a__ ,shots=1000 )
return job.result().get_counts(a__ )
if __name__ == "__main__":
print(f"""Total count for various states are: {quantum_entanglement(3)}""")
| 17 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
lowerCAmelCase : Optional[Any] = {
'configuration_falcon': ['FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FalconConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase : str = [
'FALCON_PRETRAINED_MODEL_ARCHIVE_LIST',
'FalconForCausalLM',
'FalconModel',
'FalconPreTrainedModel',
'FalconForSequenceClassification',
'FalconForTokenClassification',
'FalconForQuestionAnswering',
]
if TYPE_CHECKING:
from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_falcon import (
FALCON_PRETRAINED_MODEL_ARCHIVE_LIST,
FalconForCausalLM,
FalconForQuestionAnswering,
FalconForSequenceClassification,
FalconForTokenClassification,
FalconModel,
FalconPreTrainedModel,
)
else:
import sys
lowerCAmelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 3 | 0 |
from graphs.minimum_spanning_tree_kruskal import kruskal
def _A ( ):
a__ : Optional[Any] = 9
a__ : Dict = [
[0, 1, 4],
[0, 7, 8],
[1, 2, 8],
[7, 8, 7],
[7, 6, 1],
[2, 8, 2],
[8, 6, 6],
[2, 3, 7],
[2, 5, 4],
[6, 5, 2],
[3, 5, 14],
[3, 4, 9],
[5, 4, 10],
[1, 7, 11],
]
a__ : List[str] = kruskal(lowerCamelCase , lowerCamelCase )
a__ : str = [
[7, 6, 1],
[2, 8, 2],
[6, 5, 2],
[0, 1, 4],
[2, 5, 4],
[2, 3, 7],
[0, 7, 8],
[3, 4, 9],
]
assert sorted(lowerCamelCase ) == sorted(lowerCamelCase )
| 629 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
SCREAMING_SNAKE_CASE__ : Any = {"""configuration_sew""": ["""SEW_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SEWConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE__ : Union[str, Any] = [
"""SEW_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""SEWForCTC""",
"""SEWForSequenceClassification""",
"""SEWModel""",
"""SEWPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_sew import (
SEW_PRETRAINED_MODEL_ARCHIVE_LIST,
SEWForCTC,
SEWForSequenceClassification,
SEWModel,
SEWPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE__ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 629 | 1 |
_lowerCAmelCase : List[Any] = '''
# Installazione di Transformers
! pip install transformers datasets
# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e
# rimuovi la modalità commento al comando seguente.
# ! pip install git+https://github.com/huggingface/transformers.git
'''
_lowerCAmelCase : Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}]
_lowerCAmelCase : Any = {
'''{processor_class}''': '''FakeProcessorClass''',
'''{model_class}''': '''FakeModelClass''',
'''{object_class}''': '''FakeObjectClass''',
}
| 454 |
from math import sqrt
def __snake_case ( _lowerCAmelCase : int ) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(sqrt(_lowerCAmelCase ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def __snake_case ( _lowerCAmelCase : int = 10001 ) -> int:
A_ : Any = 0
A_ : Tuple = 1
while count != nth and number < 3:
number += 1
if is_prime(_lowerCAmelCase ):
count += 1
while count != nth:
number += 2
if is_prime(_lowerCAmelCase ):
count += 1
return number
if __name__ == "__main__":
print(F'''{solution() = }''')
| 454 | 1 |
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from diffusers import (
DDIMScheduler,
KandinskyVaaControlnetImgaImgPipeline,
KandinskyVaaPriorEmbaEmbPipeline,
UNetaDConditionModel,
VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
enable_full_determinism()
class UpperCAmelCase ( _A , unittest.TestCase ):
a: Optional[int] = KandinskyVaaControlnetImgaImgPipeline
a: Any = ["image_embeds", "negative_image_embeds", "image", "hint"]
a: Optional[Any] = ["image_embeds", "negative_image_embeds", "image", "hint"]
a: Any = [
"generator",
"height",
"width",
"strength",
"guidance_scale",
"num_inference_steps",
"return_dict",
"guidance_scale",
"num_images_per_prompt",
"output_type",
"return_dict",
]
a: int = False
@property
def _A ( self: List[Any] ):
return 32
@property
def _A ( self: Tuple ):
return 32
@property
def _A ( self: str ):
return self.time_input_dim
@property
def _A ( self: List[Any] ):
return self.time_input_dim * 4
@property
def _A ( self: Union[str, Any] ):
return 100
@property
def _A ( self: List[Any] ):
torch.manual_seed(0 )
_a = {
"in_channels": 8,
# Out channels is double in channels because predicts mean and variance
"out_channels": 8,
"addition_embed_type": "image_hint",
"down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
"up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
"mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
"block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
"layers_per_block": 1,
"encoder_hid_dim": self.text_embedder_hidden_size,
"encoder_hid_dim_type": "image_proj",
"cross_attention_dim": self.cross_attention_dim,
"attention_head_dim": 4,
"resnet_time_scale_shift": "scale_shift",
"class_embed_type": None,
}
_a = UNetaDConditionModel(**__UpperCamelCase )
return model
@property
def _A ( self: Optional[int] ):
return {
"block_out_channels": [32, 32, 64, 64],
"down_block_types": [
"DownEncoderBlock2D",
"DownEncoderBlock2D",
"DownEncoderBlock2D",
"AttnDownEncoderBlock2D",
],
"in_channels": 3,
"latent_channels": 4,
"layers_per_block": 1,
"norm_num_groups": 8,
"norm_type": "spatial",
"num_vq_embeddings": 12,
"out_channels": 3,
"up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
"vq_embed_dim": 4,
}
@property
def _A ( self: str ):
torch.manual_seed(0 )
_a = VQModel(**self.dummy_movq_kwargs )
return model
def _A ( self: List[Any] ):
_a = self.dummy_unet
_a = self.dummy_movq
_a = {
"num_train_timesteps": 1000,
"beta_schedule": "linear",
"beta_start": 0.0_0_0_8_5,
"beta_end": 0.0_1_2,
"clip_sample": False,
"set_alpha_to_one": False,
"steps_offset": 0,
"prediction_type": "epsilon",
"thresholding": False,
}
_a = DDIMScheduler(**__UpperCamelCase )
_a = {
"unet": unet,
"scheduler": scheduler,
"movq": movq,
}
return components
def _A ( self: Dict , __UpperCamelCase: Optional[int] , __UpperCamelCase: Optional[int]=0 ):
_a = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__UpperCamelCase ) ).to(__UpperCamelCase )
_a = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to(
__UpperCamelCase )
# create init_image
_a = floats_tensor((1, 3, 64, 64) , rng=random.Random(__UpperCamelCase ) ).to(__UpperCamelCase )
_a = image.cpu().permute(0 , 2 , 3 , 1 )[0]
_a = Image.fromarray(np.uinta(__UpperCamelCase ) ).convert('''RGB''' ).resize((256, 256) )
# create hint
_a = floats_tensor((1, 3, 64, 64) , rng=random.Random(__UpperCamelCase ) ).to(__UpperCamelCase )
if str(__UpperCamelCase ).startswith('''mps''' ):
_a = torch.manual_seed(__UpperCamelCase )
else:
_a = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase )
_a = {
"image": init_image,
"image_embeds": image_embeds,
"negative_image_embeds": negative_image_embeds,
"hint": hint,
"generator": generator,
"height": 64,
"width": 64,
"num_inference_steps": 10,
"guidance_scale": 7.0,
"strength": 0.2,
"output_type": "np",
}
return inputs
def _A ( self: Optional[Any] ):
_a = "cpu"
_a = self.get_dummy_components()
_a = self.pipeline_class(**__UpperCamelCase )
_a = pipe.to(__UpperCamelCase )
pipe.set_progress_bar_config(disable=__UpperCamelCase )
_a = pipe(**self.get_dummy_inputs(__UpperCamelCase ) )
_a = output.images
_a = pipe(
**self.get_dummy_inputs(__UpperCamelCase ) , return_dict=__UpperCamelCase , )[0]
_a = image[0, -3:, -3:, -1]
_a = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
_a = np.array(
[0.5_4_9_8_5_0_3_4, 0.5_5_5_0_9_3_6_5, 0.5_2_5_6_1_5_0_4, 0.5_5_7_0_4_9_4, 0.5_5_9_3_8_1_8, 0.5_2_6_3_9_7_9, 0.5_0_2_8_5_6_4_3, 0.5_0_6_9_8_4_6, 0.5_1_1_9_6_7_3_6] )
assert (
np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
), f" expected_slice {expected_slice}, but got {image_slice.flatten()}"
assert (
np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"
@slow
@require_torch_gpu
class UpperCAmelCase ( unittest.TestCase ):
def _A ( self: Dict ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _A ( self: Tuple ):
_a = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy''' )
_a = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' )
_a = init_image.resize((512, 512) )
_a = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/kandinskyv22/hint_image_cat.png''' )
_a = torch.from_numpy(np.array(__UpperCamelCase ) ).float() / 2_5_5.0
_a = hint.permute(2 , 0 , 1 ).unsqueeze(0 )
_a = "A robot, 4k photo"
_a = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained(
'''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa )
pipe_prior.to(__UpperCamelCase )
_a = KandinskyVaaControlnetImgaImgPipeline.from_pretrained(
'''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa )
_a = pipeline.to(__UpperCamelCase )
pipeline.set_progress_bar_config(disable=__UpperCamelCase )
_a = torch.Generator(device='''cpu''' ).manual_seed(0 )
_a = pipe_prior(
__UpperCamelCase , image=__UpperCamelCase , strength=0.8_5 , generator=__UpperCamelCase , negative_prompt='''''' , ).to_tuple()
_a = pipeline(
image=__UpperCamelCase , image_embeds=__UpperCamelCase , negative_image_embeds=__UpperCamelCase , hint=__UpperCamelCase , generator=__UpperCamelCase , num_inference_steps=100 , height=512 , width=512 , strength=0.5 , output_type='''np''' , )
_a = output.images[0]
assert image.shape == (512, 512, 3)
assert_mean_pixel_difference(__UpperCamelCase , __UpperCamelCase )
| 713 |
def __snake_case ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> bool:
return not any(
neighbour == 1 and colored_vertices[i] == color
for i, neighbour in enumerate(_UpperCamelCase ) )
def __snake_case ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> bool:
# Base Case
if index == len(_UpperCamelCase ):
return True
# Recursive Step
for i in range(_UpperCamelCase ):
if valid_coloring(graph[index] , _UpperCamelCase , _UpperCamelCase ):
# Color current vertex
_a = i
# Validate coloring
if util_color(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , index + 1 ):
return True
# Backtrack
_a = -1
return False
def __snake_case ( _UpperCamelCase , _UpperCamelCase ) -> list[int]:
_a = [-1] * len(_UpperCamelCase )
if util_color(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , 0 ):
return colored_vertices
return []
| 346 | 0 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_ = {
'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json',
'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json',
'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json',
'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json',
'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json',
'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json',
}
class a ( __lowerCAmelCase ):
"""simple docstring"""
__lowerCAmelCase = """roberta"""
def __init__( self , snake_case_=5_0265 , snake_case_=768 , snake_case_=12 , snake_case_=12 , snake_case_=3072 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=2 , snake_case_=0.0_2 , snake_case_=1e-1_2 , snake_case_=1 , snake_case_=0 , snake_case_=2 , snake_case_="absolute" , snake_case_=True , snake_case_=None , **snake_case_ , ):
'''simple docstring'''
super().__init__(pad_token_id=snake_case_ , bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ )
__UpperCAmelCase: Tuple = vocab_size
__UpperCAmelCase: Optional[int] = hidden_size
__UpperCAmelCase: Optional[int] = num_hidden_layers
__UpperCAmelCase: Dict = num_attention_heads
__UpperCAmelCase: Tuple = hidden_act
__UpperCAmelCase: Any = intermediate_size
__UpperCAmelCase: Optional[Any] = hidden_dropout_prob
__UpperCAmelCase: Optional[int] = attention_probs_dropout_prob
__UpperCAmelCase: Optional[int] = max_position_embeddings
__UpperCAmelCase: List[str] = type_vocab_size
__UpperCAmelCase: List[str] = initializer_range
__UpperCAmelCase: str = layer_norm_eps
__UpperCAmelCase: Union[str, Any] = position_embedding_type
__UpperCAmelCase: Tuple = use_cache
__UpperCAmelCase: Any = classifier_dropout
class a ( __lowerCAmelCase ):
"""simple docstring"""
@property
def lowercase_ ( self ):
'''simple docstring'''
if self.task == "multiple-choice":
__UpperCAmelCase: Tuple = {0: """batch""", 1: """choice""", 2: """sequence"""}
else:
__UpperCAmelCase: Union[str, Any] = {0: """batch""", 1: """sequence"""}
return OrderedDict(
[
("""input_ids""", dynamic_axis),
("""attention_mask""", dynamic_axis),
] ) | 523 | '''simple docstring'''
class a :
"""simple docstring"""
def __init__( self , snake_case_ , snake_case_ , snake_case_ ):
'''simple docstring'''
__UpperCAmelCase: List[Any] = None
__UpperCAmelCase: Tuple = None
__UpperCAmelCase: List[Any] = graph
self._normalize_graph(snake_case_ , snake_case_ )
__UpperCAmelCase: Union[str, Any] = len(snake_case_ )
__UpperCAmelCase: List[str] = None
def lowercase_ ( self , snake_case_ , snake_case_ ):
'''simple docstring'''
if sources is int:
__UpperCAmelCase: List[Any] = [sources]
if sinks is int:
__UpperCAmelCase: Optional[Any] = [sinks]
if len(snake_case_ ) == 0 or len(snake_case_ ) == 0:
return
__UpperCAmelCase: Any = sources[0]
__UpperCAmelCase: int = sinks[0]
# make fake vertex if there are more
# than one source or sink
if len(snake_case_ ) > 1 or len(snake_case_ ) > 1:
__UpperCAmelCase: Union[str, Any] = 0
for i in sources:
max_input_flow += sum(self.graph[i] )
__UpperCAmelCase: List[Any] = len(self.graph ) + 1
for room in self.graph:
room.insert(0 , 0 )
self.graph.insert(0 , [0] * size )
for i in sources:
__UpperCAmelCase: Tuple = max_input_flow
__UpperCAmelCase: Any = 0
__UpperCAmelCase: Tuple = len(self.graph ) + 1
for room in self.graph:
room.append(0 )
self.graph.append([0] * size )
for i in sinks:
__UpperCAmelCase: Tuple = max_input_flow
__UpperCAmelCase: Tuple = size - 1
def lowercase_ ( self ):
'''simple docstring'''
if self.maximum_flow_algorithm is None:
raise Exception("""You need to set maximum flow algorithm before.""" )
if self.source_index is None or self.sink_index is None:
return 0
self.maximum_flow_algorithm.execute()
return self.maximum_flow_algorithm.getMaximumFlow()
def lowercase_ ( self , snake_case_ ):
'''simple docstring'''
__UpperCAmelCase: Optional[Any] = algorithm(self )
class a :
"""simple docstring"""
def __init__( self , snake_case_ ):
'''simple docstring'''
__UpperCAmelCase: Tuple = flow_network
__UpperCAmelCase: Dict = flow_network.verticesCount
__UpperCAmelCase: List[Any] = flow_network.sourceIndex
__UpperCAmelCase: int = flow_network.sinkIndex
# it's just a reference, so you shouldn't change
# it in your algorithms, use deep copy before doing that
__UpperCAmelCase: Dict = flow_network.graph
__UpperCAmelCase: Optional[int] = False
def lowercase_ ( self ):
'''simple docstring'''
if not self.executed:
self._algorithm()
__UpperCAmelCase: str = True
def lowercase_ ( self ):
'''simple docstring'''
pass
class a ( __lowerCAmelCase ):
"""simple docstring"""
def __init__( self , snake_case_ ):
'''simple docstring'''
super().__init__(snake_case_ )
# use this to save your result
__UpperCAmelCase: int = -1
def lowercase_ ( self ):
'''simple docstring'''
if not self.executed:
raise Exception("""You should execute algorithm before using its result!""" )
return self.maximum_flow
class a ( __lowerCAmelCase ):
"""simple docstring"""
def __init__( self , snake_case_ ):
'''simple docstring'''
super().__init__(snake_case_ )
__UpperCAmelCase: Optional[int] = [[0] * self.verticies_count for i in range(self.verticies_count )]
__UpperCAmelCase: Union[str, Any] = [0] * self.verticies_count
__UpperCAmelCase: Tuple = [0] * self.verticies_count
def lowercase_ ( self ):
'''simple docstring'''
__UpperCAmelCase: Dict = self.verticies_count
# push some substance to graph
for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ):
self.preflow[self.source_index][nextvertex_index] += bandwidth
self.preflow[nextvertex_index][self.source_index] -= bandwidth
self.excesses[nextvertex_index] += bandwidth
# Relabel-to-front selection rule
__UpperCAmelCase: int = [
i
for i in range(self.verticies_count )
if i != self.source_index and i != self.sink_index
]
# move through list
__UpperCAmelCase: List[Any] = 0
while i < len(snake_case_ ):
__UpperCAmelCase: Optional[int] = vertices_list[i]
__UpperCAmelCase: Optional[int] = self.heights[vertex_index]
self.process_vertex(snake_case_ )
if self.heights[vertex_index] > previous_height:
# if it was relabeled, swap elements
# and start from 0 index
vertices_list.insert(0 , vertices_list.pop(snake_case_ ) )
__UpperCAmelCase: Union[str, Any] = 0
else:
i += 1
__UpperCAmelCase: Tuple = sum(self.preflow[self.source_index] )
def lowercase_ ( self , snake_case_ ):
'''simple docstring'''
while self.excesses[vertex_index] > 0:
for neighbour_index in range(self.verticies_count ):
# if it's neighbour and current vertex is higher
if (
self.graph[vertex_index][neighbour_index]
- self.preflow[vertex_index][neighbour_index]
> 0
and self.heights[vertex_index] > self.heights[neighbour_index]
):
self.push(snake_case_ , snake_case_ )
self.relabel(snake_case_ )
def lowercase_ ( self , snake_case_ , snake_case_ ):
'''simple docstring'''
__UpperCAmelCase: Union[str, Any] = min(
self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , )
self.preflow[from_index][to_index] += preflow_delta
self.preflow[to_index][from_index] -= preflow_delta
self.excesses[from_index] -= preflow_delta
self.excesses[to_index] += preflow_delta
def lowercase_ ( self , snake_case_ ):
'''simple docstring'''
__UpperCAmelCase: Optional[Any] = None
for to_index in range(self.verticies_count ):
if (
self.graph[vertex_index][to_index]
- self.preflow[vertex_index][to_index]
> 0
) and (min_height is None or self.heights[to_index] < min_height):
__UpperCAmelCase: str = self.heights[to_index]
if min_height is not None:
__UpperCAmelCase: Optional[Any] = min_height + 1
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_ = [0]
SCREAMING_SNAKE_CASE_ = [3]
# graph = [
# [0, 0, 4, 6, 0, 0],
# [0, 0, 5, 2, 0, 0],
# [0, 0, 0, 0, 4, 4],
# [0, 0, 0, 0, 6, 6],
# [0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0],
# ]
SCREAMING_SNAKE_CASE_ = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]]
# prepare our network
SCREAMING_SNAKE_CASE_ = FlowNetwork(graph, entrances, exits)
# set algorithm
flow_network.set_maximum_flow_algorithm(PushRelabelExecutor)
# and calculate
SCREAMING_SNAKE_CASE_ = flow_network.find_maximum_flow()
print(F"""maximum flow is {maximum_flow}""") | 523 | 1 |
import copy
import unittest
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
MODEL_FOR_QUESTION_ANSWERING_MAPPING,
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
LayoutLMvaConfig,
LayoutLMvaForQuestionAnswering,
LayoutLMvaForSequenceClassification,
LayoutLMvaForTokenClassification,
LayoutLMvaModel,
)
from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import LayoutLMvaImageProcessor
class lowercase :
def __init__( self ,A__ ,A__=2 ,A__=3 ,A__=4 ,A__=2 ,A__=7 ,A__=True ,A__=True ,A__=True ,A__=True ,A__=9_9 ,A__=3_6 ,A__=3 ,A__=4 ,A__=3_7 ,A__="gelu" ,A__=0.1 ,A__=0.1 ,A__=5_1_2 ,A__=1_6 ,A__=2 ,A__=0.02 ,A__=6 ,A__=6 ,A__=3 ,A__=4 ,A__=None ,A__=1_0_0_0 ,):
lowercase = parent
lowercase = batch_size
lowercase = num_channels
lowercase = image_size
lowercase = patch_size
lowercase = text_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 = coordinate_size
lowercase = shape_size
lowercase = num_labels
lowercase = num_choices
lowercase = scope
lowercase = range_bbox
# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
lowercase = text_seq_length
lowercase = (image_size // patch_size) ** 2 + 1
lowercase = self.text_seq_length + self.image_seq_length
def A__ ( self):
lowercase = ids_tensor([self.batch_size, self.text_seq_length] ,self.vocab_size)
lowercase = ids_tensor([self.batch_size, self.text_seq_length, 4] ,self.range_bbox)
# Ensure that bbox is legal
for i in range(bbox.shape[0]):
for j in range(bbox.shape[1]):
if bbox[i, j, 3] < bbox[i, j, 1]:
lowercase = bbox[i, j, 3]
lowercase = bbox[i, j, 1]
lowercase = t
if bbox[i, j, 2] < bbox[i, j, 0]:
lowercase = bbox[i, j, 2]
lowercase = bbox[i, j, 0]
lowercase = t
lowercase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
lowercase = None
if self.use_input_mask:
lowercase = random_attention_mask([self.batch_size, self.text_seq_length])
lowercase = None
if self.use_token_type_ids:
lowercase = ids_tensor([self.batch_size, self.text_seq_length] ,self.type_vocab_size)
lowercase = None
lowercase = None
if self.use_labels:
lowercase = ids_tensor([self.batch_size] ,self.type_sequence_label_size)
lowercase = ids_tensor([self.batch_size, self.text_seq_length] ,self.num_labels)
lowercase = LayoutLMvaConfig(
vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,initializer_range=self.initializer_range ,coordinate_size=self.coordinate_size ,shape_size=self.shape_size ,input_size=self.image_size ,patch_size=self.patch_size ,)
return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels
def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__):
lowercase = LayoutLMvaModel(config=A__)
model.to(A__)
model.eval()
# text + image
lowercase = model(A__ ,pixel_values=A__)
lowercase = model(
A__ ,bbox=A__ ,pixel_values=A__ ,attention_mask=A__ ,token_type_ids=A__)
lowercase = model(A__ ,bbox=A__ ,pixel_values=A__ ,token_type_ids=A__)
lowercase = model(A__ ,bbox=A__ ,pixel_values=A__)
self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size))
# text only
lowercase = model(A__)
self.parent.assertEqual(
result.last_hidden_state.shape ,(self.batch_size, self.text_seq_length, self.hidden_size))
# image only
lowercase = model(pixel_values=A__)
self.parent.assertEqual(
result.last_hidden_state.shape ,(self.batch_size, self.image_seq_length, self.hidden_size))
def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__):
lowercase = self.num_labels
lowercase = LayoutLMvaForSequenceClassification(A__)
model.to(A__)
model.eval()
lowercase = model(
A__ ,bbox=A__ ,pixel_values=A__ ,attention_mask=A__ ,token_type_ids=A__ ,labels=A__ ,)
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels))
def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__):
lowercase = self.num_labels
lowercase = LayoutLMvaForTokenClassification(config=A__)
model.to(A__)
model.eval()
lowercase = model(
A__ ,bbox=A__ ,pixel_values=A__ ,attention_mask=A__ ,token_type_ids=A__ ,labels=A__ ,)
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.text_seq_length, self.num_labels))
def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,A__):
lowercase = LayoutLMvaForQuestionAnswering(config=A__)
model.to(A__)
model.eval()
lowercase = model(
A__ ,bbox=A__ ,pixel_values=A__ ,attention_mask=A__ ,token_type_ids=A__ ,start_positions=A__ ,end_positions=A__ ,)
self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length))
def A__ ( self):
lowercase = self.prepare_config_and_inputs()
(
(
lowercase
) , (
lowercase
) , (
lowercase
) , (
lowercase
) , (
lowercase
) , (
lowercase
) , (
lowercase
) , (
lowercase
) ,
) = config_and_inputs
lowercase = {
'''input_ids''': input_ids,
'''bbox''': bbox,
'''pixel_values''': pixel_values,
'''token_type_ids''': token_type_ids,
'''attention_mask''': input_mask,
}
return config, inputs_dict
@require_torch
class lowercase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ):
lowercase_ : List[str] =False
lowercase_ : int =False
lowercase_ : Union[str, Any] =False
lowercase_ : Optional[Any] =(
(
LayoutLMvaModel,
LayoutLMvaForSequenceClassification,
LayoutLMvaForTokenClassification,
LayoutLMvaForQuestionAnswering,
)
if is_torch_available()
else ()
)
lowercase_ : Union[str, Any] =(
{'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel}
if is_torch_available()
else {}
)
def A__ ( self ,A__ ,A__ ,A__ ,A__ ,A__):
# `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual
# embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has
# the sequence dimension of the text embedding only.
# (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`)
return True
def A__ ( self):
lowercase = LayoutLMvaModelTester(self)
lowercase = ConfigTester(self ,config_class=A__ ,hidden_size=3_7)
def A__ ( self ,A__ ,A__ ,A__=False):
lowercase = copy.deepcopy(A__)
if model_class in get_values(A__):
lowercase = {
k: v.unsqueeze(1).expand(-1 ,self.model_tester.num_choices ,-1).contiguous()
if isinstance(A__ ,torch.Tensor) and v.ndim > 1
else v
for k, v in inputs_dict.items()
}
if return_labels:
if model_class in get_values(A__):
lowercase = torch.ones(self.model_tester.batch_size ,dtype=torch.long ,device=A__)
elif model_class in get_values(A__):
lowercase = torch.zeros(
self.model_tester.batch_size ,dtype=torch.long ,device=A__)
lowercase = torch.zeros(
self.model_tester.batch_size ,dtype=torch.long ,device=A__)
elif model_class in [
*get_values(A__),
]:
lowercase = torch.zeros(
self.model_tester.batch_size ,dtype=torch.long ,device=A__)
elif model_class in [
*get_values(A__),
]:
lowercase = torch.zeros(
(self.model_tester.batch_size, self.model_tester.text_seq_length) ,dtype=torch.long ,device=A__ ,)
return inputs_dict
def A__ ( self):
self.config_tester.run_common_tests()
def A__ ( self):
lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*A__)
def A__ ( self):
lowercase = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
lowercase = type
self.model_tester.create_and_check_model(*A__)
def A__ ( self):
lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*A__)
def A__ ( self):
lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*A__)
def A__ ( self):
lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*A__)
@slow
def A__ ( self):
for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase = LayoutLMvaModel.from_pretrained(A__)
self.assertIsNotNone(A__)
def UpperCamelCase ( ):
'''simple docstring'''
lowercase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
class lowercase ( unittest.TestCase ):
@cached_property
def A__ ( self):
return LayoutLMvaImageProcessor(apply_ocr=A__) if is_vision_available() else None
@slow
def A__ ( self):
lowercase = LayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base''').to(A__)
lowercase = self.default_image_processor
lowercase = prepare_img()
lowercase = image_processor(images=A__ ,return_tensors='''pt''').pixel_values.to(A__)
lowercase = torch.tensor([[1, 2]])
lowercase = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]).unsqueeze(0)
# forward pass
lowercase = model(
input_ids=input_ids.to(A__) ,bbox=bbox.to(A__) ,pixel_values=pixel_values.to(A__) ,)
# verify the logits
lowercase = torch.Size((1, 1_9_9, 7_6_8))
self.assertEqual(outputs.last_hidden_state.shape ,A__)
lowercase = torch.tensor(
[[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]).to(A__)
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] ,A__ ,atol=1E-4))
| 633 |
import logging
from transformers import PretrainedConfig
lowercase__ :int = logging.getLogger(__name__)
lowercase__ :Dict = {
"bertabs-finetuned-cnndm": "https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json",
}
class lowercase ( SCREAMING_SNAKE_CASE__ ):
lowercase_ : Optional[int] ='''bertabs'''
def __init__( self ,A__=3_0_5_2_2 ,A__=5_1_2 ,A__=6 ,A__=5_1_2 ,A__=8 ,A__=5_1_2 ,A__=0.2 ,A__=6 ,A__=7_6_8 ,A__=8 ,A__=2_0_4_8 ,A__=0.2 ,**A__ ,):
super().__init__(**A__)
lowercase = vocab_size
lowercase = max_pos
lowercase = enc_layers
lowercase = enc_hidden_size
lowercase = enc_heads
lowercase = enc_ff_size
lowercase = enc_dropout
lowercase = dec_layers
lowercase = dec_hidden_size
lowercase = dec_heads
lowercase = dec_ff_size
lowercase = dec_dropout
| 633 | 1 |
"""simple docstring"""
import copy
import os
import cva
import numpy as np
from matplotlib import pyplot as plt
class a :
def __init__( self : Optional[int] ) -> str:
lowerCamelCase_ = ''
lowerCamelCase_ = ''
lowerCamelCase_ = []
lowerCamelCase_ = 0
lowerCamelCase_ = 256
lowerCamelCase_ = 0
lowerCamelCase_ = 0
lowerCamelCase_ = 0
lowerCamelCase_ = 0
def UpperCamelCase ( self : int , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Tuple:
lowerCamelCase_ = cva.imread(__SCREAMING_SNAKE_CASE , 0 )
lowerCamelCase_ = copy.deepcopy(self.img )
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = plt.hist(self.img.ravel() , 256 , [0, 256] , label='x' )
lowerCamelCase_ = np.sum(__SCREAMING_SNAKE_CASE )
for i in range(len(__SCREAMING_SNAKE_CASE ) ):
lowerCamelCase_ = x[i] / self.k
self.sk += prk
lowerCamelCase_ = (self.L - 1) * self.sk
if self.rem != 0:
lowerCamelCase_ = int(last % last )
lowerCamelCase_ = int(last + 1 if self.rem >= 0.5 else last )
self.last_list.append(__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = int(np.ma.count(self.img ) / self.img[1].size )
lowerCamelCase_ = self.img[1].size
for i in range(self.number_of_cols ):
for j in range(self.number_of_rows ):
lowerCamelCase_ = self.img[j][i]
if num != self.last_list[num]:
lowerCamelCase_ = self.last_list[num]
cva.imwrite('output_data/output.jpg' , self.img )
def UpperCamelCase ( self : Tuple ) -> str:
plt.hist(self.img.ravel() , 256 , [0, 256] )
def UpperCamelCase ( self : str ) -> str:
cva.imshow('Output-Image' , self.img )
cva.imshow('Input-Image' , self.original_image )
cva.waitKey(5000 )
cva.destroyAllWindows()
if __name__ == "__main__":
_SCREAMING_SNAKE_CASE : Tuple = os.path.join(os.path.basename(__file__), '''image_data/input.jpg''')
_SCREAMING_SNAKE_CASE : Any = ConstantStretch()
stretcher.stretch(file_path)
stretcher.plot_histogram()
stretcher.show_image()
| 549 |
"""simple docstring"""
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
# Importing the dataset
_SCREAMING_SNAKE_CASE : int = pd.read_csv(
'''https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/'''
'''position_salaries.csv'''
)
_SCREAMING_SNAKE_CASE : List[Any] = dataset.iloc[:, 1:2].values
_SCREAMING_SNAKE_CASE : str = dataset.iloc[:, 2].values
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = train_test_split(X, y, test_size=0.2, random_state=0)
_SCREAMING_SNAKE_CASE : Optional[int] = PolynomialFeatures(degree=4)
_SCREAMING_SNAKE_CASE : Union[str, Any] = poly_reg.fit_transform(X)
_SCREAMING_SNAKE_CASE : List[str] = LinearRegression()
pol_reg.fit(X_poly, y)
def lowerCamelCase__ ( ) -> List[str]:
plt.scatter(_lowerCamelCase , _lowerCamelCase , color='red' )
plt.plot(_lowerCamelCase , pol_reg.predict(poly_reg.fit_transform(_lowerCamelCase ) ) , color='blue' )
plt.title('Truth or Bluff (Linear Regression)' )
plt.xlabel('Position level' )
plt.ylabel('Salary' )
plt.show()
if __name__ == "__main__":
viz_polymonial()
# Predicting a new result with Polymonial Regression
pol_reg.predict(poly_reg.fit_transform([[5.5]]))
# output should be 132148.43750003
| 549 | 1 |
"""simple docstring"""
from dataclasses import dataclass
from typing import Optional
import torch
from torch import nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .modeling_utils import ModelMixin
@dataclass
class UpperCamelCase ( snake_case ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : torch.FloatTensor
class UpperCamelCase ( snake_case , snake_case ):
"""simple docstring"""
@register_to_config
def __init__( self ,UpperCAmelCase_ = 16 ,UpperCAmelCase_ = 88 ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,UpperCAmelCase_ = 1 ,UpperCAmelCase_ = 0.0 ,UpperCAmelCase_ = 32 ,UpperCAmelCase_ = None ,UpperCAmelCase_ = False ,UpperCAmelCase_ = None ,UpperCAmelCase_ = "geglu" ,UpperCAmelCase_ = True ,UpperCAmelCase_ = True ,):
super().__init__()
_lowercase : Optional[Any] = num_attention_heads
_lowercase : Tuple = attention_head_dim
_lowercase : List[str] = num_attention_heads * attention_head_dim
_lowercase : int = in_channels
_lowercase : Optional[int] = torch.nn.GroupNorm(num_groups=UpperCAmelCase_ ,num_channels=UpperCAmelCase_ ,eps=1E-6 ,affine=UpperCAmelCase_ )
_lowercase : Dict = nn.Linear(UpperCAmelCase_ ,UpperCAmelCase_ )
# 3. Define transformers blocks
_lowercase : List[str] = nn.ModuleList(
[
BasicTransformerBlock(
UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,dropout=UpperCAmelCase_ ,cross_attention_dim=UpperCAmelCase_ ,activation_fn=UpperCAmelCase_ ,attention_bias=UpperCAmelCase_ ,double_self_attention=UpperCAmelCase_ ,norm_elementwise_affine=UpperCAmelCase_ ,)
for d in range(UpperCAmelCase_ )
] )
_lowercase : Union[str, Any] = nn.Linear(UpperCAmelCase_ ,UpperCAmelCase_ )
def lowerCamelCase__ ( self ,UpperCAmelCase_ ,UpperCAmelCase_=None ,UpperCAmelCase_=None ,UpperCAmelCase_=None ,UpperCAmelCase_=1 ,UpperCAmelCase_=None ,UpperCAmelCase_ = True ,):
_lowercase , _lowercase , _lowercase , _lowercase : Dict = hidden_states.shape
_lowercase : Optional[int] = batch_frames // num_frames
_lowercase : Dict = hidden_states
_lowercase : List[str] = hidden_states[None, :].reshape(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ )
_lowercase : int = hidden_states.permute(0 ,2 ,1 ,3 ,4 )
_lowercase : Union[str, Any] = self.norm(UpperCAmelCase_ )
_lowercase : Any = hidden_states.permute(0 ,3 ,4 ,2 ,1 ).reshape(batch_size * height * width ,UpperCAmelCase_ ,UpperCAmelCase_ )
_lowercase : Optional[Any] = self.proj_in(UpperCAmelCase_ )
# 2. Blocks
for block in self.transformer_blocks:
_lowercase : Optional[int] = block(
UpperCAmelCase_ ,encoder_hidden_states=UpperCAmelCase_ ,timestep=UpperCAmelCase_ ,cross_attention_kwargs=UpperCAmelCase_ ,class_labels=UpperCAmelCase_ ,)
# 3. Output
_lowercase : Optional[Any] = self.proj_out(UpperCAmelCase_ )
_lowercase : Optional[int] = (
hidden_states[None, None, :]
.reshape(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ )
.permute(0 ,3 ,4 ,1 ,2 )
.contiguous()
)
_lowercase : int = hidden_states.reshape(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ )
_lowercase : Optional[int] = hidden_states + residual
if not return_dict:
return (output,)
return TransformerTemporalModelOutput(sample=UpperCAmelCase_ )
| 600 |
"""simple docstring"""
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCAmelCase: str = logging.get_logger(__name__)
UpperCAmelCase: Optional[Any] = {
"""facebook/wav2vec2-base-960h""": """https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json""",
# See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2
}
class UpperCamelCase ( snake_case ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = "wav2vec2"
def __init__( self ,UpperCAmelCase_=32 ,UpperCAmelCase_=7_68 ,UpperCAmelCase_=12 ,UpperCAmelCase_=12 ,UpperCAmelCase_=30_72 ,UpperCAmelCase_="gelu" ,UpperCAmelCase_=0.1 ,UpperCAmelCase_=0.1 ,UpperCAmelCase_=0.1 ,UpperCAmelCase_=0.0 ,UpperCAmelCase_=0.0 ,UpperCAmelCase_=0.1 ,UpperCAmelCase_=0.1 ,UpperCAmelCase_=0.02 ,UpperCAmelCase_=1E-5 ,UpperCAmelCase_="group" ,UpperCAmelCase_="gelu" ,UpperCAmelCase_=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) ,UpperCAmelCase_=(5, 2, 2, 2, 2, 2, 2) ,UpperCAmelCase_=(10, 3, 3, 3, 3, 2, 2) ,UpperCAmelCase_=False ,UpperCAmelCase_=1_28 ,UpperCAmelCase_=16 ,UpperCAmelCase_=False ,UpperCAmelCase_=True ,UpperCAmelCase_=0.05 ,UpperCAmelCase_=10 ,UpperCAmelCase_=2 ,UpperCAmelCase_=0.0 ,UpperCAmelCase_=10 ,UpperCAmelCase_=0 ,UpperCAmelCase_=3_20 ,UpperCAmelCase_=2 ,UpperCAmelCase_=0.1 ,UpperCAmelCase_=1_00 ,UpperCAmelCase_=2_56 ,UpperCAmelCase_=2_56 ,UpperCAmelCase_=0.1 ,UpperCAmelCase_="sum" ,UpperCAmelCase_=False ,UpperCAmelCase_=False ,UpperCAmelCase_=2_56 ,UpperCAmelCase_=(5_12, 5_12, 5_12, 5_12, 15_00) ,UpperCAmelCase_=(5, 3, 3, 1, 1) ,UpperCAmelCase_=(1, 2, 3, 1, 1) ,UpperCAmelCase_=5_12 ,UpperCAmelCase_=0 ,UpperCAmelCase_=1 ,UpperCAmelCase_=2 ,UpperCAmelCase_=False ,UpperCAmelCase_=3 ,UpperCAmelCase_=2 ,UpperCAmelCase_=3 ,UpperCAmelCase_=None ,UpperCAmelCase_=None ,**UpperCAmelCase_ ,):
super().__init__(**UpperCAmelCase_ ,pad_token_id=UpperCAmelCase_ ,bos_token_id=UpperCAmelCase_ ,eos_token_id=UpperCAmelCase_ )
_lowercase : List[Any] = hidden_size
_lowercase : Any = feat_extract_norm
_lowercase : Tuple = feat_extract_activation
_lowercase : Tuple = list(UpperCAmelCase_ )
_lowercase : List[str] = list(UpperCAmelCase_ )
_lowercase : List[Any] = list(UpperCAmelCase_ )
_lowercase : List[Any] = conv_bias
_lowercase : Optional[Any] = num_conv_pos_embeddings
_lowercase : Dict = num_conv_pos_embedding_groups
_lowercase : List[Any] = len(self.conv_dim )
_lowercase : str = num_hidden_layers
_lowercase : Any = intermediate_size
_lowercase : int = hidden_act
_lowercase : int = num_attention_heads
_lowercase : Union[str, Any] = hidden_dropout
_lowercase : Dict = attention_dropout
_lowercase : Tuple = activation_dropout
_lowercase : str = feat_proj_dropout
_lowercase : List[str] = final_dropout
_lowercase : Tuple = layerdrop
_lowercase : List[str] = layer_norm_eps
_lowercase : Any = initializer_range
_lowercase : Any = vocab_size
_lowercase : Optional[Any] = do_stable_layer_norm
_lowercase : Union[str, Any] = use_weighted_layer_sum
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
"""Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
""" `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
f""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,"""
f""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
_lowercase : Union[str, Any] = apply_spec_augment
_lowercase : Optional[Any] = mask_time_prob
_lowercase : Optional[int] = mask_time_length
_lowercase : Dict = mask_time_min_masks
_lowercase : Optional[int] = mask_feature_prob
_lowercase : Tuple = mask_feature_length
_lowercase : Optional[Any] = mask_feature_min_masks
# parameters for pretraining with codevector quantized representations
_lowercase : str = num_codevectors_per_group
_lowercase : Union[str, Any] = num_codevector_groups
_lowercase : Optional[Any] = contrastive_logits_temperature
_lowercase : Tuple = feat_quantizer_dropout
_lowercase : Optional[int] = num_negatives
_lowercase : str = codevector_dim
_lowercase : Optional[int] = proj_codevector_dim
_lowercase : int = diversity_loss_weight
# ctc loss
_lowercase : Optional[int] = ctc_loss_reduction
_lowercase : str = ctc_zero_infinity
# adapter
_lowercase : str = add_adapter
_lowercase : List[str] = adapter_kernel_size
_lowercase : Any = adapter_stride
_lowercase : List[Any] = num_adapter_layers
_lowercase : Optional[Any] = output_hidden_size or hidden_size
_lowercase : str = adapter_attn_dim
# SequenceClassification-specific parameter. Feel free to ignore for other classes.
_lowercase : int = classifier_proj_size
# XVector-specific parameters. Feel free to ignore for other classes.
_lowercase : List[str] = list(UpperCAmelCase_ )
_lowercase : List[Any] = list(UpperCAmelCase_ )
_lowercase : Tuple = list(UpperCAmelCase_ )
_lowercase : List[Any] = xvector_output_dim
@property
def lowerCamelCase__ ( self ):
return functools.reduce(operator.mul ,self.conv_stride ,1 )
| 600 | 1 |
"""simple docstring"""
from __future__ import annotations
def lowercase ( lowerCAmelCase__ ):
lowerCamelCase_ = str(lowerCAmelCase__ )
return n == n[::-1]
def lowercase ( lowerCAmelCase__ = 1_000_000 ):
lowerCamelCase_ = 0
for i in range(1 ,lowerCAmelCase__ ):
if is_palindrome(lowerCAmelCase__ ) and is_palindrome(bin(lowerCAmelCase__ ).split('''b''' )[1] ):
total += i
return total
if __name__ == "__main__":
print(solution(int(str(input().strip()))))
| 29 |
import tempfile
import torch
from diffusers import (
DEISMultistepScheduler,
DPMSolverMultistepScheduler,
DPMSolverSinglestepScheduler,
UniPCMultistepScheduler,
)
from .test_schedulers import SchedulerCommonTest
class _lowerCamelCase ( UpperCamelCase_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = (DEISMultistepScheduler,)
SCREAMING_SNAKE_CASE_ = (('''num_inference_steps''', 25),)
def __SCREAMING_SNAKE_CASE ( self , **__SCREAMING_SNAKE_CASE ) -> str:
"""simple docstring"""
UpperCamelCase__ : Union[str, Any] = {
'''num_train_timesteps''': 1_0_0_0,
'''beta_start''': 0.0001,
'''beta_end''': 0.02,
'''beta_schedule''': '''linear''',
'''solver_order''': 2,
}
config.update(**__SCREAMING_SNAKE_CASE )
return config
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE=0 , **__SCREAMING_SNAKE_CASE ) -> Any:
"""simple docstring"""
UpperCamelCase__ : Optional[Any] = dict(self.forward_default_kwargs )
UpperCamelCase__ : Dict = kwargs.pop('''num_inference_steps''' , __SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Tuple = self.dummy_sample
UpperCamelCase__ : Optional[int] = 0.1 * sample
UpperCamelCase__ : Tuple = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
UpperCamelCase__ : Union[str, Any] = self.get_scheduler_config(**__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Optional[Any] = scheduler_class(**__SCREAMING_SNAKE_CASE )
scheduler.set_timesteps(__SCREAMING_SNAKE_CASE )
# copy over dummy past residuals
UpperCamelCase__ : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : List[str] = scheduler_class.from_pretrained(__SCREAMING_SNAKE_CASE )
new_scheduler.set_timesteps(__SCREAMING_SNAKE_CASE )
# copy over dummy past residuals
UpperCamelCase__ : int = dummy_past_residuals[: new_scheduler.config.solver_order]
UpperCamelCase__ ,UpperCamelCase__ : Any = sample, sample
for t in range(__SCREAMING_SNAKE_CASE , time_step + scheduler.config.solver_order + 1 ):
UpperCamelCase__ : Union[str, Any] = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample
UpperCamelCase__ : int = new_scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def __SCREAMING_SNAKE_CASE ( self ) -> int:
"""simple docstring"""
pass
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE=0 , **__SCREAMING_SNAKE_CASE ) -> Optional[int]:
"""simple docstring"""
UpperCamelCase__ : List[Any] = dict(self.forward_default_kwargs )
UpperCamelCase__ : Tuple = kwargs.pop('''num_inference_steps''' , __SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Union[str, Any] = self.dummy_sample
UpperCamelCase__ : List[Any] = 0.1 * sample
UpperCamelCase__ : Dict = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
UpperCamelCase__ : Optional[int] = self.get_scheduler_config()
UpperCamelCase__ : Union[str, Any] = scheduler_class(**__SCREAMING_SNAKE_CASE )
scheduler.set_timesteps(__SCREAMING_SNAKE_CASE )
# copy over dummy past residuals (must be after setting timesteps)
UpperCamelCase__ : List[Any] = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : str = scheduler_class.from_pretrained(__SCREAMING_SNAKE_CASE )
# copy over dummy past residuals
new_scheduler.set_timesteps(__SCREAMING_SNAKE_CASE )
# copy over dummy past residual (must be after setting timesteps)
UpperCamelCase__ : Optional[int] = dummy_past_residuals[: new_scheduler.config.solver_order]
UpperCamelCase__ : Optional[Any] = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample
UpperCamelCase__ : Dict = new_scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ) -> int:
"""simple docstring"""
if scheduler is None:
UpperCamelCase__ : List[str] = self.scheduler_classes[0]
UpperCamelCase__ : str = self.get_scheduler_config(**__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Dict = scheduler_class(**__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : List[str] = self.scheduler_classes[0]
UpperCamelCase__ : Tuple = self.get_scheduler_config(**__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Any = scheduler_class(**__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : List[Any] = 1_0
UpperCamelCase__ : Tuple = self.dummy_model()
UpperCamelCase__ : Dict = self.dummy_sample_deter
scheduler.set_timesteps(__SCREAMING_SNAKE_CASE )
for i, t in enumerate(scheduler.timesteps ):
UpperCamelCase__ : List[Any] = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Optional[Any] = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).prev_sample
return sample
def __SCREAMING_SNAKE_CASE ( self ) -> int:
"""simple docstring"""
UpperCamelCase__ : Optional[int] = dict(self.forward_default_kwargs )
UpperCamelCase__ : List[Any] = kwargs.pop('''num_inference_steps''' , __SCREAMING_SNAKE_CASE )
for scheduler_class in self.scheduler_classes:
UpperCamelCase__ : Optional[int] = self.get_scheduler_config()
UpperCamelCase__ : Any = scheduler_class(**__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : int = self.dummy_sample
UpperCamelCase__ : int = 0.1 * sample
if num_inference_steps is not None and hasattr(__SCREAMING_SNAKE_CASE , '''set_timesteps''' ):
scheduler.set_timesteps(__SCREAMING_SNAKE_CASE )
elif num_inference_steps is not None and not hasattr(__SCREAMING_SNAKE_CASE , '''set_timesteps''' ):
UpperCamelCase__ : str = num_inference_steps
# copy over dummy past residuals (must be done after set_timesteps)
UpperCamelCase__ : Tuple = [residual + 0.2, residual + 0.15, residual + 0.10]
UpperCamelCase__ : Dict = dummy_past_residuals[: scheduler.config.solver_order]
UpperCamelCase__ : int = scheduler.timesteps[5]
UpperCamelCase__ : Optional[int] = scheduler.timesteps[6]
UpperCamelCase__ : Any = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample
UpperCamelCase__ : Any = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample
self.assertEqual(output_a.shape , sample.shape )
self.assertEqual(output_a.shape , output_a.shape )
def __SCREAMING_SNAKE_CASE ( self ) -> str:
"""simple docstring"""
UpperCamelCase__ : List[str] = DEISMultistepScheduler(**self.get_scheduler_config() )
UpperCamelCase__ : Tuple = self.full_loop(scheduler=__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Optional[Any] = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) )
assert abs(result_mean.item() - 0.23916 ) < 1e-3
UpperCamelCase__ : List[Any] = DPMSolverSinglestepScheduler.from_config(scheduler.config )
UpperCamelCase__ : Union[str, Any] = DPMSolverMultistepScheduler.from_config(scheduler.config )
UpperCamelCase__ : int = UniPCMultistepScheduler.from_config(scheduler.config )
UpperCamelCase__ : List[str] = DEISMultistepScheduler.from_config(scheduler.config )
UpperCamelCase__ : Dict = self.full_loop(scheduler=__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Optional[Any] = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) )
assert abs(result_mean.item() - 0.23916 ) < 1e-3
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
"""simple docstring"""
for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]:
self.check_over_configs(num_train_timesteps=__SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
"""simple docstring"""
self.check_over_configs(thresholding=__SCREAMING_SNAKE_CASE )
for order in [1, 2, 3]:
for solver_type in ["logrho"]:
for threshold in [0.5, 1.0, 2.0]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
thresholding=__SCREAMING_SNAKE_CASE , prediction_type=__SCREAMING_SNAKE_CASE , sample_max_value=__SCREAMING_SNAKE_CASE , algorithm_type='''deis''' , solver_order=__SCREAMING_SNAKE_CASE , solver_type=__SCREAMING_SNAKE_CASE , )
def __SCREAMING_SNAKE_CASE ( self ) -> List[str]:
"""simple docstring"""
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=__SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self ) -> str:
"""simple docstring"""
for algorithm_type in ["deis"]:
for solver_type in ["logrho"]:
for order in [1, 2, 3]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
solver_order=__SCREAMING_SNAKE_CASE , solver_type=__SCREAMING_SNAKE_CASE , prediction_type=__SCREAMING_SNAKE_CASE , algorithm_type=__SCREAMING_SNAKE_CASE , )
UpperCamelCase__ : Any = self.full_loop(
solver_order=__SCREAMING_SNAKE_CASE , solver_type=__SCREAMING_SNAKE_CASE , prediction_type=__SCREAMING_SNAKE_CASE , algorithm_type=__SCREAMING_SNAKE_CASE , )
assert not torch.isnan(__SCREAMING_SNAKE_CASE ).any(), "Samples have nan numbers"
def __SCREAMING_SNAKE_CASE ( self ) -> int:
"""simple docstring"""
self.check_over_configs(lower_order_final=__SCREAMING_SNAKE_CASE )
self.check_over_configs(lower_order_final=__SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]:
"""simple docstring"""
for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]:
self.check_over_forward(num_inference_steps=__SCREAMING_SNAKE_CASE , time_step=0 )
def __SCREAMING_SNAKE_CASE ( self ) -> Any:
"""simple docstring"""
UpperCamelCase__ : str = self.full_loop()
UpperCamelCase__ : Optional[int] = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) )
assert abs(result_mean.item() - 0.23916 ) < 1e-3
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
"""simple docstring"""
UpperCamelCase__ : Any = self.full_loop(prediction_type='''v_prediction''' )
UpperCamelCase__ : List[Any] = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) )
assert abs(result_mean.item() - 0.091 ) < 1e-3
def __SCREAMING_SNAKE_CASE ( self ) -> Any:
"""simple docstring"""
UpperCamelCase__ : Union[str, Any] = self.scheduler_classes[0]
UpperCamelCase__ : Optional[Any] = self.get_scheduler_config(thresholding=__SCREAMING_SNAKE_CASE , dynamic_thresholding_ratio=0 )
UpperCamelCase__ : Tuple = scheduler_class(**__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : List[Any] = 1_0
UpperCamelCase__ : Dict = self.dummy_model()
UpperCamelCase__ : Tuple = self.dummy_sample_deter.half()
scheduler.set_timesteps(__SCREAMING_SNAKE_CASE )
for i, t in enumerate(scheduler.timesteps ):
UpperCamelCase__ : Any = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Tuple = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).prev_sample
assert sample.dtype == torch.floataa
| 285 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__lowerCamelCase : str = {'''configuration_yolos''': ['''YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''YolosConfig''', '''YolosOnnxConfig''']}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCamelCase : List[str] = ['''YolosFeatureExtractor''']
__lowerCamelCase : List[str] = ['''YolosImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCamelCase : int = [
'''YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''YolosForObjectDetection''',
'''YolosModel''',
'''YolosPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_yolos import YolosFeatureExtractor
from .image_processing_yolos import YolosImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_yolos import (
YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST,
YolosForObjectDetection,
YolosModel,
YolosPreTrainedModel,
)
else:
import sys
__lowerCamelCase : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 714 | import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple
from transformers import AddedToken, BatchEncoding, PerceiverTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available
from ...test_tokenization_common import TokenizerTesterMixin
if is_torch_available():
__lowerCamelCase : Optional[int] = '''pt'''
elif is_tf_available():
__lowerCamelCase : str = '''tf'''
else:
__lowerCamelCase : int = '''jax'''
class a__ ( A__ , unittest.TestCase ):
A = PerceiverTokenizer
A = False
def __UpperCamelCase ( self : str ):
"""simple docstring"""
super().setUp()
SCREAMING_SNAKE_CASE_ : List[Any] = PerceiverTokenizer()
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def __UpperCamelCase ( self : Any ):
"""simple docstring"""
return PerceiverTokenizer.from_pretrained("deepmind/language-perceiver" )
def __UpperCamelCase ( self : Optional[int],**_A : List[Any] ):
"""simple docstring"""
return self.tokenizer_class.from_pretrained(self.tmpdirname,**_A )
def __UpperCamelCase ( self : List[Any],_A : Optional[Any],_A : str=False,_A : Tuple=20,_A : Tuple=5 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = []
for i in range(len(_A ) ):
try:
SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.decode([i],clean_up_tokenization_spaces=_A )
except UnicodeDecodeError:
pass
toks.append((i, tok) )
SCREAMING_SNAKE_CASE_ : int = list(filter(lambda _A : re.match(R"^[ a-zA-Z]+$",t[1] ),_A ) )
SCREAMING_SNAKE_CASE_ : Dict = list(filter(lambda _A : [t[0]] == tokenizer.encode(t[1],add_special_tokens=_A ),_A ) )
if max_length is not None and len(_A ) > max_length:
SCREAMING_SNAKE_CASE_ : List[str] = toks[:max_length]
if min_length is not None and len(_A ) < min_length and len(_A ) > 0:
while len(_A ) < min_length:
SCREAMING_SNAKE_CASE_ : int = toks + toks
# toks_str = [t[1] for t in toks]
SCREAMING_SNAKE_CASE_ : List[Any] = [t[0] for t in toks]
# Ensure consistency
SCREAMING_SNAKE_CASE_ : str = tokenizer.decode(_A,clean_up_tokenization_spaces=_A )
if " " not in output_txt and len(_A ) > 1:
SCREAMING_SNAKE_CASE_ : Dict = (
tokenizer.decode([toks_ids[0]],clean_up_tokenization_spaces=_A )
+ " "
+ tokenizer.decode(toks_ids[1:],clean_up_tokenization_spaces=_A )
)
if with_prefix_space:
SCREAMING_SNAKE_CASE_ : str = " " + output_txt
SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.encode(_A,add_special_tokens=_A )
return output_txt, output_ids
def __UpperCamelCase ( self : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[int] = self.perceiver_tokenizer
SCREAMING_SNAKE_CASE_ : Union[str, Any] = "Unicode €."
SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer(_A )
SCREAMING_SNAKE_CASE_ : int = [4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5]
self.assertEqual(encoded["input_ids"],_A )
# decoding
SCREAMING_SNAKE_CASE_ : str = tokenizer.decode(_A )
self.assertEqual(_A,"[CLS]Unicode €.[SEP]" )
SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer("e è é ê ë" )
SCREAMING_SNAKE_CASE_ : Tuple = [4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5]
self.assertEqual(encoded["input_ids"],_A )
# decoding
SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.decode(_A )
self.assertEqual(_A,"[CLS]e è é ê ë[SEP]" )
# encode/decode, but with `encode` instead of `__call__`
self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë" ) ),"[CLS]e è é ê ë[SEP]" )
def __UpperCamelCase ( self : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[Any] = self.perceiver_tokenizer
SCREAMING_SNAKE_CASE_ : List[str] = ["A long paragraph for summarization.", "Another paragraph for summarization."]
# fmt: off
SCREAMING_SNAKE_CASE_ : Optional[Any] = [4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0]
# fmt: on
SCREAMING_SNAKE_CASE_ : str = tokenizer(_A,padding=_A,return_tensors=_A )
self.assertIsInstance(_A,_A )
if FRAMEWORK != "jax":
SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(batch.input_ids.numpy()[0] )
else:
SCREAMING_SNAKE_CASE_ : Optional[int] = list(batch.input_ids.tolist()[0] )
self.assertListEqual(_A,_A )
self.assertEqual((2, 38),batch.input_ids.shape )
self.assertEqual((2, 38),batch.attention_mask.shape )
def __UpperCamelCase ( self : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[Any] = self.perceiver_tokenizer
SCREAMING_SNAKE_CASE_ : Any = ["A long paragraph for summarization.", "Another paragraph for summarization."]
SCREAMING_SNAKE_CASE_ : List[str] = tokenizer(_A,padding=_A,return_tensors=_A )
# check if input_ids are returned and no decoder_input_ids
self.assertIn("input_ids",_A )
self.assertIn("attention_mask",_A )
self.assertNotIn("decoder_input_ids",_A )
self.assertNotIn("decoder_attention_mask",_A )
def __UpperCamelCase ( self : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : int = self.perceiver_tokenizer
SCREAMING_SNAKE_CASE_ : int = [
"Summary of the text.",
"Another summary.",
]
SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer(
text_target=_A,max_length=32,padding="max_length",truncation=_A,return_tensors=_A )
self.assertEqual(32,targets["input_ids"].shape[1] )
def __UpperCamelCase ( self : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[str] = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F'{tokenizer.__class__.__name__}' ):
self.assertNotEqual(tokenizer.model_max_length,42 )
# Now let's start the test
SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F'{tokenizer.__class__.__name__}' ):
# Isolate this from the other tests because we save additional tokens/etc
SCREAMING_SNAKE_CASE_ : Tuple = tempfile.mkdtemp()
SCREAMING_SNAKE_CASE_ : str = " He is very happy, UNwant\u00E9d,running"
SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.encode(_A,add_special_tokens=_A )
tokenizer.save_pretrained(_A )
SCREAMING_SNAKE_CASE_ : int = tokenizer.__class__.from_pretrained(_A )
SCREAMING_SNAKE_CASE_ : Optional[int] = after_tokenizer.encode(_A,add_special_tokens=_A )
self.assertListEqual(_A,_A )
shutil.rmtree(_A )
SCREAMING_SNAKE_CASE_ : Tuple = self.get_tokenizers(model_max_length=42 )
for tokenizer in tokenizers:
with self.subTest(F'{tokenizer.__class__.__name__}' ):
# Isolate this from the other tests because we save additional tokens/etc
SCREAMING_SNAKE_CASE_ : Optional[Any] = tempfile.mkdtemp()
SCREAMING_SNAKE_CASE_ : Tuple = " He is very happy, UNwant\u00E9d,running"
tokenizer.add_tokens(["bim", "bambam"] )
SCREAMING_SNAKE_CASE_ : int = tokenizer.additional_special_tokens
additional_special_tokens.append("new_additional_special_token" )
tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens} )
SCREAMING_SNAKE_CASE_ : str = tokenizer.encode(_A,add_special_tokens=_A )
tokenizer.save_pretrained(_A )
SCREAMING_SNAKE_CASE_ : str = tokenizer.__class__.from_pretrained(_A )
SCREAMING_SNAKE_CASE_ : str = after_tokenizer.encode(_A,add_special_tokens=_A )
self.assertListEqual(_A,_A )
self.assertIn("new_additional_special_token",after_tokenizer.additional_special_tokens )
self.assertEqual(after_tokenizer.model_max_length,42 )
SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.__class__.from_pretrained(_A,model_max_length=43 )
self.assertEqual(tokenizer.model_max_length,43 )
shutil.rmtree(_A )
def __UpperCamelCase ( self : List[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[int] = []
if self.test_slow_tokenizer:
tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )
if self.test_rust_tokenizer:
tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )
for tokenizer_class, tokenizer_utils in tokenizer_list:
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer_utils.save_pretrained(_A )
with open(os.path.join(_A,"special_tokens_map.json" ),encoding="utf-8" ) as json_file:
SCREAMING_SNAKE_CASE_ : Optional[int] = json.load(_A )
with open(os.path.join(_A,"tokenizer_config.json" ),encoding="utf-8" ) as json_file:
SCREAMING_SNAKE_CASE_ : int = json.load(_A )
SCREAMING_SNAKE_CASE_ : Any = [F'<extra_id_{i}>' for i in range(125 )]
SCREAMING_SNAKE_CASE_ : List[Any] = added_tokens_extra_ids + [
"an_additional_special_token"
]
SCREAMING_SNAKE_CASE_ : Union[str, Any] = added_tokens_extra_ids + [
"an_additional_special_token"
]
with open(os.path.join(_A,"special_tokens_map.json" ),"w",encoding="utf-8" ) as outfile:
json.dump(_A,_A )
with open(os.path.join(_A,"tokenizer_config.json" ),"w",encoding="utf-8" ) as outfile:
json.dump(_A,_A )
# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
# "special_tokens_map.json" files
SCREAMING_SNAKE_CASE_ : Dict = tokenizer_class.from_pretrained(
_A,)
self.assertIn(
"an_additional_special_token",tokenizer_without_change_in_init.additional_special_tokens )
self.assertEqual(
["an_additional_special_token"],tokenizer_without_change_in_init.convert_ids_to_tokens(
tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"] ) ),)
# Now we test that we can change the value of additional_special_tokens in the from_pretrained
SCREAMING_SNAKE_CASE_ : Union[str, Any] = added_tokens_extra_ids + [AddedToken("a_new_additional_special_token",lstrip=_A )]
SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer_class.from_pretrained(
_A,additional_special_tokens=_A,)
self.assertIn("a_new_additional_special_token",tokenizer.additional_special_tokens )
self.assertEqual(
["a_new_additional_special_token"],tokenizer.convert_ids_to_tokens(
tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"] ) ),)
def __UpperCamelCase ( self : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = self.perceiver_tokenizer
self.assertEqual(tokenizer.decode([178] ),"�" )
def __UpperCamelCase ( self : Dict ):
"""simple docstring"""
pass
def __UpperCamelCase ( self : int ):
"""simple docstring"""
pass
def __UpperCamelCase ( self : Optional[int] ):
"""simple docstring"""
pass
def __UpperCamelCase ( self : List[str] ):
"""simple docstring"""
pass
def __UpperCamelCase ( self : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Tuple = self.get_tokenizers(fast=_A,do_lower_case=_A )
for tokenizer in tokenizers:
with self.subTest(F'{tokenizer.__class__.__name__}' ):
SCREAMING_SNAKE_CASE_ : str = ["[CLS]", "t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "s", "t", "[SEP]"]
SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.convert_tokens_to_string(_A )
self.assertIsInstance(_A,_A )
| 316 | 0 |
"""simple docstring"""
import importlib
import inspect
import os
import re
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
lowerCAmelCase__ = '''src/transformers'''
# This is to make sure the transformers module imported is the one in the repo.
lowerCAmelCase__ = importlib.util.spec_from_file_location(
'''transformers''',
os.path.join(PATH_TO_TRANSFORMERS, '''__init__.py'''),
submodule_search_locations=[PATH_TO_TRANSFORMERS],
)
lowerCAmelCase__ = spec.loader.load_module()
lowerCAmelCase__ = transformers.models.auto.configuration_auto.CONFIG_MAPPING
# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
lowerCAmelCase__ = re.compile('''\[(.+?)\]\((https://huggingface\.co/.+?)\)''')
lowerCAmelCase__ = {
'''CLIPConfigMixin''',
'''DecisionTransformerConfigMixin''',
'''EncoderDecoderConfigMixin''',
'''RagConfigMixin''',
'''SpeechEncoderDecoderConfigMixin''',
'''VisionEncoderDecoderConfigMixin''',
'''VisionTextDualEncoderConfigMixin''',
}
def snake_case_ ( ):
'''simple docstring'''
_lowerCamelCase : Any = []
for config_class in list(CONFIG_MAPPING.values() ):
_lowerCamelCase : Tuple = False
# source code of `config_class`
_lowerCamelCase : int = inspect.getsource(A_ )
_lowerCamelCase : str = _re_checkpoint.findall(A_ )
for checkpoint in checkpoints:
# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
_lowerCamelCase , _lowerCamelCase : Tuple = checkpoint
# verify the checkpoint name corresponds to the checkpoint link
_lowerCamelCase : Tuple = F'''https://huggingface.co/{ckpt_name}'''
if ckpt_link == ckpt_link_from_name:
_lowerCamelCase : Union[str, Any] = True
break
_lowerCamelCase : Tuple = config_class.__name__
if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
configs_without_checkpoint.append(A_ )
if len(A_ ) > 0:
_lowerCamelCase : Union[str, Any] = '''\n'''.join(sorted(A_ ) )
raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' )
if __name__ == "__main__":
check_config_docstrings_have_checkpoints()
| 83 |
def lowerCamelCase_ ( UpperCamelCase_ , UpperCamelCase_ ):
if a < 0 or b < 0:
raise ValueError('''the value of both inputs must be positive''' )
_a : str = str(bin(UpperCamelCase_ ) )[2:] # remove the leading "0b"
_a : Dict = str(bin(UpperCamelCase_ ) )[2:]
_a : str = max(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) )
return "0b" + "".join(
str(int('''1''' in (char_a, char_b) ) )
for char_a, char_b in zip(a_binary.zfill(UpperCamelCase_ ) , b_binary.zfill(UpperCamelCase_ ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 471 | 0 |
import json
from typing import TYPE_CHECKING, List, Optional, Tuple
from tokenizers import pre_tokenizers
from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_gpta import GPTaTokenizer
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}
SCREAMING_SNAKE_CASE_ = {
'''vocab_file''': {
'''gpt2''': '''https://huggingface.co/gpt2/resolve/main/vocab.json''',
'''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/vocab.json''',
'''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/vocab.json''',
'''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/vocab.json''',
'''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/vocab.json''',
},
'''merges_file''': {
'''gpt2''': '''https://huggingface.co/gpt2/resolve/main/merges.txt''',
'''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/merges.txt''',
'''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/merges.txt''',
'''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/merges.txt''',
'''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/merges.txt''',
},
'''tokenizer_file''': {
'''gpt2''': '''https://huggingface.co/gpt2/resolve/main/tokenizer.json''',
'''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json''',
'''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/tokenizer.json''',
'''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json''',
'''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/tokenizer.json''',
},
}
SCREAMING_SNAKE_CASE_ = {
'''gpt2''': 1_0_2_4,
'''gpt2-medium''': 1_0_2_4,
'''gpt2-large''': 1_0_2_4,
'''gpt2-xl''': 1_0_2_4,
'''distilgpt2''': 1_0_2_4,
}
class UpperCamelCase__ ( UpperCamelCase__ ):
'''simple docstring'''
__snake_case : Dict = VOCAB_FILES_NAMES
__snake_case : Any = PRETRAINED_VOCAB_FILES_MAP
__snake_case : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__snake_case : Optional[Any] = ["""input_ids""", """attention_mask"""]
__snake_case : Union[str, Any] = GPTaTokenizer
def __init__( self : Any ,lowerCamelCase__ : List[str]=None ,lowerCamelCase__ : Optional[int]=None ,lowerCamelCase__ : Union[str, Any]=None ,lowerCamelCase__ : Any="<|endoftext|>" ,lowerCamelCase__ : Dict="<|endoftext|>" ,lowerCamelCase__ : str="<|endoftext|>" ,lowerCamelCase__ : Dict=False ,**lowerCamelCase__ : List[str] ,) -> int:
'''simple docstring'''
super().__init__(
lowerCamelCase__ ,lowerCamelCase__ ,tokenizer_file=lowerCamelCase__ ,unk_token=lowerCamelCase__ ,bos_token=lowerCamelCase__ ,eos_token=lowerCamelCase__ ,add_prefix_space=lowerCamelCase__ ,**lowerCamelCase__ ,)
SCREAMING_SNAKE_CASE = kwargs.pop("""add_bos_token""" ,lowerCamelCase__ )
SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get("""add_prefix_space""" ,lowerCamelCase__ ) != add_prefix_space:
SCREAMING_SNAKE_CASE = getattr(lowerCamelCase__ ,pre_tok_state.pop("""type""" ) )
SCREAMING_SNAKE_CASE = add_prefix_space
SCREAMING_SNAKE_CASE = pre_tok_class(**lowerCamelCase__ )
SCREAMING_SNAKE_CASE = add_prefix_space
def SCREAMING_SNAKE_CASE__ ( self : Tuple ,*lowerCamelCase__ : Optional[int] ,**lowerCamelCase__ : Tuple ) -> BatchEncoding:
'''simple docstring'''
SCREAMING_SNAKE_CASE = kwargs.get("""is_split_into_words""" ,lowerCamelCase__ )
assert self.add_prefix_space or not is_split_into_words, (
F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
"to use it with pretokenized inputs."
)
return super()._batch_encode_plus(*lowerCamelCase__ ,**lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : Tuple ,*lowerCamelCase__ : Any ,**lowerCamelCase__ : int ) -> BatchEncoding:
'''simple docstring'''
SCREAMING_SNAKE_CASE = kwargs.get("""is_split_into_words""" ,lowerCamelCase__ )
assert self.add_prefix_space or not is_split_into_words, (
F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
"to use it with pretokenized inputs."
)
return super()._encode_plus(*lowerCamelCase__ ,**lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : Any ,lowerCamelCase__ : Any = None ) -> Tuple[str]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self._tokenizer.model.save(lowerCamelCase__ ,name=lowerCamelCase__ )
return tuple(lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : str ,lowerCamelCase__ : List[Any] ) -> List[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = []
for is_user, text in conversation.iter_texts():
input_ids.extend(self.encode(lowerCamelCase__ ,add_special_tokens=lowerCamelCase__ ) + [self.eos_token_id] )
if len(lowerCamelCase__ ) > self.model_max_length:
SCREAMING_SNAKE_CASE = input_ids[-self.model_max_length :]
return input_ids
| 717 |
from __future__ import annotations
import inspect
import unittest
import numpy as np
from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFResNetForImageClassification, TFResNetModel
from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class UpperCamelCase__ :
'''simple docstring'''
def __init__( self : str ,lowerCamelCase__ : int ,lowerCamelCase__ : List[str]=3 ,lowerCamelCase__ : Optional[Any]=32 ,lowerCamelCase__ : Any=3 ,lowerCamelCase__ : Any=10 ,lowerCamelCase__ : Any=[10, 20, 30, 40] ,lowerCamelCase__ : Any=[1, 1, 2, 1] ,lowerCamelCase__ : Union[str, Any]=True ,lowerCamelCase__ : List[str]=True ,lowerCamelCase__ : Union[str, Any]="relu" ,lowerCamelCase__ : Dict=3 ,lowerCamelCase__ : Any=None ,) -> Union[str, Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = parent
SCREAMING_SNAKE_CASE = batch_size
SCREAMING_SNAKE_CASE = image_size
SCREAMING_SNAKE_CASE = num_channels
SCREAMING_SNAKE_CASE = embeddings_size
SCREAMING_SNAKE_CASE = hidden_sizes
SCREAMING_SNAKE_CASE = depths
SCREAMING_SNAKE_CASE = is_training
SCREAMING_SNAKE_CASE = use_labels
SCREAMING_SNAKE_CASE = hidden_act
SCREAMING_SNAKE_CASE = num_labels
SCREAMING_SNAKE_CASE = scope
SCREAMING_SNAKE_CASE = len(lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
SCREAMING_SNAKE_CASE = None
if self.use_labels:
SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] ,self.num_labels )
SCREAMING_SNAKE_CASE = self.get_config()
return config, pixel_values, labels
def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Union[str, Any]:
'''simple docstring'''
return ResNetConfig(
num_channels=self.num_channels ,embeddings_size=self.embeddings_size ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,hidden_act=self.hidden_act ,num_labels=self.num_labels ,image_size=self.image_size ,)
def SCREAMING_SNAKE_CASE__ ( self : Dict ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : List[Any] ) -> Union[str, Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = TFResNetModel(config=lowerCamelCase__ )
SCREAMING_SNAKE_CASE = model(lowerCamelCase__ )
# expected last hidden states: B, C, H // 32, W // 32
self.parent.assertEqual(
result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,)
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Dict ) -> str:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.num_labels
SCREAMING_SNAKE_CASE = TFResNetForImageClassification(lowerCamelCase__ )
SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,labels=lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) )
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = config_and_inputs
SCREAMING_SNAKE_CASE = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_tf
class UpperCamelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ):
'''simple docstring'''
__snake_case : Union[str, Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
__snake_case : int = (
{"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
if is_tf_available()
else {}
)
__snake_case : Optional[int] = False
__snake_case : int = False
__snake_case : Optional[Any] = False
__snake_case : Union[str, Any] = False
__snake_case : str = False
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> List[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = TFResNetModelTester(self )
SCREAMING_SNAKE_CASE = ConfigTester(self ,config_class=lowerCamelCase__ ,has_text_modality=lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Union[str, Any]:
'''simple docstring'''
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def SCREAMING_SNAKE_CASE__ ( self : int ) -> List[Any]:
'''simple docstring'''
return
@unittest.skip(reason="""ResNet does not use inputs_embeds""" )
def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any:
'''simple docstring'''
pass
@unittest.skip(reason="""ResNet does not support input and output embeddings""" )
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Optional[int]:
'''simple docstring'''
pass
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> List[str]:
'''simple docstring'''
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE = model_class(lowerCamelCase__ )
SCREAMING_SNAKE_CASE = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
SCREAMING_SNAKE_CASE = [*signature.parameters.keys()]
SCREAMING_SNAKE_CASE = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] ,lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Union[str, Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : int ) -> List[Any]:
'''simple docstring'''
def check_hidden_states_output(lowerCamelCase__ : str ,lowerCamelCase__ : Dict ,lowerCamelCase__ : Dict ):
SCREAMING_SNAKE_CASE = model_class(lowerCamelCase__ )
SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ ) )
SCREAMING_SNAKE_CASE = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
SCREAMING_SNAKE_CASE = self.model_tester.num_stages
self.assertEqual(len(lowerCamelCase__ ) ,expected_num_stages + 1 )
# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) ,[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,)
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
SCREAMING_SNAKE_CASE = ["""basic""", """bottleneck"""]
for model_class in self.all_model_classes:
for layer_type in layers_type:
SCREAMING_SNAKE_CASE = layer_type
SCREAMING_SNAKE_CASE = True
check_hidden_states_output(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
SCREAMING_SNAKE_CASE = True
check_hidden_states_output(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Tuple:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__ )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> List[Any]:
'''simple docstring'''
for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(lowerCamelCase__ )
self.assertIsNotNone(lowerCamelCase__ )
def __lowercase ( ) -> Union[str, Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_tf
@require_vision
class UpperCamelCase__ ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Dict:
'''simple docstring'''
return (
AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
if is_vision_available()
else None
)
@slow
def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
SCREAMING_SNAKE_CASE = self.default_image_processor
SCREAMING_SNAKE_CASE = prepare_img()
SCREAMING_SNAKE_CASE = image_processor(images=lowerCamelCase__ ,return_tensors="""tf""" )
# forward pass
SCREAMING_SNAKE_CASE = model(**lowerCamelCase__ )
# verify the logits
SCREAMING_SNAKE_CASE = tf.TensorShape((1, 1000) )
self.assertEqual(outputs.logits.shape ,lowerCamelCase__ )
SCREAMING_SNAKE_CASE = tf.constant([-11.1069, -9.7877, -8.3777] )
self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() ,lowerCamelCase__ ,atol=1e-4 ) )
| 116 | 0 |
import builtins
import sys
from ...utils.imports import _is_package_available
from . import cursor, input
from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
from .keymap import KEYMAP
_lowerCAmelCase = False
try:
_lowerCAmelCase = _is_package_available("""google.colab""")
except ModuleNotFoundError:
pass
@input.register
class _UpperCAmelCase :
def __init__( self , a__ = None , a__ = [] ):
A_ : Union[str, Any] = 0
A_ : Optional[Any] = choices
A_ : Optional[int] = prompt
if sys.platform == "win32":
A_ : int = """*"""
else:
A_ : str = """➔ """
def _lowerCamelCase ( self , a__ , a__ = "" ):
if sys.platform != "win32":
writeColor(self.choices[index] , 32 , a__ )
else:
forceWrite(self.choices[index] , a__ )
def _lowerCamelCase ( self , a__ ):
if index == self.position:
forceWrite(F""" {self.arrow_char} """ )
self.write_choice(a__ )
else:
forceWrite(F""" {self.choices[index]}""" )
reset_cursor()
def _lowerCamelCase ( self , a__ , a__ = 1 ):
A_ : Any = self.position
if direction == Direction.DOWN:
if self.position + 1 >= len(self.choices ):
return
self.position += num_spaces
else:
if self.position - 1 < 0:
return
self.position -= num_spaces
clear_line()
self.print_choice(a__ )
move_cursor(a__ , direction.name )
self.print_choice(self.position )
@input.mark(KEYMAP["""up"""] )
def _lowerCamelCase ( self ):
self.move_direction(Direction.UP )
@input.mark(KEYMAP["""down"""] )
def _lowerCamelCase ( self ):
self.move_direction(Direction.DOWN )
@input.mark(KEYMAP["""newline"""] )
def _lowerCamelCase ( self ):
move_cursor(len(self.choices ) - self.position , """DOWN""" )
return self.position
@input.mark(KEYMAP["""interrupt"""] )
def _lowerCamelCase ( self ):
move_cursor(len(self.choices ) - self.position , """DOWN""" )
raise KeyboardInterrupt
@input.mark_multiple(*[KEYMAP[str(a__ )] for number in range(10 )] )
def _lowerCamelCase ( self ):
A_ : Any = int(chr(self.current_selection ) )
A_ : List[Any] = index - self.position
if index == self.position:
return
if index < len(self.choices ):
if self.position > index:
self.move_direction(Direction.UP , -movement )
elif self.position < index:
self.move_direction(Direction.DOWN , a__ )
else:
return
else:
return
def _lowerCamelCase ( self , a__ = 0 ):
if self.prompt:
linebreak()
forceWrite(self.prompt , """\n""" )
if in_colab:
forceWrite("""Please input a choice index (starting from 0), and press enter""" , """\n""" )
else:
forceWrite("""Please select a choice using the arrow or number keys, and selecting with enter""" , """\n""" )
A_ : int = default_choice
for i in range(len(self.choices ) ):
self.print_choice(a__ )
forceWrite("""\n""" )
move_cursor(len(self.choices ) - self.position , """UP""" )
with cursor.hide():
while True:
if in_colab:
try:
A_ : List[Any] = int(builtins.input() )
except ValueError:
A_ : Optional[Any] = default_choice
else:
A_ : str = self.handle_input()
if choice is not None:
reset_cursor()
for _ in range(len(self.choices ) + 1 ):
move_cursor(1 , """UP""" )
clear_line()
self.write_choice(a__ , """\n""" )
return choice
| 569 |
import os
from math import logaa
def _lowerCAmelCase ( _lowerCAmelCase = "base_exp.txt" ):
'''simple docstring'''
A_ : float = 0
A_ : int = 0
for i, line in enumerate(open(os.path.join(os.path.dirname(_lowerCAmelCase ) ,_lowerCAmelCase ) ) ):
A_ , A_ : str = list(map(_lowerCAmelCase ,line.split(""",""" ) ) )
if x * logaa(_lowerCAmelCase ) > largest:
A_ : Tuple = x * logaa(_lowerCAmelCase )
A_ : List[Any] = i + 1
return result
if __name__ == "__main__":
print(solution())
| 569 | 1 |
"""simple docstring"""
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer
a = logging.get_logger(__name__)
a = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}
a = {
'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'
),
},
}
a = {
'bert-base-uncased': 5_1_2,
'bert-large-uncased': 5_1_2,
'bert-base-cased': 5_1_2,
'bert-large-cased': 5_1_2,
'bert-base-multilingual-uncased': 5_1_2,
'bert-base-multilingual-cased': 5_1_2,
'bert-base-chinese': 5_1_2,
'bert-base-german-cased': 5_1_2,
'bert-large-uncased-whole-word-masking': 5_1_2,
'bert-large-cased-whole-word-masking': 5_1_2,
'bert-large-uncased-whole-word-masking-finetuned-squad': 5_1_2,
'bert-large-cased-whole-word-masking-finetuned-squad': 5_1_2,
'bert-base-cased-finetuned-mrpc': 5_1_2,
'bert-base-german-dbmdz-cased': 5_1_2,
'bert-base-german-dbmdz-uncased': 5_1_2,
'TurkuNLP/bert-base-finnish-cased-v1': 5_1_2,
'TurkuNLP/bert-base-finnish-uncased-v1': 5_1_2,
'wietsedv/bert-base-dutch-cased': 5_1_2,
}
a = {
'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 SCREAMING_SNAKE_CASE__ ( a__ ):
_a = VOCAB_FILES_NAMES
_a = PRETRAINED_VOCAB_FILES_MAP
_a = PRETRAINED_INIT_CONFIGURATION
_a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_a = BertTokenizer
def __init__( self : Dict , lowerCAmelCase : List[Any]=None , lowerCAmelCase : int=None , lowerCAmelCase : Dict=True , lowerCAmelCase : Any="[UNK]" , lowerCAmelCase : Union[str, Any]="[SEP]" , lowerCAmelCase : Union[str, Any]="[PAD]" , lowerCAmelCase : Tuple="[CLS]" , lowerCAmelCase : Optional[Any]="[MASK]" , lowerCAmelCase : Any=True , lowerCAmelCase : str=None , **lowerCAmelCase : Any , ):
super().__init__(
_A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , )
lowerCAmelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get("""lowercase""" , _A ) != do_lower_case
or normalizer_state.get("""strip_accents""" , _A ) != strip_accents
or normalizer_state.get("""handle_chinese_chars""" , _A ) != tokenize_chinese_chars
):
lowerCAmelCase = getattr(_A , normalizer_state.pop("""type""" ) )
lowerCAmelCase = do_lower_case
lowerCAmelCase = strip_accents
lowerCAmelCase = tokenize_chinese_chars
lowerCAmelCase = normalizer_class(**_A )
lowerCAmelCase = do_lower_case
def __lowercase ( self : Union[str, Any] , lowerCAmelCase : Tuple , lowerCAmelCase : List[Any]=None ):
lowerCAmelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def __lowercase ( self : Dict , lowerCAmelCase : str , lowerCAmelCase : int = None ):
lowerCAmelCase = [self.sep_token_id]
lowerCAmelCase = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def __lowercase ( self : str , lowerCAmelCase : Tuple , lowerCAmelCase : str = None ):
lowerCAmelCase = self._tokenizer.model.save(_A , name=_A )
return tuple(_A )
| 716 |
"""simple docstring"""
import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing the experiment tracking capability,
# 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
#
########################################################################
a = 1_6
a = 3_2
def lowercase (snake_case__ : Accelerator , snake_case__ : int = 16 ) -> Dict:
'''simple docstring'''
lowerCAmelCase = AutoTokenizer.from_pretrained("""bert-base-cased""" )
lowerCAmelCase = load_dataset("""glue""" , """mrpc""" )
def tokenize_function(snake_case__ : List[Any] ):
# max_length=None => use the model max length (it's actually the default)
lowerCAmelCase = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=snake_case__ , max_length=snake_case__ )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
lowerCAmelCase = datasets.map(
snake_case__ , batched=snake_case__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
lowerCAmelCase = tokenized_datasets.rename_column("""label""" , """labels""" )
def collate_fn(snake_case__ : Union[str, Any] ):
# On TPU it's best to pad everything to the same length or training will be very slow.
lowerCAmelCase = 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":
lowerCAmelCase = 16
elif accelerator.mixed_precision != "no":
lowerCAmelCase = 8
else:
lowerCAmelCase = None
return tokenizer.pad(
snake_case__ , padding="""longest""" , max_length=snake_case__ , pad_to_multiple_of=snake_case__ , return_tensors="""pt""" , )
# Instantiate dataloaders.
lowerCAmelCase = DataLoader(
tokenized_datasets["""train"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ )
lowerCAmelCase = DataLoader(
tokenized_datasets["""validation"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ )
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
a = mocked_dataloaders # noqa: F811
def lowercase (snake_case__ : int , snake_case__ : Tuple ) -> int:
'''simple docstring'''
if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , snake_case__ ) == "1":
lowerCAmelCase = 2
# Initialize Accelerator
# New Code #
# We pass in "all" to `log_with` to grab all available trackers in the environment
# Note: If using a custom `Tracker` class, should be passed in here such as:
# >>> log_with = ["all", MyCustomTrackerClassInstance()]
if args.with_tracking:
lowerCAmelCase = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="""all""" , project_dir=args.project_dir )
else:
lowerCAmelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lowerCAmelCase = config["""lr"""]
lowerCAmelCase = int(config["""num_epochs"""] )
lowerCAmelCase = int(config["""seed"""] )
lowerCAmelCase = int(config["""batch_size"""] )
set_seed(snake_case__ )
lowerCAmelCase , lowerCAmelCase = get_dataloaders(snake_case__ , snake_case__ )
lowerCAmelCase = evaluate.load("""glue""" , """mrpc""" )
# If the batch size is too big we use gradient accumulation
lowerCAmelCase = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
lowerCAmelCase = batch_size // MAX_GPU_BATCH_SIZE
lowerCAmelCase = MAX_GPU_BATCH_SIZE
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
lowerCAmelCase = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=snake_case__ )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
lowerCAmelCase = model.to(accelerator.device )
# Instantiate optimizer
lowerCAmelCase = AdamW(params=model.parameters() , lr=snake_case__ )
# Instantiate scheduler
lowerCAmelCase = get_linear_schedule_with_warmup(
optimizer=snake_case__ , num_warmup_steps=100 , num_training_steps=(len(snake_case__ ) * 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.
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = accelerator.prepare(
snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ )
# New Code #
# We need to initialize the trackers we use. Overall configurations can also be stored
if args.with_tracking:
lowerCAmelCase = os.path.split(snake_case__ )[-1].split(""".""" )[0]
accelerator.init_trackers(snake_case__ , snake_case__ )
# Now we train the model
for epoch in range(snake_case__ ):
model.train()
# New Code #
# For our tracking example, we will log the total loss of each epoch
if args.with_tracking:
lowerCAmelCase = 0
for step, batch in enumerate(snake_case__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
lowerCAmelCase = model(**snake_case__ )
lowerCAmelCase = outputs.loss
# New Code #
if args.with_tracking:
total_loss += loss.detach().float()
lowerCAmelCase = loss / gradient_accumulation_steps
accelerator.backward(snake_case__ )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(snake_case__ ):
# We could avoid this line since we set the accelerator with `device_placement=True` (the default).
batch.to(accelerator.device )
with torch.no_grad():
lowerCAmelCase = model(**snake_case__ )
lowerCAmelCase = outputs.logits.argmax(dim=-1 )
lowerCAmelCase , lowerCAmelCase = accelerator.gather_for_metrics((predictions, batch["""labels"""]) )
metric.add_batch(
predictions=snake_case__ , references=snake_case__ , )
lowerCAmelCase = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f'''epoch {epoch}:''' , snake_case__ )
# New Code #
# To actually log, we call `Accelerator.log`
# The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int`
if args.with_tracking:
accelerator.log(
{
"""accuracy""": eval_metric["""accuracy"""],
"""f1""": eval_metric["""f1"""],
"""train_loss""": total_loss.item() / len(snake_case__ ),
"""epoch""": epoch,
} , step=snake_case__ , )
# New Code #
# When a run is finished, you should call `accelerator.end_training()`
# to close all of the open trackers
if args.with_tracking:
accelerator.end_training()
def lowercase () -> str:
'''simple docstring'''
lowerCAmelCase = argparse.ArgumentParser(description="""Simple example of training script.""" )
parser.add_argument(
"""--mixed_precision""" , type=snake_case__ , default=snake_case__ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose"""
"""between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."""
"""and an Nvidia Ampere GPU.""" , )
parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" )
parser.add_argument(
"""--with_tracking""" , action="""store_true""" , help="""Whether to load in all available experiment trackers from the environment and use them for logging.""" , )
parser.add_argument(
"""--project_dir""" , type=snake_case__ , default="""logs""" , help="""Location on where to store experiment tracking logs` and relevent project information""" , )
lowerCAmelCase = parser.parse_args()
lowerCAmelCase = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
training_function(snake_case__ , snake_case__ )
if __name__ == "__main__":
main()
| 529 | 0 |
import math
import sys
def lowerCamelCase__ ( _lowercase ):
'''simple docstring'''
UpperCAmelCase_ : List[str] = ''''''
try:
with open(_lowercase , '''rb''' ) as binary_file:
UpperCAmelCase_ : Dict = binary_file.read()
for dat in data:
UpperCAmelCase_ : Union[str, Any] = f'''{dat:08b}'''
result += curr_byte
return result
except OSError:
print('''File not accessible''' )
sys.exit()
def lowerCamelCase__ ( _lowercase ):
'''simple docstring'''
UpperCAmelCase_ : Optional[int] = {'''0''': '''0''', '''1''': '''1'''}
UpperCAmelCase_, UpperCAmelCase_ : str = '''''', ''''''
UpperCAmelCase_ : Any = len(_lowercase )
for i in range(len(_lowercase ) ):
curr_string += data_bits[i]
if curr_string not in lexicon:
continue
UpperCAmelCase_ : Any = lexicon[curr_string]
result += last_match_id
UpperCAmelCase_ : Any = last_match_id + '''0'''
if math.loga(_lowercase ).is_integer():
UpperCAmelCase_ : int = {}
for curr_key in list(_lowercase ):
UpperCAmelCase_ : List[Any] = lexicon.pop(_lowercase )
UpperCAmelCase_ : List[Any] = new_lex
UpperCAmelCase_ : Any = last_match_id + '''1'''
index += 1
UpperCAmelCase_ : List[Any] = ''''''
return result
def lowerCamelCase__ ( _lowercase , _lowercase ):
'''simple docstring'''
UpperCAmelCase_ : str = 8
try:
with open(_lowercase , '''wb''' ) as opened_file:
UpperCAmelCase_ : List[str] = [
to_write[i : i + byte_length]
for i in range(0 , len(_lowercase ) , _lowercase )
]
if len(result_byte_array[-1] ) % byte_length == 0:
result_byte_array.append('''10000000''' )
else:
result_byte_array[-1] += "1" + "0" * (
byte_length - len(result_byte_array[-1] ) - 1
)
for elem in result_byte_array[:-1]:
opened_file.write(int(_lowercase , 2 ).to_bytes(1 , byteorder='''big''' ) )
except OSError:
print('''File not accessible''' )
sys.exit()
def lowerCamelCase__ ( _lowercase ):
'''simple docstring'''
UpperCAmelCase_ : Dict = 0
for letter in data_bits:
if letter == "1":
break
counter += 1
UpperCAmelCase_ : Optional[int] = data_bits[counter:]
UpperCAmelCase_ : Dict = data_bits[counter + 1 :]
return data_bits
def lowerCamelCase__ ( _lowercase , _lowercase ):
'''simple docstring'''
UpperCAmelCase_ : List[Any] = read_file_binary(_lowercase )
UpperCAmelCase_ : Optional[Any] = remove_prefix(_lowercase )
UpperCAmelCase_ : Tuple = decompress_data(_lowercase )
write_file_binary(_lowercase , _lowercase )
if __name__ == "__main__":
compress(sys.argv[1], sys.argv[2]) | 30 |
'''simple docstring'''
import unittest
import numpy as np
import torch
from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class lowerCAmelCase ( unittest.TestCase ):
@property
def snake_case ( self : str ):
"""simple docstring"""
torch.manual_seed(0 )
__lowercase =UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , )
return model
def snake_case ( self : int ):
"""simple docstring"""
__lowercase =self.dummy_uncond_unet
__lowercase =PNDMScheduler()
__lowercase =PNDMPipeline(unet=__lowercase , scheduler=__lowercase )
pndm.to(__lowercase )
pndm.set_progress_bar_config(disable=__lowercase )
__lowercase =torch.manual_seed(0 )
__lowercase =pndm(generator=__lowercase , num_inference_steps=20 , output_type='numpy' ).images
__lowercase =torch.manual_seed(0 )
__lowercase =pndm(generator=__lowercase , num_inference_steps=20 , output_type='numpy' , return_dict=__lowercase )[0]
__lowercase =image[0, -3:, -3:, -1]
__lowercase =image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
__lowercase =np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
@slow
@require_torch
class lowerCAmelCase ( unittest.TestCase ):
def snake_case ( self : Union[str, Any] ):
"""simple docstring"""
__lowercase ='google/ddpm-cifar10-32'
__lowercase =UNetaDModel.from_pretrained(__lowercase )
__lowercase =PNDMScheduler()
__lowercase =PNDMPipeline(unet=__lowercase , scheduler=__lowercase )
pndm.to(__lowercase )
pndm.set_progress_bar_config(disable=__lowercase )
__lowercase =torch.manual_seed(0 )
__lowercase =pndm(generator=__lowercase , output_type='numpy' ).images
__lowercase =image[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
__lowercase =np.array([0.1_5_6_4, 0.1_4_6_4_5, 0.1_4_0_6, 0.1_4_7_1_5, 0.1_2_4_2_5, 0.1_4_0_4_5, 0.1_3_1_1_5, 0.1_2_1_7_5, 0.1_2_5] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
| 119 | 0 |
def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> int:
"""simple docstring"""
if len(snake_case__ ) != len(snake_case__ ):
raise ValueError("""The length of profit and weight must be same.""" )
if max_weight <= 0:
raise ValueError("""max_weight must greater than zero.""" )
if any(p < 0 for p in profit ):
raise ValueError("""Profit can not be negative.""" )
if any(w < 0 for w in weight ):
raise ValueError("""Weight can not be negative.""" )
# List created to store profit gained for the 1kg in case of each weight
# respectively. Calculate and append profit/weight for each element.
_SCREAMING_SNAKE_CASE = [p / w for p, w in zip(snake_case__ ,snake_case__ )]
# Creating a copy of the list and sorting profit/weight in ascending order
_SCREAMING_SNAKE_CASE = sorted(snake_case__ )
# declaring useful variables
_SCREAMING_SNAKE_CASE = len(snake_case__ )
_SCREAMING_SNAKE_CASE = 0
_SCREAMING_SNAKE_CASE = 0
_SCREAMING_SNAKE_CASE = 0
# loop till the total weight do not reach max limit e.g. 15 kg and till i<length
while limit <= max_weight and i < length:
# flag value for encountered greatest element in sorted_profit_by_weight
_SCREAMING_SNAKE_CASE = sorted_profit_by_weight[length - i - 1]
_SCREAMING_SNAKE_CASE = profit_by_weight.index(snake_case__ )
_SCREAMING_SNAKE_CASE = -1
# check if the weight encountered is less than the total weight
# encountered before.
if max_weight - limit >= weight[index]:
limit += weight[index]
# Adding profit gained for the given weight 1 ===
# weight[index]/weight[index]
gain += 1 * profit[index]
else:
# Since the weight encountered is greater than limit, therefore take the
# required number of remaining kgs and calculate profit for it.
# weight remaining / weight[index]
gain += (max_weight - limit) / weight[index] * profit[index]
break
i += 1
return gain
if __name__ == "__main__":
print(
'''Input profits, weights, and then max_weight (all positive ints) separated by '''
'''spaces.'''
)
UpperCamelCase = [int(x) for x in input('''Input profits separated by spaces: ''').split()]
UpperCamelCase = [int(x) for x in input('''Input weights separated by spaces: ''').split()]
UpperCamelCase = int(input('''Max weight allowed: '''))
# Function Call
calc_profit(profit, weight, max_weight)
| 569 |
from ..utils import is_flax_available, is_torch_available
if is_torch_available():
from .autoencoder_kl import AutoencoderKL
from .controlnet import ControlNetModel
from .dual_transformer_ad import DualTransformeraDModel
from .modeling_utils import ModelMixin
from .prior_transformer import PriorTransformer
from .ta_film_transformer import TaFilmDecoder
from .transformer_ad import TransformeraDModel
from .unet_ad import UNetaDModel
from .unet_ad import UNetaDModel
from .unet_ad_condition import UNetaDConditionModel
from .unet_ad_condition import UNetaDConditionModel
from .vq_model import VQModel
if is_flax_available():
from .controlnet_flax import FlaxControlNetModel
from .unet_ad_condition_flax import FlaxUNetaDConditionModel
from .vae_flax import FlaxAutoencoderKL
| 569 | 1 |
'''simple docstring'''
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:
UpperCAmelCase_ : Any = False
if is_vision_available():
from PIL import Image
from transformers import PixaStructImageProcessor
class lowerCAmelCase ( unittest.TestCase):
def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=18 , __SCREAMING_SNAKE_CASE=30 , __SCREAMING_SNAKE_CASE=400 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , ) -> int:
'''simple docstring'''
__snake_case = size if size is not None else {'''height''': 20, '''width''': 20}
__snake_case = parent
__snake_case = batch_size
__snake_case = num_channels
__snake_case = image_size
__snake_case = min_resolution
__snake_case = max_resolution
__snake_case = size
__snake_case = do_normalize
__snake_case = do_convert_rgb
__snake_case = [512, 1024, 2048, 4096]
__snake_case = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}
def lowerCAmelCase ( self ) -> Union[str, Any]:
'''simple docstring'''
return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}
def lowerCAmelCase ( self ) -> str:
'''simple docstring'''
__snake_case = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
__snake_case = 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 ( __lowerCAmelCase , unittest.TestCase):
__lowercase : str = PixaStructImageProcessor if is_vision_available() else None
def lowerCAmelCase ( self ) -> Union[str, Any]:
'''simple docstring'''
__snake_case = PixaStructImageProcessingTester(self )
@property
def lowerCAmelCase ( self ) -> Dict:
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase ( self ) -> List[Any]:
'''simple docstring'''
__snake_case = 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 lowerCAmelCase ( self ) -> Optional[Any]:
'''simple docstring'''
__snake_case = self.image_processor_tester.prepare_dummy_image()
__snake_case = self.image_processing_class(**self.image_processor_dict )
__snake_case = 2048
__snake_case = image_processor(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' , max_patches=__SCREAMING_SNAKE_CASE )
self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0_606 ) , atol=1E-3 , rtol=1E-3 ) )
def lowerCAmelCase ( self ) -> int:
'''simple docstring'''
__snake_case = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__snake_case = 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
__snake_case = (
(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
__snake_case = 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
__snake_case = 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 lowerCAmelCase ( self ) -> Optional[int]:
'''simple docstring'''
__snake_case = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__snake_case = 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
__snake_case = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
__snake_case = True
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
with self.assertRaises(__SCREAMING_SNAKE_CASE ):
__snake_case = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=__SCREAMING_SNAKE_CASE ).flattened_patches
__snake_case = '''Hello'''
__snake_case = 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
__snake_case = 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 lowerCAmelCase ( self ) -> int:
'''simple docstring'''
__snake_case = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__snake_case = 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 )
__snake_case = (
(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
__snake_case = 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
__snake_case = 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 lowerCAmelCase ( self ) -> Any:
'''simple docstring'''
__snake_case = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__snake_case = 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
__snake_case = (
(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
__snake_case = 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
__snake_case = 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 ( __lowerCAmelCase , unittest.TestCase):
__lowercase : int = PixaStructImageProcessor if is_vision_available() else None
def lowerCAmelCase ( self ) -> Optional[Any]:
'''simple docstring'''
__snake_case = PixaStructImageProcessingTester(self , num_channels=4 )
__snake_case = 3
@property
def lowerCAmelCase ( self ) -> Tuple:
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase ( self ) -> Union[str, Any]:
'''simple docstring'''
__snake_case = 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 lowerCAmelCase ( self ) -> Optional[int]:
'''simple docstring'''
__snake_case = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__snake_case = 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
__snake_case = (
(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
__snake_case = 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
__snake_case = 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) , )
| 24 |
import tempfile
import numpy as np
import torch
from transformers import AutoTokenizer, TaEncoderModel
from diffusers import DDPMScheduler, UNetaDConditionModel
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.pipelines.deepfloyd_if import IFWatermarker
from diffusers.utils.testing_utils import torch_device
from ..test_pipelines_common import to_np
class lowerCAmelCase :
def UpperCAmelCase ( self :Optional[Any] ):
'''simple docstring'''
torch.manual_seed(0 )
lowercase__ = TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5" )
torch.manual_seed(0 )
lowercase__ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5" )
torch.manual_seed(0 )
lowercase__ = UNetaDConditionModel(
sample_size=32 , layers_per_block=1 , block_out_channels=[32, 64] , down_block_types=[
"ResnetDownsampleBlock2D",
"SimpleCrossAttnDownBlock2D",
] , mid_block_type="UNetMidBlock2DSimpleCrossAttn" , up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"] , in_channels=3 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type="text" , addition_embed_type_num_heads=2 , cross_attention_norm="group_norm" , resnet_time_scale_shift="scale_shift" , act_fn="gelu" , )
unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
torch.manual_seed(0 )
lowercase__ = DDPMScheduler(
num_train_timesteps=10_00 , beta_schedule="squaredcos_cap_v2" , beta_start=0.0001 , beta_end=0.02 , thresholding=_lowercase , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type="epsilon" , variance_type="learned_range" , )
torch.manual_seed(0 )
lowercase__ = IFWatermarker()
return {
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"unet": unet,
"scheduler": scheduler,
"watermarker": watermarker,
"safety_checker": None,
"feature_extractor": None,
}
def UpperCAmelCase ( self :Union[str, Any] ):
'''simple docstring'''
torch.manual_seed(0 )
lowercase__ = TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5" )
torch.manual_seed(0 )
lowercase__ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5" )
torch.manual_seed(0 )
lowercase__ = UNetaDConditionModel(
sample_size=32 , layers_per_block=[1, 2] , block_out_channels=[32, 64] , down_block_types=[
"ResnetDownsampleBlock2D",
"SimpleCrossAttnDownBlock2D",
] , mid_block_type="UNetMidBlock2DSimpleCrossAttn" , up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"] , in_channels=6 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type="text" , addition_embed_type_num_heads=2 , cross_attention_norm="group_norm" , resnet_time_scale_shift="scale_shift" , act_fn="gelu" , class_embed_type="timestep" , mid_block_scale_factor=1.414 , time_embedding_act_fn="gelu" , time_embedding_dim=32 , )
unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
torch.manual_seed(0 )
lowercase__ = DDPMScheduler(
num_train_timesteps=10_00 , beta_schedule="squaredcos_cap_v2" , beta_start=0.0001 , beta_end=0.02 , thresholding=_lowercase , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type="epsilon" , variance_type="learned_range" , )
torch.manual_seed(0 )
lowercase__ = DDPMScheduler(
num_train_timesteps=10_00 , beta_schedule="squaredcos_cap_v2" , beta_start=0.0001 , beta_end=0.02 , )
torch.manual_seed(0 )
lowercase__ = IFWatermarker()
return {
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"unet": unet,
"scheduler": scheduler,
"image_noising_scheduler": image_noising_scheduler,
"watermarker": watermarker,
"safety_checker": None,
"feature_extractor": None,
}
def UpperCAmelCase ( self :Any ):
'''simple docstring'''
lowercase__ = self.get_dummy_components()
lowercase__ = self.pipeline_class(**_lowercase )
pipe.to(_lowercase )
pipe.set_progress_bar_config(disable=_lowercase )
lowercase__ = self.get_dummy_inputs(_lowercase )
lowercase__ = inputs["prompt"]
lowercase__ = inputs["generator"]
lowercase__ = inputs["num_inference_steps"]
lowercase__ = inputs["output_type"]
if "image" in inputs:
lowercase__ = inputs["image"]
else:
lowercase__ = None
if "mask_image" in inputs:
lowercase__ = inputs["mask_image"]
else:
lowercase__ = None
if "original_image" in inputs:
lowercase__ = inputs["original_image"]
else:
lowercase__ = None
lowercase__ , lowercase__ = pipe.encode_prompt(_lowercase )
# inputs with prompt converted to embeddings
lowercase__ = {
"prompt_embeds": prompt_embeds,
"negative_prompt_embeds": negative_prompt_embeds,
"generator": generator,
"num_inference_steps": num_inference_steps,
"output_type": output_type,
}
if image is not None:
lowercase__ = image
if mask_image is not None:
lowercase__ = mask_image
if original_image is not None:
lowercase__ = original_image
# set all optional components to None
for optional_component in pipe._optional_components:
setattr(_lowercase , _lowercase , _lowercase )
lowercase__ = pipe(**_lowercase )[0]
with tempfile.TemporaryDirectory() as tmpdir:
pipe.save_pretrained(_lowercase )
lowercase__ = self.pipeline_class.from_pretrained(_lowercase )
pipe_loaded.to(_lowercase )
pipe_loaded.set_progress_bar_config(disable=_lowercase )
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
for optional_component in pipe._optional_components:
self.assertTrue(
getattr(_lowercase , _lowercase ) is None , f'''`{optional_component}` did not stay set to None after loading.''' , )
lowercase__ = self.get_dummy_inputs(_lowercase )
lowercase__ = inputs["generator"]
lowercase__ = inputs["num_inference_steps"]
lowercase__ = inputs["output_type"]
# inputs with prompt converted to embeddings
lowercase__ = {
"prompt_embeds": prompt_embeds,
"negative_prompt_embeds": negative_prompt_embeds,
"generator": generator,
"num_inference_steps": num_inference_steps,
"output_type": output_type,
}
if image is not None:
lowercase__ = image
if mask_image is not None:
lowercase__ = mask_image
if original_image is not None:
lowercase__ = original_image
lowercase__ = pipe_loaded(**_lowercase )[0]
lowercase__ = np.abs(to_np(_lowercase ) - to_np(_lowercase ) ).max()
self.assertLess(_lowercase , 1e-4 )
def UpperCAmelCase ( self :List[str] ):
'''simple docstring'''
lowercase__ = self.get_dummy_components()
lowercase__ = self.pipeline_class(**_lowercase )
pipe.to(_lowercase )
pipe.set_progress_bar_config(disable=_lowercase )
lowercase__ = self.get_dummy_inputs(_lowercase )
lowercase__ = pipe(**_lowercase )[0]
with tempfile.TemporaryDirectory() as tmpdir:
pipe.save_pretrained(_lowercase )
lowercase__ = self.pipeline_class.from_pretrained(_lowercase )
pipe_loaded.to(_lowercase )
pipe_loaded.set_progress_bar_config(disable=_lowercase )
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests
lowercase__ = self.get_dummy_inputs(_lowercase )
lowercase__ = pipe_loaded(**_lowercase )[0]
lowercase__ = np.abs(to_np(_lowercase ) - to_np(_lowercase ) ).max()
self.assertLess(_lowercase , 1e-4 )
| 655 | 0 |
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,
)
SCREAMING_SNAKE_CASE_ = pytest.mark.integration
@pytest.mark.parametrize("path", ["paws", "csv"] )
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> int:
inspect_dataset(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
a_ : Optional[Any] = path + ".py"
assert script_name in os.listdir(SCREAMING_SNAKE_CASE__ )
assert "__pycache__" not in os.listdir(SCREAMING_SNAKE_CASE__ )
@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 lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> str:
inspect_metric(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
a_ : Union[str, Any] = path + ".py"
assert script_name in os.listdir(SCREAMING_SNAKE_CASE__ )
assert "__pycache__" not in os.listdir(SCREAMING_SNAKE_CASE__ )
@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 lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> List[str]:
a_ : Any = get_dataset_config_info(SCREAMING_SNAKE_CASE__, config_name=SCREAMING_SNAKE_CASE__ )
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 lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> str:
with pytest.raises(SCREAMING_SNAKE_CASE__ ):
get_dataset_config_info(SCREAMING_SNAKE_CASE__, config_name=SCREAMING_SNAKE_CASE__ )
@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 lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> str:
a_ : Optional[Any] = get_dataset_config_names(SCREAMING_SNAKE_CASE__ )
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 lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> Any:
a_ : int = get_dataset_infos(SCREAMING_SNAKE_CASE__ )
assert list(infos.keys() ) == expected_configs
a_ : Optional[int] = expected_configs[0]
assert expected_config in infos
a_ : 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 lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> Tuple:
a_ : str = get_dataset_infos(SCREAMING_SNAKE_CASE__ )
assert expected_config in infos
a_ : List[str] = 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 lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> str:
with pytest.raises(SCREAMING_SNAKE_CASE__ ):
get_dataset_split_names(SCREAMING_SNAKE_CASE__, config_name=SCREAMING_SNAKE_CASE__ ) | 709 |
"""simple docstring"""
import unittest
from transformers import SPIECE_UNDERLINE
from transformers.models.speechta import SpeechTaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.tokenization_utils import AddedToken
from ...test_tokenization_common import TokenizerTesterMixin
SCREAMING_SNAKE_CASE_ = get_tests_dir("""fixtures/test_sentencepiece_bpe_char.model""")
@require_sentencepiece
@require_tokenizers
class snake_case_ ( a_ ,unittest.TestCase ):
__lowerCAmelCase = SpeechTaTokenizer
__lowerCAmelCase = False
__lowerCAmelCase = True
def snake_case_ ( self ):
super().setUp()
# We have a SentencePiece fixture for testing
a_ : Any = SpeechTaTokenizer(a_ )
a_ : Optional[int] = AddedToken("<mask>" , lstrip=a_ , rstrip=a_ )
a_ : Any = mask_token
tokenizer.add_special_tokens({"mask_token": mask_token} )
tokenizer.add_tokens(["<ctc_blank>"] )
tokenizer.save_pretrained(self.tmpdirname )
def snake_case_ ( self , a_ ):
a_ : Tuple = "this is a test"
a_ : Any = "this is a test"
return input_text, output_text
def snake_case_ ( self , a_ , a_=False , a_=2_0 , a_=5 ):
a_ , a_ : Optional[Any] = self.get_input_output_texts(a_ )
a_ : Optional[Any] = tokenizer.encode(a_ , add_special_tokens=a_ )
a_ : Dict = tokenizer.decode(a_ , clean_up_tokenization_spaces=a_ )
return text, ids
def snake_case_ ( self ):
a_ : List[Any] = "<pad>"
a_ : Optional[int] = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ )
def snake_case_ ( self ):
a_ : List[Any] = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<s>" )
self.assertEqual(vocab_keys[1] , "<pad>" )
self.assertEqual(vocab_keys[-4] , "œ" )
self.assertEqual(vocab_keys[-2] , "<mask>" )
self.assertEqual(vocab_keys[-1] , "<ctc_blank>" )
self.assertEqual(len(a_ ) , 8_1 )
def snake_case_ ( self ):
self.assertEqual(self.get_tokenizer().vocab_size , 7_9 )
def snake_case_ ( self ):
a_ : Any = self.get_tokenizers(do_lower_case=a_ )
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
a_ : Dict = tokenizer.vocab_size
a_ : List[str] = len(a_ )
self.assertNotEqual(a_ , 0 )
# We usually have added tokens from the start in tests because our vocab fixtures are
# smaller than the original vocabs - let's not assert this
# self.assertEqual(vocab_size, all_size)
a_ : Optional[int] = ["aaaaa bbbbbb", "cccccccccdddddddd"]
a_ : int = tokenizer.add_tokens(a_ )
a_ : List[Any] = tokenizer.vocab_size
a_ : Tuple = len(a_ )
self.assertNotEqual(a_ , 0 )
self.assertEqual(a_ , a_ )
self.assertEqual(a_ , len(a_ ) )
self.assertEqual(a_ , all_size + len(a_ ) )
a_ : str = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=a_ )
self.assertGreaterEqual(len(a_ ) , 4 )
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 )
a_ : Tuple = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"}
a_ : Dict = tokenizer.add_special_tokens(a_ )
a_ : Optional[Any] = tokenizer.vocab_size
a_ : Any = len(a_ )
self.assertNotEqual(a_ , 0 )
self.assertEqual(a_ , a_ )
self.assertEqual(a_ , len(a_ ) )
self.assertEqual(a_ , all_size_a + len(a_ ) )
a_ : Any = tokenizer.encode(
">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=a_ )
self.assertGreaterEqual(len(a_ ) , 6 )
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[0] , tokens[1] )
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[-3] , tokens[-4] )
self.assertEqual(tokens[0] , tokenizer.eos_token_id )
self.assertEqual(tokens[-3] , tokenizer.pad_token_id )
def snake_case_ ( self ):
pass
def snake_case_ ( self ):
pass
def snake_case_ ( self ):
a_ : Union[str, Any] = self.get_tokenizer()
a_ : Any = tokenizer.tokenize("This is a test" )
# fmt: off
self.assertListEqual(a_ , [SPIECE_UNDERLINE, "T", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "a", SPIECE_UNDERLINE, "t", "e", "s", "t"] )
# fmt: on
self.assertListEqual(
tokenizer.convert_tokens_to_ids(a_ ) , [4, 3_2, 1_1, 1_0, 1_2, 4, 1_0, 1_2, 4, 7, 4, 6, 5, 1_2, 6] , )
a_ : Optional[int] = tokenizer.tokenize("I was born in 92000, and this is falsé." )
self.assertListEqual(
a_ , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "92000", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] )
a_ : Tuple = tokenizer.convert_tokens_to_ids(a_ )
# fmt: off
self.assertListEqual(a_ , [4, 3_0, 4, 2_0, 7, 1_2, 4, 2_5, 8, 1_3, 9, 4, 1_0, 9, 4, 3, 2_3, 4, 7, 9, 1_4, 4, 6, 1_1, 1_0, 1_2, 4, 1_0, 1_2, 4, 1_9, 7, 1_5, 1_2, 7_3, 2_6] )
# fmt: on
a_ : Tuple = tokenizer.convert_ids_to_tokens(a_ )
self.assertListEqual(
a_ , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "<unk>", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] )
@slow
def snake_case_ ( self ):
# Use custom sequence because this tokenizer does not handle numbers.
a_ : List[Any] = [
"Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides "
"general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural "
"Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained "
"models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.",
"BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly "
"conditioning on both left and right context in all layers.",
"The quick brown fox jumps over the lazy dog.",
]
# fmt: off
a_ : Tuple = {
"input_ids": [
[4, 3_2, 1_3, 7, 9, 1_2, 1_9, 8, 1_3, 1_8, 5, 1_3, 1_2, 4, 6_4, 1_9, 8, 1_3, 1_8, 5, 1_3, 1_5, 2_2, 4, 2_8, 9, 8, 2_0, 9, 4, 7, 1_2, 4, 2_4, 2_2, 6, 8, 1_3, 1_7, 1_1, 3_9, 6, 1_3, 7, 9, 1_2, 1_9, 8, 1_3, 1_8, 5, 1_3, 1_2, 4, 7, 9, 1_4, 4, 2_4, 2_2, 6, 8, 1_3, 1_7, 1_1, 3_9, 2_4, 1_3, 5, 6, 1_3, 7, 1_0, 9, 5, 1_4, 3_9, 2_5, 5, 1_3, 6, 6_3, 4, 2_4, 1_3, 8, 2_7, 1_0, 1_4, 5, 1_2, 4, 2_1, 5, 9, 5, 1_3, 7, 1_5, 3_9, 2_4, 1_6, 1_3, 2_4, 8, 1_2, 5, 4, 7, 1_3, 1_7, 1_1, 1_0, 6, 5, 1_7, 6, 1_6, 1_3, 5, 1_2, 4, 6_4, 4_0, 4_7, 5_4, 3_2, 2_3, 4, 5_3, 4_9, 3_2, 2_3, 4, 5_4, 8, 4_0, 4_7, 5_4, 3_2, 7, 2_3, 4, 6_9, 5_2, 4_3, 2_3, 4, 5_1, 1_0, 1_2, 6, 1_0, 1_5, 4_0, 5, 1_3, 6, 2_3, 4, 6_9, 5_2, 4_8, 5, 6, 2_6, 2_6, 2_6, 6_3, 4, 1_9, 8, 1_3, 4, 4_8, 7, 6, 1_6, 1_3, 7, 1_5, 4, 5_2, 7, 9, 2_1, 1_6, 7, 2_1, 5, 4, 6_1, 9, 1_4, 5, 1_3, 1_2, 6, 7, 9, 1_4, 1_0, 9, 2_1, 4, 6_4, 4_8, 5_2, 6_1, 6_3, 4, 7, 9, 1_4, 4, 4_8, 7, 6, 1_6, 1_3, 7, 1_5, 4, 5_2, 7, 9, 2_1, 1_6, 7, 2_1, 5, 4, 5_3, 5, 9, 5, 1_3, 7, 6, 1_0, 8, 9, 4, 6_4, 4_8, 5_2, 5_3, 6_3, 4, 2_0, 1_0, 6, 1_1, 4, 8, 2_7, 5, 1_3, 4, 6, 1_1, 1_0, 1_3, 6, 2_2, 3_9, 6, 2_0, 8, 4, 2_4, 1_3, 5, 6, 1_3, 7, 1_0, 9, 5, 1_4, 4, 1_8, 8, 1_4, 5, 1_5, 1_2, 4, 1_0, 9, 4, 8, 9, 5, 4, 1_1, 1_6, 9, 1_4, 1_3, 5, 1_4, 4, 2_4, 1_5, 1_6, 1_2, 4, 1_5, 7, 9, 2_1, 1_6, 7, 2_1, 5, 1_2, 4, 7, 9, 1_4, 4, 1_4, 5, 5, 2_4, 4, 1_0, 9, 6, 5, 1_3, 8, 2_4, 5, 1_3, 7, 2_5, 1_0, 1_5, 1_0, 6, 2_2, 4, 2_5, 5, 6, 2_0, 5, 5, 9, 4, 5_8, 7, 3_7, 2_3, 4, 4_9, 2_2, 3_2, 8, 1_3, 1_7, 1_1, 4, 7, 9, 1_4, 4, 3_2, 5, 9, 1_2, 8, 1_3, 5_5, 1_5, 8, 2_0, 2_6, 2],
[4, 4_0, 4_7, 5_4, 3_2, 4, 1_0, 1_2, 4, 1_4, 5, 1_2, 1_0, 2_1, 9, 5, 1_4, 4, 6, 8, 4, 2_4, 1_3, 5, 3_9, 6, 1_3, 7, 1_0, 9, 4, 1_4, 5, 5, 2_4, 4, 2_5, 1_0, 1_4, 1_0, 1_3, 5, 1_7, 6, 1_0, 8, 9, 7, 1_5, 4, 1_3, 5, 2_4, 1_3, 5, 1_2, 5, 9, 6, 7, 6, 1_0, 8, 9, 1_2, 4, 1_9, 1_3, 8, 1_8, 4, 1_6, 9, 1_5, 7, 2_5, 5, 1_5, 5, 1_4, 4, 6, 5, 3_7, 6, 4, 2_5, 2_2, 4, 4_6, 8, 1_0, 9, 6, 1_5, 2_2, 4, 1_7, 8, 9, 1_4, 1_0, 6, 1_0, 8, 9, 1_0, 9, 2_1, 4, 8, 9, 4, 2_5, 8, 6, 1_1, 4, 1_5, 5, 1_9, 6, 4, 7, 9, 1_4, 4, 1_3, 1_0, 2_1, 1_1, 6, 4, 1_7, 8, 9, 6, 5, 3_7, 6, 4, 1_0, 9, 4, 7, 1_5, 1_5, 4, 1_5, 7, 2_2, 5, 1_3, 1_2, 2_6, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[4, 3_2, 1_1, 5, 4, 4_5, 1_6, 1_0, 1_7, 2_8, 4, 2_5, 1_3, 8, 2_0, 9, 4, 1_9, 8, 3_7, 4, 4_6, 1_6, 1_8, 2_4, 1_2, 4, 8, 2_7, 5, 1_3, 4, 6, 1_1, 5, 4, 1_5, 7, 5_7, 2_2, 4, 1_4, 8, 2_1, 2_6, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
],
"attention_mask": [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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="microsoft/speecht5_asr" , revision="c5ef64c71905caeccde0e4462ef3f9077224c524" , sequences=a_ , ) | 370 | 0 |
'''simple docstring'''
import math
def _SCREAMING_SNAKE_CASE ( __snake_case : int ):
_A = []
_A = 2
_A = int(math.sqrt(__snake_case ) ) # Size of every segment
_A = [True] * (end + 1)
_A = []
while start <= end:
if temp[start] is True:
in_prime.append(__snake_case )
for i in range(start * start , end + 1 , __snake_case ):
_A = False
start += 1
prime += in_prime
_A = end + 1
_A = min(2 * end , __snake_case )
while low <= n:
_A = [True] * (high - low + 1)
for each in in_prime:
_A = math.floor(low / each ) * each
if t < low:
t += each
for j in range(__snake_case , high + 1 , __snake_case ):
_A = False
for j in range(len(__snake_case ) ):
if temp[j] is True:
prime.append(j + low )
_A = high + 1
_A = min(high + end , __snake_case )
return prime
print(sieve(10**6))
| 107 |
'''simple docstring'''
def a_ ( lowerCamelCase : Optional[Any] ):
stooge(lowerCamelCase , 0 , len(lowerCamelCase ) - 1 )
return arr
def a_ ( lowerCamelCase : Optional[int] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Tuple ):
if i >= h:
return
# If first element is smaller than the last then swap them
if arr[i] > arr[h]:
lowerCAmelCase , lowerCAmelCase = arr[h], arr[i]
# If there are more than 2 elements in the array
if h - i + 1 > 2:
lowerCAmelCase = (int)((h - i + 1) / 3 )
# Recursively sort first 2/3 elements
stooge(lowerCamelCase , lowerCamelCase , (h - t) )
# Recursively sort last 2/3 elements
stooge(lowerCamelCase , i + t , (lowerCamelCase) )
# Recursively sort first 2/3 elements
stooge(lowerCamelCase , lowerCamelCase , (h - t) )
if __name__ == "__main__":
__snake_case =input("""Enter numbers separated by a comma:\n""").strip()
__snake_case =[int(item) for item in user_input.split(""",""")]
print(stooge_sort(unsorted))
| 133 | 0 |
'''simple docstring'''
import io
import json
import fsspec
import pytest
from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.json import JsonDatasetReader, JsonDatasetWriter
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def lowerCamelCase__ ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[Any] ):
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize('keep_in_memory' , [False, True] )
def lowerCamelCase__ ( __lowerCamelCase : List[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Any ):
'''simple docstring'''
_UpperCAmelCase : Optional[Any] =tmp_path / 'cache'
_UpperCAmelCase : Dict ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
_UpperCAmelCase : Tuple =JsonDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read()
_check_json_dataset(lowerCAmelCase__ , lowerCAmelCase__ )
@pytest.mark.parametrize(
'features' , [
None,
{'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'},
{'col_1': 'string', 'col_2': 'string', 'col_3': 'string'},
{'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'},
{'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'},
] , )
def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any] ):
'''simple docstring'''
_UpperCAmelCase : List[Any] =tmp_path / 'cache'
_UpperCAmelCase : List[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
_UpperCAmelCase : List[str] =features.copy() if features else default_expected_features
_UpperCAmelCase : Optional[int] =(
Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None
)
_UpperCAmelCase : List[Any] =JsonDatasetReader(lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read()
_check_json_dataset(lowerCAmelCase__ , lowerCAmelCase__ )
@pytest.mark.parametrize(
'features' , [
None,
{'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'},
] , )
def lowerCamelCase__ ( __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int ):
'''simple docstring'''
_UpperCAmelCase : Optional[Any] =tmp_path / 'cache'
_UpperCAmelCase : Any ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}
_UpperCAmelCase : Any =features.copy() if features else default_expected_features
_UpperCAmelCase : List[str] =(
Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None
)
_UpperCAmelCase : List[Any] =JsonDatasetReader(lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read()
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
assert dataset.num_rows == 2
assert dataset.num_columns == 3
assert dataset.column_names == ["col_3", "col_1", "col_2"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
def lowerCamelCase__ ( __lowerCamelCase : Tuple , __lowerCamelCase : Dict ):
'''simple docstring'''
_UpperCAmelCase : int ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'}
_UpperCAmelCase : Any =features.copy()
_UpperCAmelCase : List[str] =(
Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None
)
_UpperCAmelCase : Dict =tmp_path / 'cache'
_UpperCAmelCase : int =JsonDatasetReader(lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read()
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
assert dataset.num_rows == 2
assert dataset.num_columns == 3
assert dataset.column_names == ["col_2", "col_3", "col_1"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] )
def lowerCamelCase__ ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] ):
'''simple docstring'''
_UpperCAmelCase : List[Any] =tmp_path / 'cache'
_UpperCAmelCase : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
_UpperCAmelCase : int =JsonDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , split=lowerCAmelCase__ ).read()
_check_json_dataset(lowerCAmelCase__ , lowerCAmelCase__ )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize('path_type' , [str, list] )
def lowerCamelCase__ ( __lowerCamelCase : List[Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[Any] ):
'''simple docstring'''
if issubclass(lowerCAmelCase__ , lowerCAmelCase__ ):
_UpperCAmelCase : Tuple =jsonl_path
elif issubclass(lowerCAmelCase__ , lowerCAmelCase__ ):
_UpperCAmelCase : Optional[Any] =[jsonl_path]
_UpperCAmelCase : Optional[int] =tmp_path / 'cache'
_UpperCAmelCase : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
_UpperCAmelCase : Union[str, Any] =JsonDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read()
_check_json_dataset(lowerCAmelCase__ , lowerCAmelCase__ )
def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : int=("train",) ):
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
for split in splits:
_UpperCAmelCase : int =dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize('keep_in_memory' , [False, True] )
def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] ):
'''simple docstring'''
_UpperCAmelCase : Optional[int] =tmp_path / 'cache'
_UpperCAmelCase : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
_UpperCAmelCase : Optional[Any] =JsonDatasetReader({'train': jsonl_path} , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read()
_check_json_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ )
@pytest.mark.parametrize(
'features' , [
None,
{'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'},
{'col_1': 'string', 'col_2': 'string', 'col_3': 'string'},
{'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'},
{'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'},
] , )
def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : List[str] ):
'''simple docstring'''
_UpperCAmelCase : Optional[int] =tmp_path / 'cache'
_UpperCAmelCase : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
_UpperCAmelCase : List[str] =features.copy() if features else default_expected_features
_UpperCAmelCase : Dict =(
Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None
)
_UpperCAmelCase : Dict =JsonDatasetReader({'train': jsonl_path} , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read()
_check_json_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ )
@pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] )
def lowerCamelCase__ ( __lowerCamelCase : Optional[int] , __lowerCamelCase : int , __lowerCamelCase : Dict ):
'''simple docstring'''
if split:
_UpperCAmelCase : Optional[int] ={split: jsonl_path}
else:
_UpperCAmelCase : int ='train'
_UpperCAmelCase : List[Any] ={'train': jsonl_path, 'test': jsonl_path}
_UpperCAmelCase : Any =tmp_path / 'cache'
_UpperCAmelCase : Optional[int] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
_UpperCAmelCase : Dict =JsonDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read()
_check_json_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
def lowerCamelCase__ ( __lowerCamelCase : List[Any] ):
'''simple docstring'''
return json.load(lowerCAmelCase__ )
def lowerCamelCase__ ( __lowerCamelCase : Dict ):
'''simple docstring'''
return [json.loads(lowerCAmelCase__ ) for line in buffer]
class __magic_name__ :
@pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)])
def lowerCAmelCase ( self , snake_case , snake_case , snake_case) -> Union[str, Any]:
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(snake_case__ , snake_case__ , lines=snake_case__).write()
buffer.seek(0)
_UpperCAmelCase : Any =load_json_function(snake_case__)
assert isinstance(snake_case__ , snake_case__)
assert isinstance(exported_content[0] , snake_case__)
assert len(snake_case__) == 1_0
@pytest.mark.parametrize(
'orient, container, keys, len_at' , [
('records', list, {'tokens', 'labels', 'answers', 'id'}, None),
('split', dict, {'columns', 'data'}, 'data'),
('index', dict, set('0123456789'), None),
('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'),
('values', list, None, None),
('table', dict, {'schema', 'data'}, 'data'),
] , )
def lowerCAmelCase ( self , snake_case , snake_case , snake_case , snake_case , snake_case) -> int:
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(snake_case__ , snake_case__ , lines=snake_case__ , orient=snake_case__).write()
buffer.seek(0)
_UpperCAmelCase : str =load_json(snake_case__)
assert isinstance(snake_case__ , snake_case__)
if keys:
if container is dict:
assert exported_content.keys() == keys
else:
assert exported_content[0].keys() == keys
else:
assert not hasattr(snake_case__ , 'keys') and not hasattr(exported_content[0] , 'keys')
if len_at:
assert len(exported_content[len_at]) == 1_0
else:
assert len(snake_case__) == 1_0
@pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)])
def lowerCAmelCase ( self , snake_case , snake_case , snake_case) -> Union[str, Any]:
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(snake_case__ , snake_case__ , lines=snake_case__ , num_proc=2).write()
buffer.seek(0)
_UpperCAmelCase : List[Any] =load_json_function(snake_case__)
assert isinstance(snake_case__ , snake_case__)
assert isinstance(exported_content[0] , snake_case__)
assert len(snake_case__) == 1_0
@pytest.mark.parametrize(
'orient, container, keys, len_at' , [
('records', list, {'tokens', 'labels', 'answers', 'id'}, None),
('split', dict, {'columns', 'data'}, 'data'),
('index', dict, set('0123456789'), None),
('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'),
('values', list, None, None),
('table', dict, {'schema', 'data'}, 'data'),
] , )
def lowerCAmelCase ( self , snake_case , snake_case , snake_case , snake_case , snake_case) -> Dict:
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(snake_case__ , snake_case__ , lines=snake_case__ , orient=snake_case__ , num_proc=2).write()
buffer.seek(0)
_UpperCAmelCase : Union[str, Any] =load_json(snake_case__)
assert isinstance(snake_case__ , snake_case__)
if keys:
if container is dict:
assert exported_content.keys() == keys
else:
assert exported_content[0].keys() == keys
else:
assert not hasattr(snake_case__ , 'keys') and not hasattr(exported_content[0] , 'keys')
if len_at:
assert len(exported_content[len_at]) == 1_0
else:
assert len(snake_case__) == 1_0
def lowerCAmelCase ( self , snake_case) -> str:
'''simple docstring'''
with pytest.raises(snake_case__):
with io.BytesIO() as buffer:
JsonDatasetWriter(snake_case__ , snake_case__ , num_proc=0)
@pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')])
def lowerCAmelCase ( self , snake_case , snake_case , snake_case , snake_case , snake_case) -> Dict:
'''simple docstring'''
_UpperCAmelCase : int =tmp_path_factory.mktemp('data') / f"test.json.{extension}"
_UpperCAmelCase : Union[str, Any] =str(shared_datadir / f"test_file.json.{extension}")
JsonDatasetWriter(snake_case__ , snake_case__ , compression=snake_case__).write()
with fsspec.open(snake_case__ , 'rb' , compression='infer') as f:
_UpperCAmelCase : Optional[Any] =f.read()
with fsspec.open(snake_case__ , 'rb' , compression='infer') as f:
_UpperCAmelCase : Tuple =f.read()
assert exported_content == original_content
| 706 |
'''simple docstring'''
import argparse
import fairseq
import torch
from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging
logging.set_verbosity_info()
lowercase =logging.get_logger(__name__)
lowercase ={
'post_extract_proj': 'feature_projection.projection',
'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv',
'self_attn.k_proj': 'encoder.layers.*.attention.k_proj',
'self_attn.v_proj': 'encoder.layers.*.attention.v_proj',
'self_attn.q_proj': 'encoder.layers.*.attention.q_proj',
'self_attn.out_proj': 'encoder.layers.*.attention.out_proj',
'self_attn_layer_norm': 'encoder.layers.*.layer_norm',
'fc1': 'encoder.layers.*.feed_forward.intermediate_dense',
'fc2': 'encoder.layers.*.feed_forward.output_dense',
'final_layer_norm': 'encoder.layers.*.final_layer_norm',
'encoder.layer_norm': 'encoder.layer_norm',
'encoder.layer_norm_for_extract': 'layer_norm_for_extract',
'w2v_model.layer_norm': 'feature_projection.layer_norm',
'quantizer.weight_proj': 'quantizer.weight_proj',
'quantizer.vars': 'quantizer.codevectors',
'project_q': 'project_q',
'final_proj': 'project_hid',
'w2v_encoder.proj': 'lm_head',
'label_embs_concat': 'label_embeddings_concat',
'mask_emb': 'masked_spec_embed',
'spk_proj': 'speaker_proj',
}
lowercase =[
'lm_head',
'quantizer.weight_proj',
'quantizer.codevectors',
'project_q',
'project_hid',
'label_embeddings_concat',
'speaker_proj',
'layer_norm_for_extract',
]
def lowerCamelCase__ ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] ):
'''simple docstring'''
for attribute in key.split('.' ):
_UpperCAmelCase : Optional[Any] =getattr(__lowerCamelCase , __lowerCamelCase )
if weight_type is not None:
_UpperCAmelCase : List[Any] =getattr(__lowerCamelCase , __lowerCamelCase ).shape
else:
_UpperCAmelCase : Dict =hf_pointer.shape
if hf_shape != value.shape:
raise ValueError(
f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
f" {value.shape} for {full_name}" )
if weight_type == "weight":
_UpperCAmelCase : Tuple =value
elif weight_type == "weight_g":
_UpperCAmelCase : List[str] =value
elif weight_type == "weight_v":
_UpperCAmelCase : Any =value
elif weight_type == "bias":
_UpperCAmelCase : Dict =value
else:
_UpperCAmelCase : Optional[Any] =value
logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." )
def lowerCamelCase__ ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] ):
'''simple docstring'''
_UpperCAmelCase : Tuple =[]
_UpperCAmelCase : List[Any] =fairseq_model.state_dict()
_UpperCAmelCase : Union[str, Any] =hf_model.unispeech_sat.feature_extractor
for name, value in fairseq_dict.items():
_UpperCAmelCase : Optional[int] =False
if "conv_layers" in name:
load_conv_layer(
__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , hf_model.config.feat_extract_norm == 'group' , )
_UpperCAmelCase : Dict =True
else:
for key, mapped_key in MAPPING.items():
_UpperCAmelCase : str ='unispeech_sat.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]:
if "layer_norm_for_extract" in name and (".".join(name.split('.' )[:-1] ) != key):
# special case since naming is very similar
continue
_UpperCAmelCase : Optional[Any] =True
if "*" in mapped_key:
_UpperCAmelCase : List[str] =name.split(__lowerCamelCase )[0].split('.' )[-2]
_UpperCAmelCase : Any =mapped_key.replace('*' , __lowerCamelCase )
if "weight_g" in name:
_UpperCAmelCase : int ='weight_g'
elif "weight_v" in name:
_UpperCAmelCase : List[str] ='weight_v'
elif "bias" in name:
_UpperCAmelCase : Optional[int] ='bias'
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
_UpperCAmelCase : str ='weight'
else:
_UpperCAmelCase : str =None
set_recursively(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
continue
if not is_used:
unused_weights.append(__lowerCamelCase )
logger.warning(f"Unused weights: {unused_weights}" )
def lowerCamelCase__ ( __lowerCamelCase : List[Any] , __lowerCamelCase : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[Any] ):
'''simple docstring'''
_UpperCAmelCase : Dict =full_name.split('conv_layers.' )[-1]
_UpperCAmelCase : List[str] =name.split('.' )
_UpperCAmelCase : List[str] =int(items[0] )
_UpperCAmelCase : Optional[int] =int(items[1] )
if type_id == 0:
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
raise ValueError(
f"{full_name} has size {value.shape}, but"
f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." )
_UpperCAmelCase : List[str] =value
logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
raise ValueError(
f"{full_name} has size {value.shape}, but"
f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." )
_UpperCAmelCase : Union[str, Any] =value
logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
raise ValueError(
f"{full_name} has size {value.shape}, but"
f" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found." )
_UpperCAmelCase : Tuple =value
logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
f"{full_name} has size {value.shape}, but"
f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." )
_UpperCAmelCase : Tuple =value
logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." )
else:
unused_weights.append(__lowerCamelCase )
@torch.no_grad()
def lowerCamelCase__ ( __lowerCamelCase : List[str] , __lowerCamelCase : str , __lowerCamelCase : Any=None , __lowerCamelCase : List[str]=None , __lowerCamelCase : Any=True ):
'''simple docstring'''
if config_path is not None:
_UpperCAmelCase : Dict =UniSpeechSatConfig.from_pretrained(__lowerCamelCase )
else:
_UpperCAmelCase : Union[str, Any] =UniSpeechSatConfig()
_UpperCAmelCase : List[Any] =''
if is_finetuned:
_UpperCAmelCase : Union[str, Any] =UniSpeechSatForCTC(__lowerCamelCase )
else:
_UpperCAmelCase : Tuple =UniSpeechSatForPreTraining(__lowerCamelCase )
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : str =fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} )
_UpperCAmelCase : Tuple =model[0].eval()
recursively_load_weights(__lowerCamelCase , __lowerCamelCase )
hf_wavavec.save_pretrained(__lowerCamelCase )
if __name__ == "__main__":
lowercase =argparse.ArgumentParser()
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint')
parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model')
parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
parser.add_argument(
'--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not'
)
lowercase =parser.parse_args()
convert_unispeech_sat_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 331 | 0 |
"""simple docstring"""
def _A (__a , __a , __a = 0 , __a = 0 ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Union[str, Any] = right or len(__a ) - 1
if left > right:
return -1
elif list_data[left] == key:
return left
elif list_data[right] == key:
return right
else:
return search(__a , __a , left + 1 , right - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 512 |
"""simple docstring"""
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional
import datasets
import evaluate
import numpy as np
from datasets import load_dataset
import transformers
from transformers import (
AutoConfig,
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
EvalPrediction,
HfArgumentParser,
Trainer,
TrainingArguments,
default_data_collator,
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
# 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/text-classification/requirements.txt""")
UpperCAmelCase_ : str = logging.getLogger(__name__)
@dataclass
class lowerCAmelCase__ :
'''simple docstring'''
__UpperCamelCase = field(
default=1_2_8 , 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=UpperCAmelCase__ , metadata={"help": "Overwrite the cached preprocessed datasets or not."} )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={
"help": (
"Whether to pad all samples to `max_seq_length`. "
"If False, will pad the samples dynamically when batching to the maximum length in the batch."
)
} , )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of training examples to this "
"value if set."
)
} , )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
"value if set."
)
} , )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of prediction examples to this "
"value if set."
)
} , )
@dataclass
class lowerCAmelCase__ :
'''simple docstring'''
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={"help": "Evaluation language. Also train language if `train_language` is set to None."} )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={"help": "Train language if it is different from the evaluation language."} )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={"help": "arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"} , )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , )
__UpperCamelCase = field(
default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={
"help": (
"Will use the token generated when running `huggingface-cli login` (necessary to use this script "
"with private models)."
)
} , )
__UpperCamelCase = field(
default=UpperCAmelCase__ , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , )
def _A () -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : int = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = 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_xnli''' , __a )
# 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()
SCREAMING_SNAKE_CASE_ : int = training_args.get_process_log_level()
logger.setLevel(__a )
datasets.utils.logging.set_verbosity(__a )
transformers.utils.logging.set_verbosity(__a )
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.
SCREAMING_SNAKE_CASE_ : Tuple = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
SCREAMING_SNAKE_CASE_ : Union[str, 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:
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 )
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
# download the dataset.
# Downloading and loading xnli dataset from the hub.
if training_args.do_train:
if model_args.train_language is None:
SCREAMING_SNAKE_CASE_ : int = load_dataset(
'''xnli''' , model_args.language , split='''train''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
else:
SCREAMING_SNAKE_CASE_ : Any = load_dataset(
'''xnli''' , model_args.train_language , split='''train''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
SCREAMING_SNAKE_CASE_ : Optional[Any] = train_dataset.features['''label'''].names
if training_args.do_eval:
SCREAMING_SNAKE_CASE_ : Dict = load_dataset(
'''xnli''' , model_args.language , split='''validation''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
SCREAMING_SNAKE_CASE_ : Tuple = eval_dataset.features['''label'''].names
if training_args.do_predict:
SCREAMING_SNAKE_CASE_ : Optional[int] = load_dataset(
'''xnli''' , model_args.language , split='''test''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
SCREAMING_SNAKE_CASE_ : str = predict_dataset.features['''label'''].names
# Labels
SCREAMING_SNAKE_CASE_ : List[Any] = len(__a )
# Load pretrained model and tokenizer
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__a , idalabel={str(__a ): label for i, label in enumerate(__a )} , labelaid={label: i for i, label in enumerate(__a )} , finetuning_task='''xnli''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
SCREAMING_SNAKE_CASE_ : Any = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , 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 , )
SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__a , 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 , )
# Preprocessing the datasets
# Padding strategy
if data_args.pad_to_max_length:
SCREAMING_SNAKE_CASE_ : Any = '''max_length'''
else:
# We will pad later, dynamically at batch creation, to the max sequence length in each batch
SCREAMING_SNAKE_CASE_ : Union[str, Any] = False
def preprocess_function(__a ):
# Tokenize the texts
return tokenizer(
examples['''premise'''] , examples['''hypothesis'''] , padding=__a , max_length=data_args.max_seq_length , truncation=__a , )
if training_args.do_train:
if data_args.max_train_samples is not None:
SCREAMING_SNAKE_CASE_ : Optional[Any] = min(len(__a ) , data_args.max_train_samples )
SCREAMING_SNAKE_CASE_ : Optional[int] = train_dataset.select(range(__a ) )
with training_args.main_process_first(desc='''train dataset map pre-processing''' ):
SCREAMING_SNAKE_CASE_ : Union[str, Any] = train_dataset.map(
__a , batched=__a , load_from_cache_file=not data_args.overwrite_cache , desc='''Running tokenizer on train dataset''' , )
# Log a few random samples from the training set:
for index in random.sample(range(len(__a ) ) , 3 ):
logger.info(f'Sample {index} of the training set: {train_dataset[index]}.' )
if training_args.do_eval:
if data_args.max_eval_samples is not None:
SCREAMING_SNAKE_CASE_ : Dict = min(len(__a ) , data_args.max_eval_samples )
SCREAMING_SNAKE_CASE_ : str = eval_dataset.select(range(__a ) )
with training_args.main_process_first(desc='''validation dataset map pre-processing''' ):
SCREAMING_SNAKE_CASE_ : Optional[Any] = eval_dataset.map(
__a , batched=__a , load_from_cache_file=not data_args.overwrite_cache , desc='''Running tokenizer on validation dataset''' , )
if training_args.do_predict:
if data_args.max_predict_samples is not None:
SCREAMING_SNAKE_CASE_ : Dict = min(len(__a ) , data_args.max_predict_samples )
SCREAMING_SNAKE_CASE_ : List[str] = predict_dataset.select(range(__a ) )
with training_args.main_process_first(desc='''prediction dataset map pre-processing''' ):
SCREAMING_SNAKE_CASE_ : int = predict_dataset.map(
__a , batched=__a , load_from_cache_file=not data_args.overwrite_cache , desc='''Running tokenizer on prediction dataset''' , )
# Get the metric function
SCREAMING_SNAKE_CASE_ : List[str] = evaluate.load('''xnli''' )
# You can define your custom 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(__a ):
SCREAMING_SNAKE_CASE_ : Any = p.predictions[0] if isinstance(p.predictions , __a ) else p.predictions
SCREAMING_SNAKE_CASE_ : Tuple = np.argmax(__a , axis=1 )
return metric.compute(predictions=__a , references=p.label_ids )
# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
if data_args.pad_to_max_length:
SCREAMING_SNAKE_CASE_ : str = default_data_collator
elif training_args.fpaa:
SCREAMING_SNAKE_CASE_ : List[Any] = DataCollatorWithPadding(__a , pad_to_multiple_of=8 )
else:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = None
# Initialize our Trainer
SCREAMING_SNAKE_CASE_ : List[str] = Trainer(
model=__a , args=__a , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__a , tokenizer=__a , data_collator=__a , )
# Training
if training_args.do_train:
SCREAMING_SNAKE_CASE_ : List[str] = None
if training_args.resume_from_checkpoint is not None:
SCREAMING_SNAKE_CASE_ : Dict = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
SCREAMING_SNAKE_CASE_ : List[str] = last_checkpoint
SCREAMING_SNAKE_CASE_ : Any = trainer.train(resume_from_checkpoint=__a )
SCREAMING_SNAKE_CASE_ : List[Any] = train_result.metrics
SCREAMING_SNAKE_CASE_ : Union[str, Any] = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(__a )
)
SCREAMING_SNAKE_CASE_ : Optional[Any] = min(__a , len(__a ) )
trainer.save_model() # Saves the tokenizer too for easy upload
trainer.log_metrics('''train''' , __a )
trainer.save_metrics('''train''' , __a )
trainer.save_state()
# Evaluation
if training_args.do_eval:
logger.info('''*** Evaluate ***''' )
SCREAMING_SNAKE_CASE_ : List[str] = trainer.evaluate(eval_dataset=__a )
SCREAMING_SNAKE_CASE_ : List[Any] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__a )
SCREAMING_SNAKE_CASE_ : str = min(__a , len(__a ) )
trainer.log_metrics('''eval''' , __a )
trainer.save_metrics('''eval''' , __a )
# Prediction
if training_args.do_predict:
logger.info('''*** Predict ***''' )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = trainer.predict(__a , metric_key_prefix='''predict''' )
SCREAMING_SNAKE_CASE_ : List[Any] = (
data_args.max_predict_samples if data_args.max_predict_samples is not None else len(__a )
)
SCREAMING_SNAKE_CASE_ : Union[str, Any] = min(__a , len(__a ) )
trainer.log_metrics('''predict''' , __a )
trainer.save_metrics('''predict''' , __a )
SCREAMING_SNAKE_CASE_ : Any = np.argmax(__a , axis=1 )
SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join(training_args.output_dir , '''predictions.txt''' )
if trainer.is_world_process_zero():
with open(__a , '''w''' ) as writer:
writer.write('''index\tprediction\n''' )
for index, item in enumerate(__a ):
SCREAMING_SNAKE_CASE_ : str = label_list[item]
writer.write(f'{index}\t{item}\n' )
if __name__ == "__main__":
main()
| 512 | 1 |
"""simple docstring"""
import unittest
from transformers.testing_utils import require_bsa
from transformers.utils import is_bsa_available
from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin
if is_bsa_available():
from transformers import MarkupLMFeatureExtractor
class __a ( unittest.TestCase ):
def __init__( self , a__ ):
_lowerCamelCase = parent
def snake_case_ ( self ):
return {}
def SCREAMING_SNAKE_CASE_ ( ):
_lowerCamelCase = '<HTML>\n\n <HEAD>\n <TITLE>sample document</TITLE>\n </HEAD>\n\n <BODY BGCOLOR="FFFFFF">\n <HR>\n <a href="http://google.com">Goog</a>\n <H1>This is one header</H1>\n <H2>This is a another Header</H2>\n <P>Travel from\n <P>\n <B>SFO to JFK</B>\n <BR>\n <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>\n <HR>\n <div style="color:#0000FF">\n <h3>Traveler <b> name </b> is\n <p> John Doe </p>\n </div>'
_lowerCamelCase = '\n <!DOCTYPE html>\n <html>\n <body>\n\n <h1>My First Heading</h1>\n <p>My first paragraph.</p>\n\n </body>\n </html>\n '
return [html_string_a, html_string_a]
@require_bsa
class __a ( lowerCAmelCase__ , unittest.TestCase ):
SCREAMING_SNAKE_CASE__ : Tuple = MarkupLMFeatureExtractor if is_bsa_available() else None
def snake_case_ ( self ):
_lowerCamelCase = MarkupLMFeatureExtractionTester(self )
@property
def snake_case_ ( self ):
return self.feature_extract_tester.prepare_feat_extract_dict()
def snake_case_ ( self ):
# Initialize feature_extractor
_lowerCamelCase = self.feature_extraction_class()
# Test not batched input
_lowerCamelCase = get_html_strings()[0]
_lowerCamelCase = feature_extractor(a__ )
# fmt: off
_lowerCamelCase = [['sample document', 'Goog', 'This is one header', 'This is a another Header', 'Travel from', 'SFO to JFK', 'on May 2, 2015 at 2:00 pm. For details go to confirm.com', 'Traveler', 'name', 'is', 'John Doe']]
_lowerCamelCase = [['/html/head/title', '/html/body/a', '/html/body/h1', '/html/body/h2', '/html/body/p', '/html/body/p/p/b[1]', '/html/body/p/p/b[2]/i', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/b', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/p']]
# fmt: on
self.assertEqual(encoding.nodes , a__ )
self.assertEqual(encoding.xpaths , a__ )
# Test batched
_lowerCamelCase = get_html_strings()
_lowerCamelCase = feature_extractor(a__ )
# fmt: off
_lowerCamelCase = expected_nodes + [['My First Heading', 'My first paragraph.']]
_lowerCamelCase = expected_xpaths + [['/html/body/h1', '/html/body/p']]
self.assertEqual(len(encoding.nodes ) , 2 )
self.assertEqual(len(encoding.xpaths ) , 2 )
self.assertEqual(encoding.nodes , a__ )
self.assertEqual(encoding.xpaths , a__ )
| 713 |
"""simple docstring"""
from manim import *
class __a ( lowerCAmelCase__ ):
def snake_case_ ( self ):
_lowerCamelCase = Rectangle(height=0.5 , width=0.5 )
_lowerCamelCase = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 )
_lowerCamelCase = [mem.copy() for i in range(6 )]
_lowerCamelCase = [mem.copy() for i in range(6 )]
_lowerCamelCase = VGroup(*a__ ).arrange(a__ , buff=0 )
_lowerCamelCase = VGroup(*a__ ).arrange(a__ , buff=0 )
_lowerCamelCase = VGroup(a__ , a__ ).arrange(a__ , buff=0 )
_lowerCamelCase = Text('CPU' , font_size=24 )
_lowerCamelCase = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ )
cpu.move_to([-2.5, -0.5, 0] )
self.add(a__ )
_lowerCamelCase = [mem.copy() for i in range(4 )]
_lowerCamelCase = VGroup(*a__ ).arrange(a__ , buff=0 )
_lowerCamelCase = Text('GPU' , font_size=24 )
_lowerCamelCase = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ )
gpu.move_to([-1, -1, 0] )
self.add(a__ )
_lowerCamelCase = [mem.copy() for i in range(6 )]
_lowerCamelCase = VGroup(*a__ ).arrange(a__ , buff=0 )
_lowerCamelCase = Text('Model' , font_size=24 )
_lowerCamelCase = Group(a__ , a__ ).arrange(a__ , buff=0.5 , aligned_edge=a__ )
model.move_to([3, -1.0, 0] )
self.add(a__ )
_lowerCamelCase = []
for i, rect in enumerate(a__ ):
rect.set_stroke(a__ )
# target = fill.copy().set_fill(YELLOW, opacity=0.7)
# target.move_to(rect)
# self.add(target)
_lowerCamelCase = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(a__ , opacity=0.7 )
if i == 0:
cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=a__ )
cpu_target.set_x(cpu_target.get_x() + 0.1 )
elif i == 3:
cpu_target.next_to(cpu_targs[0] , direction=a__ , buff=0.0 )
else:
cpu_target.next_to(cpu_targs[i - 1] , direction=a__ , buff=0.0 )
self.add(a__ )
cpu_targs.append(a__ )
_lowerCamelCase = [mem.copy() for i in range(6 )]
_lowerCamelCase = VGroup(*a__ ).arrange(a__ , buff=0 )
_lowerCamelCase = Text('Loaded Checkpoint' , font_size=24 )
_lowerCamelCase = Group(a__ , a__ ).arrange(a__ , aligned_edge=a__ , buff=0.4 )
checkpoint.move_to([3, 0.5, 0] )
_lowerCamelCase = Square(side_length=2.2 )
key.move_to([-5, 2, 0] )
_lowerCamelCase = MarkupText(
F'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , )
key_text.move_to([-5, 2.4, 0] )
self.add(a__ , a__ )
_lowerCamelCase = MarkupText(
F'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint' , font_size=18 , )
blue_text.next_to(a__ , DOWN * 2.4 , aligned_edge=key_text.get_left() )
_lowerCamelCase = MarkupText(
F'Next, a <i><span fgcolor="{BLUE}">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor="{BLUE}">single shard</span>.' , font_size=24 , )
step_a.move_to([2, 2, 0] )
self.play(Write(a__ ) , Write(a__ ) )
self.play(Write(a__ , run_time=1 ) , Create(a__ , run_time=1 ) )
_lowerCamelCase = []
_lowerCamelCase = []
for i, rect in enumerate(a__ ):
_lowerCamelCase = fill.copy().set_fill(a__ , opacity=0.7 )
target.move_to(a__ )
first_animations.append(GrowFromCenter(a__ , run_time=1 ) )
_lowerCamelCase = target.copy()
cpu_target.generate_target()
if i < 5:
cpu_target.target.move_to(cpu_left_col_base[i + 1] )
else:
cpu_target.target.move_to(cpu_right_col_base[i - 5] )
second_animations.append(MoveToTarget(a__ , run_time=1.5 ) )
self.play(*a__ )
self.play(*a__ )
self.wait()
| 222 | 0 |
from collections import defaultdict
from math import gcd
def A_ ( _UpperCAmelCase = 1_50_00_00 ):
SCREAMING_SNAKE_CASE_: defaultdict = defaultdict(_UpperCAmelCase )
SCREAMING_SNAKE_CASE_: Any = 2
while 2 * euclid_m * (euclid_m + 1) <= limit:
for euclid_n in range((euclid_m % 2) + 1 , _UpperCAmelCase , 2 ):
if gcd(_UpperCAmelCase , _UpperCAmelCase ) > 1:
continue
SCREAMING_SNAKE_CASE_: str = 2 * euclid_m * (euclid_m + euclid_n)
for perimeter in range(_UpperCAmelCase , limit + 1 , _UpperCAmelCase ):
frequencies[perimeter] += 1
euclid_m += 1
return sum(1 for frequency in frequencies.values() if frequency == 1 )
if __name__ == "__main__":
print(f'''{solution() = }''')
| 671 |
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 rescale, resize, to_channel_dimension_format
from ...image_utils import (
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
lowerCAmelCase : Dict = logging.get_logger(__name__)
def A_ ( _UpperCAmelCase , _UpperCAmelCase ):
SCREAMING_SNAKE_CASE_: Optional[int] = b.T
SCREAMING_SNAKE_CASE_: Dict = np.sum(np.square(_UpperCAmelCase ) , axis=1 )
SCREAMING_SNAKE_CASE_: Tuple = np.sum(np.square(_UpperCAmelCase ) , axis=0 )
SCREAMING_SNAKE_CASE_: List[Any] = np.matmul(_UpperCAmelCase , _UpperCAmelCase )
SCREAMING_SNAKE_CASE_: Dict = aa[:, None] - 2 * ab + ba[None, :]
return d
def A_ ( _UpperCAmelCase , _UpperCAmelCase ):
SCREAMING_SNAKE_CASE_: int = x.reshape(-1 , 3 )
SCREAMING_SNAKE_CASE_: Tuple = squared_euclidean_distance(_UpperCAmelCase , _UpperCAmelCase )
return np.argmin(_UpperCAmelCase , axis=1 )
class __lowercase ( UpperCAmelCase_ ):
"""simple docstring"""
_UpperCAmelCase : int = ['''pixel_values''']
def __init__( self : Tuple , lowerCAmelCase__ : Optional[Union[List[List[int]], np.ndarray]] = None , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : Dict[str, int] = None , lowerCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : bool = True , **lowerCAmelCase__ : List[str] , ):
super().__init__(**lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Any = size if size is not None else {"height": 256, "width": 256}
SCREAMING_SNAKE_CASE_: Tuple = get_size_dict(lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Tuple = np.array(lowerCAmelCase__) if clusters is not None else None
SCREAMING_SNAKE_CASE_: Dict = do_resize
SCREAMING_SNAKE_CASE_: str = size
SCREAMING_SNAKE_CASE_: List[Any] = resample
SCREAMING_SNAKE_CASE_: Optional[int] = do_normalize
SCREAMING_SNAKE_CASE_: Dict = do_color_quantize
def _SCREAMING_SNAKE_CASE ( self : List[str] , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Dict[str, int] , lowerCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase__ : Optional[Any] , ):
SCREAMING_SNAKE_CASE_: List[str] = get_size_dict(lowerCAmelCase__)
if "height" not in size or "width" not in size:
raise ValueError(F"Size dictionary must contain both height and width keys. Got {size.keys()}")
return resize(
lowerCAmelCase__ , size=(size["height"], size["width"]) , resample=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__)
def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , ):
SCREAMING_SNAKE_CASE_: str = rescale(image=lowerCAmelCase__ , scale=1 / 127.5 , data_format=lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Optional[int] = image - 1
return image
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : ImageInput , lowerCAmelCase__ : bool = None , lowerCAmelCase__ : Dict[str, int] = None , lowerCAmelCase__ : PILImageResampling = None , lowerCAmelCase__ : bool = None , lowerCAmelCase__ : Optional[bool] = None , lowerCAmelCase__ : Optional[Union[List[List[int]], np.ndarray]] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **lowerCAmelCase__ : Union[str, Any] , ):
SCREAMING_SNAKE_CASE_: Tuple = do_resize if do_resize is not None else self.do_resize
SCREAMING_SNAKE_CASE_: Optional[int] = size if size is not None else self.size
SCREAMING_SNAKE_CASE_: Dict = get_size_dict(lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: List[str] = resample if resample is not None else self.resample
SCREAMING_SNAKE_CASE_: int = do_normalize if do_normalize is not None else self.do_normalize
SCREAMING_SNAKE_CASE_: List[str] = do_color_quantize if do_color_quantize is not None else self.do_color_quantize
SCREAMING_SNAKE_CASE_: Tuple = clusters if clusters is not None else self.clusters
SCREAMING_SNAKE_CASE_: Optional[int] = np.array(lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: Optional[int] = make_list_of_images(lowerCAmelCase__)
if not valid_images(lowerCAmelCase__):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray.")
if do_resize and size is None or resample is None:
raise ValueError("Size and resample must be specified if do_resize is True.")
if do_color_quantize and clusters is None:
raise ValueError("Clusters must be specified if do_color_quantize is True.")
# All transformations expect numpy arrays.
SCREAMING_SNAKE_CASE_: Union[str, Any] = [to_numpy_array(lowerCAmelCase__) for image in images]
if do_resize:
SCREAMING_SNAKE_CASE_: Optional[Any] = [self.resize(image=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__) for image in images]
if do_normalize:
SCREAMING_SNAKE_CASE_: str = [self.normalize(image=lowerCAmelCase__) for image in images]
if do_color_quantize:
SCREAMING_SNAKE_CASE_: Any = [to_channel_dimension_format(lowerCAmelCase__ , ChannelDimension.LAST) for image in images]
# color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
SCREAMING_SNAKE_CASE_: List[Any] = np.array(lowerCAmelCase__)
SCREAMING_SNAKE_CASE_: List[str] = color_quantize(lowerCAmelCase__ , lowerCAmelCase__).reshape(images.shape[:-1])
# flatten to (batch_size, height*width)
SCREAMING_SNAKE_CASE_: str = images.shape[0]
SCREAMING_SNAKE_CASE_: Tuple = images.reshape(lowerCAmelCase__ , -1)
# We need to convert back to a list of images to keep consistent behaviour across processors.
SCREAMING_SNAKE_CASE_: str = list(lowerCAmelCase__)
else:
SCREAMING_SNAKE_CASE_: Dict = [to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__) for image in images]
SCREAMING_SNAKE_CASE_: Optional[Any] = {"input_ids": images}
return BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__)
| 671 | 1 |
import collections.abc
from typing import Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_poolformer import PoolFormerConfig
_snake_case = logging.get_logger(__name__)
# General docstring
_snake_case = '''PoolFormerConfig'''
# Base docstring
_snake_case = '''sail/poolformer_s12'''
_snake_case = [1, 5_12, 7, 7]
# Image classification docstring
_snake_case = '''sail/poolformer_s12'''
_snake_case = '''tabby, tabby cat'''
_snake_case = [
'''sail/poolformer_s12''',
# See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]
def lowerCamelCase_ ( A : Optional[Any] , A : float = 0.0 , A : bool = False ):
"""simple docstring"""
if drop_prob == 0.0 or not training:
return input
lowerCAmelCase_ = 1 - drop_prob
lowerCAmelCase_ = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
lowerCAmelCase_ = keep_prob + torch.rand(UpperCAmelCase__ , dtype=input.dtype , device=input.device )
random_tensor.floor_() # binarize
lowerCAmelCase_ = input.div(UpperCAmelCase__ ) * random_tensor
return output
class UpperCamelCase_ ( nn.Module ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase = None):
super().__init__()
lowerCAmelCase_ = drop_prob
def lowercase__ ( self , _UpperCAmelCase):
return drop_path(__lowerCAmelCase , self.drop_prob , self.training)
def lowercase__ ( self):
return "p={}".format(self.drop_prob)
class UpperCamelCase_ ( nn.Module ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None):
super().__init__()
lowerCAmelCase_ = patch_size if isinstance(__lowerCAmelCase , collections.abc.Iterable) else (patch_size, patch_size)
lowerCAmelCase_ = stride if isinstance(__lowerCAmelCase , collections.abc.Iterable) else (stride, stride)
lowerCAmelCase_ = padding if isinstance(__lowerCAmelCase , collections.abc.Iterable) else (padding, padding)
lowerCAmelCase_ = nn.Convad(__lowerCAmelCase , __lowerCAmelCase , kernel_size=__lowerCAmelCase , stride=__lowerCAmelCase , padding=__lowerCAmelCase)
lowerCAmelCase_ = norm_layer(__lowerCAmelCase) if norm_layer else nn.Identity()
def lowercase__ ( self , _UpperCAmelCase):
lowerCAmelCase_ = self.projection(__lowerCAmelCase)
lowerCAmelCase_ = self.norm(__lowerCAmelCase)
return embeddings
class UpperCamelCase_ ( nn.GroupNorm ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase , **_UpperCAmelCase):
super().__init__(1 , __lowerCAmelCase , **__lowerCAmelCase)
class UpperCamelCase_ ( nn.Module ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase):
super().__init__()
lowerCAmelCase_ = nn.AvgPoolad(__lowerCAmelCase , stride=1 , padding=pool_size // 2 , count_include_pad=__lowerCAmelCase)
def lowercase__ ( self , _UpperCAmelCase):
return self.pool(__lowerCAmelCase) - hidden_states
class UpperCamelCase_ ( nn.Module ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase):
super().__init__()
lowerCAmelCase_ = nn.Convad(__lowerCAmelCase , __lowerCAmelCase , 1)
lowerCAmelCase_ = nn.Convad(__lowerCAmelCase , __lowerCAmelCase , 1)
lowerCAmelCase_ = PoolFormerDropPath(__lowerCAmelCase)
if isinstance(config.hidden_act , __lowerCAmelCase):
lowerCAmelCase_ = ACTaFN[config.hidden_act]
else:
lowerCAmelCase_ = config.hidden_act
def lowercase__ ( self , _UpperCAmelCase):
lowerCAmelCase_ = self.conva(__lowerCAmelCase)
lowerCAmelCase_ = self.act_fn(__lowerCAmelCase)
lowerCAmelCase_ = self.drop(__lowerCAmelCase)
lowerCAmelCase_ = self.conva(__lowerCAmelCase)
lowerCAmelCase_ = self.drop(__lowerCAmelCase)
return hidden_states
class UpperCamelCase_ ( nn.Module ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase):
super().__init__()
lowerCAmelCase_ = PoolFormerPooling(__lowerCAmelCase)
lowerCAmelCase_ = PoolFormerOutput(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase)
lowerCAmelCase_ = PoolFormerGroupNorm(__lowerCAmelCase)
lowerCAmelCase_ = PoolFormerGroupNorm(__lowerCAmelCase)
# Useful for training neural nets
lowerCAmelCase_ = PoolFormerDropPath(__lowerCAmelCase) if drop_path > 0.0 else nn.Identity()
lowerCAmelCase_ = config.use_layer_scale
if config.use_layer_scale:
lowerCAmelCase_ = nn.Parameter(
config.layer_scale_init_value * torch.ones((__lowerCAmelCase)) , requires_grad=__lowerCAmelCase)
lowerCAmelCase_ = nn.Parameter(
config.layer_scale_init_value * torch.ones((__lowerCAmelCase)) , requires_grad=__lowerCAmelCase)
def lowercase__ ( self , _UpperCAmelCase):
if self.use_layer_scale:
lowerCAmelCase_ = self.pooling(self.before_norm(__lowerCAmelCase))
lowerCAmelCase_ = self.layer_scale_a.unsqueeze(-1).unsqueeze(-1) * pooling_output
# First residual connection
lowerCAmelCase_ = hidden_states + self.drop_path(__lowerCAmelCase)
lowerCAmelCase_ = ()
lowerCAmelCase_ = self.output(self.after_norm(__lowerCAmelCase))
lowerCAmelCase_ = self.layer_scale_a.unsqueeze(-1).unsqueeze(-1) * layer_output
# Second residual connection
lowerCAmelCase_ = hidden_states + self.drop_path(__lowerCAmelCase)
lowerCAmelCase_ = (output,) + outputs
return outputs
else:
lowerCAmelCase_ = self.drop_path(self.pooling(self.before_norm(__lowerCAmelCase)))
# First residual connection
lowerCAmelCase_ = pooling_output + hidden_states
lowerCAmelCase_ = ()
# Second residual connection inside the PoolFormerOutput block
lowerCAmelCase_ = self.drop_path(self.output(self.after_norm(__lowerCAmelCase)))
lowerCAmelCase_ = hidden_states + layer_output
lowerCAmelCase_ = (output,) + outputs
return outputs
class UpperCamelCase_ ( nn.Module ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase):
super().__init__()
lowerCAmelCase_ = config
# stochastic depth decay rule
lowerCAmelCase_ = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths))]
# patch embeddings
lowerCAmelCase_ = []
for i in range(config.num_encoder_blocks):
embeddings.append(
PoolFormerEmbeddings(
patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ))
lowerCAmelCase_ = nn.ModuleList(__lowerCAmelCase)
# Transformer blocks
lowerCAmelCase_ = []
lowerCAmelCase_ = 0
for i in range(config.num_encoder_blocks):
# each block consists of layers
lowerCAmelCase_ = []
if i != 0:
cur += config.depths[i - 1]
for j in range(config.depths[i]):
layers.append(
PoolFormerLayer(
__lowerCAmelCase , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio) , drop_path=dpr[cur + j] , ))
blocks.append(nn.ModuleList(__lowerCAmelCase))
lowerCAmelCase_ = nn.ModuleList(__lowerCAmelCase)
def lowercase__ ( self , _UpperCAmelCase , _UpperCAmelCase=False , _UpperCAmelCase=True):
lowerCAmelCase_ = () if output_hidden_states else None
lowerCAmelCase_ = pixel_values
for idx, layers in enumerate(zip(self.patch_embeddings , self.block)):
lowerCAmelCase_ , lowerCAmelCase_ = layers
# Get patch embeddings from hidden_states
lowerCAmelCase_ = embedding_layer(__lowerCAmelCase)
# Send the embeddings through the blocks
for _, blk in enumerate(__lowerCAmelCase):
lowerCAmelCase_ = blk(__lowerCAmelCase)
lowerCAmelCase_ = layer_outputs[0]
if output_hidden_states:
lowerCAmelCase_ = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
return BaseModelOutputWithNoAttention(last_hidden_state=__lowerCAmelCase , hidden_states=__lowerCAmelCase)
class UpperCamelCase_ ( UpperCAmelCase__ ):
'''simple docstring'''
a :str = PoolFormerConfig
a :List[str] = 'poolformer'
a :Union[str, Any] = 'pixel_values'
a :Tuple = True
def lowercase__ ( self , _UpperCAmelCase):
if isinstance(__lowerCAmelCase , (nn.Linear, nn.Convad)):
module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(__lowerCAmelCase , nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
def lowercase__ ( self , _UpperCAmelCase , _UpperCAmelCase=False):
if isinstance(__lowerCAmelCase , __lowerCAmelCase):
lowerCAmelCase_ = value
_snake_case = r'''
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.
Parameters:
config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''
_snake_case = r'''
Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
[`PoolFormerImageProcessor.__call__`] for details.
'''
@add_start_docstrings(
'The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.' , UpperCAmelCase__ , )
class UpperCamelCase_ ( UpperCAmelCase__ ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase):
super().__init__(__lowerCAmelCase)
lowerCAmelCase_ = config
lowerCAmelCase_ = PoolFormerEncoder(__lowerCAmelCase)
# Initialize weights and apply final processing
self.post_init()
def lowercase__ ( self):
return self.embeddings.patch_embeddings
@add_start_docstrings_to_model_forward(__lowerCAmelCase)
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC , output_type=__lowerCAmelCase , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , )
def lowercase__ ( self , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , ):
lowerCAmelCase_ = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
lowerCAmelCase_ = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError('''You have to specify pixel_values''')
lowerCAmelCase_ = self.encoder(
__lowerCAmelCase , output_hidden_states=__lowerCAmelCase , return_dict=__lowerCAmelCase , )
lowerCAmelCase_ = encoder_outputs[0]
if not return_dict:
return (sequence_output, None) + encoder_outputs[1:]
return BaseModelOutputWithNoAttention(
last_hidden_state=__lowerCAmelCase , hidden_states=encoder_outputs.hidden_states , )
class UpperCamelCase_ ( nn.Module ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase):
super().__init__()
lowerCAmelCase_ = nn.Linear(config.hidden_size , config.hidden_size)
def lowercase__ ( self , _UpperCAmelCase):
lowerCAmelCase_ = self.dense(__lowerCAmelCase)
return output
@add_start_docstrings(
'\n PoolFormer Model transformer with an image classification head on top\n ' , UpperCAmelCase__ , )
class UpperCamelCase_ ( UpperCAmelCase__ ):
'''simple docstring'''
def __init__( self , _UpperCAmelCase):
super().__init__(__lowerCAmelCase)
lowerCAmelCase_ = config.num_labels
lowerCAmelCase_ = PoolFormerModel(__lowerCAmelCase)
# Final norm
lowerCAmelCase_ = PoolFormerGroupNorm(config.hidden_sizes[-1])
# Classifier head
lowerCAmelCase_ = (
nn.Linear(config.hidden_sizes[-1] , config.num_labels) if config.num_labels > 0 else nn.Identity()
)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(__lowerCAmelCase)
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__lowerCAmelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
def lowercase__ ( self , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , ):
lowerCAmelCase_ = return_dict if return_dict is not None else self.config.use_return_dict
lowerCAmelCase_ = self.poolformer(
__lowerCAmelCase , output_hidden_states=__lowerCAmelCase , return_dict=__lowerCAmelCase , )
lowerCAmelCase_ = outputs[0]
lowerCAmelCase_ = self.classifier(self.norm(__lowerCAmelCase).mean([-2, -1]))
lowerCAmelCase_ = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
lowerCAmelCase_ = '''regression'''
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
lowerCAmelCase_ = '''single_label_classification'''
else:
lowerCAmelCase_ = '''multi_label_classification'''
if self.config.problem_type == "regression":
lowerCAmelCase_ = MSELoss()
if self.num_labels == 1:
lowerCAmelCase_ = loss_fct(logits.squeeze() , labels.squeeze())
else:
lowerCAmelCase_ = loss_fct(__lowerCAmelCase , __lowerCAmelCase)
elif self.config.problem_type == "single_label_classification":
lowerCAmelCase_ = CrossEntropyLoss()
lowerCAmelCase_ = loss_fct(logits.view(-1 , self.num_labels) , labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
lowerCAmelCase_ = BCEWithLogitsLoss()
lowerCAmelCase_ = loss_fct(__lowerCAmelCase , __lowerCAmelCase)
if not return_dict:
lowerCAmelCase_ = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutputWithNoAttention(loss=__lowerCAmelCase , logits=__lowerCAmelCase , hidden_states=outputs.hidden_states)
| 710 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
_snake_case = {
"configuration_lxmert": ["LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LxmertConfig"],
"tokenization_lxmert": ["LxmertTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_snake_case = ["LxmertTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_snake_case = [
"LxmertEncoder",
"LxmertForPreTraining",
"LxmertForQuestionAnswering",
"LxmertModel",
"LxmertPreTrainedModel",
"LxmertVisualFeatureEncoder",
"LxmertXLayer",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_snake_case = [
"TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFLxmertForPreTraining",
"TFLxmertMainLayer",
"TFLxmertModel",
"TFLxmertPreTrainedModel",
"TFLxmertVisualFeatureEncoder",
]
if TYPE_CHECKING:
from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig
from .tokenization_lxmert import LxmertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_lxmert_fast import LxmertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_lxmert import (
LxmertEncoder,
LxmertForPreTraining,
LxmertForQuestionAnswering,
LxmertModel,
LxmertPreTrainedModel,
LxmertVisualFeatureEncoder,
LxmertXLayer,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_lxmert import (
TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFLxmertForPreTraining,
TFLxmertMainLayer,
TFLxmertModel,
TFLxmertPreTrainedModel,
TFLxmertVisualFeatureEncoder,
)
else:
import sys
_snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 413 | 0 |
'''simple docstring'''
import warnings
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class __a ( _snake_case ):
__UpperCamelCase : Dict = ['image_processor', 'tokenizer']
__UpperCamelCase : Any = 'ViltImageProcessor'
__UpperCamelCase : List[str] = ('BertTokenizer', 'BertTokenizerFast')
def __init__( self : Dict ,lowerCamelCase : Union[str, Any]=None ,lowerCamelCase : List[Any]=None ,**lowerCamelCase : Tuple ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = None
if "feature_extractor" in kwargs:
warnings.warn(
"""The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
""" instead.""" ,lowerCamelCase ,)
__SCREAMING_SNAKE_CASE = kwargs.pop("""feature_extractor""" )
__SCREAMING_SNAKE_CASE = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("""You need to specify an `image_processor`.""" )
if tokenizer is None:
raise ValueError("""You need to specify a `tokenizer`.""" )
super().__init__(lowerCamelCase ,lowerCamelCase )
__SCREAMING_SNAKE_CASE = self.image_processor
def __call__( self : int ,lowerCamelCase : Dict ,lowerCamelCase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,lowerCamelCase : bool = True ,lowerCamelCase : Union[bool, str, PaddingStrategy] = False ,lowerCamelCase : Union[bool, str, TruncationStrategy] = None ,lowerCamelCase : Optional[int] = None ,lowerCamelCase : int = 0 ,lowerCamelCase : Optional[int] = None ,lowerCamelCase : Optional[bool] = None ,lowerCamelCase : Optional[bool] = None ,lowerCamelCase : bool = False ,lowerCamelCase : bool = False ,lowerCamelCase : bool = False ,lowerCamelCase : bool = False ,lowerCamelCase : bool = True ,lowerCamelCase : Optional[Union[str, TensorType]] = None ,**lowerCamelCase : str ,):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = self.tokenizer(
text=lowerCamelCase ,add_special_tokens=lowerCamelCase ,padding=lowerCamelCase ,truncation=lowerCamelCase ,max_length=lowerCamelCase ,stride=lowerCamelCase ,pad_to_multiple_of=lowerCamelCase ,return_token_type_ids=lowerCamelCase ,return_attention_mask=lowerCamelCase ,return_overflowing_tokens=lowerCamelCase ,return_special_tokens_mask=lowerCamelCase ,return_offsets_mapping=lowerCamelCase ,return_length=lowerCamelCase ,verbose=lowerCamelCase ,return_tensors=lowerCamelCase ,**lowerCamelCase ,)
# add pixel_values + pixel_mask
__SCREAMING_SNAKE_CASE = self.image_processor(lowerCamelCase ,return_tensors=lowerCamelCase )
encoding.update(lowerCamelCase )
return encoding
def UpperCAmelCase__ ( self : Optional[int] ,*lowerCamelCase : Any ,**lowerCamelCase : Tuple ):
'''simple docstring'''
return self.tokenizer.batch_decode(*lowerCamelCase ,**lowerCamelCase )
def UpperCAmelCase__ ( self : List[Any] ,*lowerCamelCase : Union[str, Any] ,**lowerCamelCase : List[Any] ):
'''simple docstring'''
return self.tokenizer.decode(*lowerCamelCase ,**lowerCamelCase )
@property
def UpperCAmelCase__ ( self : Any ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = self.tokenizer.model_input_names
__SCREAMING_SNAKE_CASE = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
@property
def UpperCAmelCase__ ( self : Dict ):
'''simple docstring'''
warnings.warn(
"""`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" ,lowerCamelCase ,)
return self.image_processor_class
@property
def UpperCAmelCase__ ( self : int ):
'''simple docstring'''
warnings.warn(
"""`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" ,lowerCamelCase ,)
return self.image_processor
| 109 |
"""simple docstring"""
import unittest
import numpy as np
from transformers import is_flax_available
from transformers.testing_utils import require_flax
from ..test_modeling_flax_common import ids_tensor
if is_flax_available():
import jax
import jax.numpy as jnp
from transformers.generation import (
FlaxForcedBOSTokenLogitsProcessor,
FlaxForcedEOSTokenLogitsProcessor,
FlaxLogitsProcessorList,
FlaxMinLengthLogitsProcessor,
FlaxTemperatureLogitsWarper,
FlaxTopKLogitsWarper,
FlaxTopPLogitsWarper,
)
@require_flax
class __lowerCamelCase ( unittest.TestCase ):
def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase ):
lowerCamelCase_ = jnp.ones((batch_size, length) ) / length
return scores
def UpperCAmelCase__ ( self ):
lowerCamelCase_ = None
lowerCamelCase_ = 20
lowerCamelCase_ = self._get_uniform_logits(batch_size=2 , length=UpperCAmelCase )
# tweak scores to not be uniform anymore
lowerCamelCase_ = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch
lowerCamelCase_ = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch
# compute softmax
lowerCamelCase_ = jax.nn.softmax(UpperCAmelCase , axis=-1 )
lowerCamelCase_ = FlaxTemperatureLogitsWarper(temperature=0.5 )
lowerCamelCase_ = FlaxTemperatureLogitsWarper(temperature=1.3 )
lowerCamelCase_ = jax.nn.softmax(temp_dist_warper_sharper(UpperCAmelCase , scores.copy() , cur_len=UpperCAmelCase ) , axis=-1 )
lowerCamelCase_ = jax.nn.softmax(temp_dist_warper_smoother(UpperCAmelCase , scores.copy() , cur_len=UpperCAmelCase ) , axis=-1 )
# uniform distribution stays uniform
self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) )
self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) )
# sharp peaks get higher, valleys get lower
self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() )
self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() )
# smooth peaks get lower, valleys get higher
self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() )
self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() )
def UpperCAmelCase__ ( self ):
lowerCamelCase_ = None
lowerCamelCase_ = 10
lowerCamelCase_ = 2
# create ramp distribution
lowerCamelCase_ = np.broadcast_to(np.arange(UpperCAmelCase )[None, :] , (batch_size, vocab_size) ).copy()
lowerCamelCase_ = ramp_logits[1:, : vocab_size // 2] + vocab_size
lowerCamelCase_ = FlaxTopKLogitsWarper(3 )
lowerCamelCase_ = top_k_warp(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
# check that correct tokens are filtered
self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] )
self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] )
# check special case
lowerCamelCase_ = 5
lowerCamelCase_ = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 )
lowerCamelCase_ = np.broadcast_to(np.arange(UpperCAmelCase )[None, :] , (batch_size, length) ).copy()
lowerCamelCase_ = top_k_warp_safety_check(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
# min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] )
def UpperCAmelCase__ ( self ):
lowerCamelCase_ = None
lowerCamelCase_ = 10
lowerCamelCase_ = 2
# create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
lowerCamelCase_ = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.1_5, 0.3, 0.3, 0.2_5]] ) )
lowerCamelCase_ = FlaxTopPLogitsWarper(0.8 )
lowerCamelCase_ = np.exp(top_p_warp(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase ) )
# dist should be filtered to keep min num values so that sum is >= top_p
# exp (-inf) => 0
lowerCamelCase_ = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.2_5]] )
self.assertTrue(np.allclose(UpperCAmelCase , UpperCAmelCase , atol=1e-3 ) )
# check edge cases with negative and extreme logits
lowerCamelCase_ = np.broadcast_to(np.arange(UpperCAmelCase )[None, :] , (batch_size, vocab_size) ).copy() - (
vocab_size // 2
)
# make ramp_logits more extreme
lowerCamelCase_ = ramp_logits[1] * 1_0_0.0
# make sure at least 2 tokens are kept
lowerCamelCase_ = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 )
lowerCamelCase_ = top_p_warp(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
# first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] )
def UpperCAmelCase__ ( self ):
lowerCamelCase_ = 20
lowerCamelCase_ = 4
lowerCamelCase_ = 0
lowerCamelCase_ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=UpperCAmelCase )
# check that min length is applied at length 5
lowerCamelCase_ = ids_tensor((batch_size, 20) , vocab_size=20 )
lowerCamelCase_ = 5
lowerCamelCase_ = self._get_uniform_logits(UpperCAmelCase , UpperCAmelCase )
lowerCamelCase_ = min_dist_processor(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('''inf''' )] )
# check that min length is not applied anymore at length 15
lowerCamelCase_ = self._get_uniform_logits(UpperCAmelCase , UpperCAmelCase )
lowerCamelCase_ = 15
lowerCamelCase_ = min_dist_processor(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
self.assertFalse(jnp.isinf(UpperCAmelCase ).any() )
def UpperCAmelCase__ ( self ):
lowerCamelCase_ = 20
lowerCamelCase_ = 4
lowerCamelCase_ = 0
lowerCamelCase_ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase )
# check that all scores are -inf except the bos_token_id score
lowerCamelCase_ = ids_tensor((batch_size, 1) , vocab_size=20 )
lowerCamelCase_ = 1
lowerCamelCase_ = self._get_uniform_logits(UpperCAmelCase , UpperCAmelCase )
lowerCamelCase_ = logits_processor(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() )
self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero
# check that bos_token_id is not forced if current length is greater than 1
lowerCamelCase_ = 3
lowerCamelCase_ = self._get_uniform_logits(UpperCAmelCase , UpperCAmelCase )
lowerCamelCase_ = logits_processor(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
self.assertFalse(jnp.isinf(UpperCAmelCase ).any() )
def UpperCAmelCase__ ( self ):
lowerCamelCase_ = 20
lowerCamelCase_ = 4
lowerCamelCase_ = 0
lowerCamelCase_ = 5
lowerCamelCase_ = FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase , eos_token_id=UpperCAmelCase )
# check that all scores are -inf except the eos_token_id when max_length is reached
lowerCamelCase_ = ids_tensor((batch_size, 4) , vocab_size=20 )
lowerCamelCase_ = 4
lowerCamelCase_ = self._get_uniform_logits(UpperCAmelCase , UpperCAmelCase )
lowerCamelCase_ = logits_processor(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() )
self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero
# check that eos_token_id is not forced if max_length is not reached
lowerCamelCase_ = 3
lowerCamelCase_ = self._get_uniform_logits(UpperCAmelCase , UpperCAmelCase )
lowerCamelCase_ = logits_processor(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
self.assertFalse(jnp.isinf(UpperCAmelCase ).any() )
def UpperCAmelCase__ ( self ):
lowerCamelCase_ = 4
lowerCamelCase_ = 10
lowerCamelCase_ = 15
lowerCamelCase_ = 2
lowerCamelCase_ = 1
lowerCamelCase_ = 15
# dummy input_ids and scores
lowerCamelCase_ = ids_tensor((batch_size, sequence_length) , UpperCAmelCase )
lowerCamelCase_ = input_ids.copy()
lowerCamelCase_ = self._get_uniform_logits(UpperCAmelCase , UpperCAmelCase )
lowerCamelCase_ = scores.copy()
# instantiate all dist processors
lowerCamelCase_ = FlaxTemperatureLogitsWarper(temperature=0.5 )
lowerCamelCase_ = FlaxTopKLogitsWarper(3 )
lowerCamelCase_ = FlaxTopPLogitsWarper(0.8 )
# instantiate all logits processors
lowerCamelCase_ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=UpperCAmelCase )
lowerCamelCase_ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase )
lowerCamelCase_ = FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase , eos_token_id=UpperCAmelCase )
lowerCamelCase_ = 10
# no processor list
lowerCamelCase_ = temp_dist_warp(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
lowerCamelCase_ = top_k_warp(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
lowerCamelCase_ = top_p_warp(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
lowerCamelCase_ = min_dist_proc(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
lowerCamelCase_ = bos_dist_proc(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
lowerCamelCase_ = eos_dist_proc(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
# with processor list
lowerCamelCase_ = FlaxLogitsProcessorList(
[temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] )
lowerCamelCase_ = processor(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
# scores should be equal
self.assertTrue(jnp.allclose(UpperCAmelCase , UpperCAmelCase , atol=1e-3 ) )
# input_ids should never be changed
self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
def UpperCAmelCase__ ( self ):
lowerCamelCase_ = 4
lowerCamelCase_ = 10
lowerCamelCase_ = 15
lowerCamelCase_ = 2
lowerCamelCase_ = 1
lowerCamelCase_ = 15
# dummy input_ids and scores
lowerCamelCase_ = ids_tensor((batch_size, sequence_length) , UpperCAmelCase )
lowerCamelCase_ = input_ids.copy()
lowerCamelCase_ = self._get_uniform_logits(UpperCAmelCase , UpperCAmelCase )
lowerCamelCase_ = scores.copy()
# instantiate all dist processors
lowerCamelCase_ = FlaxTemperatureLogitsWarper(temperature=0.5 )
lowerCamelCase_ = FlaxTopKLogitsWarper(3 )
lowerCamelCase_ = FlaxTopPLogitsWarper(0.8 )
# instantiate all logits processors
lowerCamelCase_ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=UpperCAmelCase )
lowerCamelCase_ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase )
lowerCamelCase_ = FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase , eos_token_id=UpperCAmelCase )
lowerCamelCase_ = 10
# no processor list
def run_no_processor_list(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ):
lowerCamelCase_ = temp_dist_warp(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
lowerCamelCase_ = top_k_warp(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
lowerCamelCase_ = top_p_warp(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
lowerCamelCase_ = min_dist_proc(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
lowerCamelCase_ = bos_dist_proc(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
lowerCamelCase_ = eos_dist_proc(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
return scores
# with processor list
def run_processor_list(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ):
lowerCamelCase_ = FlaxLogitsProcessorList(
[temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] )
lowerCamelCase_ = processor(UpperCAmelCase , UpperCAmelCase , cur_len=UpperCAmelCase )
return scores
lowerCamelCase_ = jax.jit(UpperCAmelCase )
lowerCamelCase_ = jax.jit(UpperCAmelCase )
lowerCamelCase_ = jitted_run_no_processor_list(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase )
lowerCamelCase_ = jitted_run_processor_list(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase )
# scores should be equal
self.assertTrue(jnp.allclose(UpperCAmelCase , UpperCAmelCase , atol=1e-3 ) )
# input_ids should never be changed
self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
| 29 | 0 |
import numpy as np
from PIL import Image
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : np.ndarray , __UpperCamelCase : int , __UpperCamelCase : int ) -> np.ndarray:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = np.array(__UpperCamelCase )
if arr.shape[0] != arr.shape[1]:
raise ValueError("""The input array is not a square matrix""" )
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = 0
# compute the shape of the output matrix
SCREAMING_SNAKE_CASE__ = (arr.shape[0] - size) // stride + 1
# initialize the output matrix with zeros of shape maxpool_shape
SCREAMING_SNAKE_CASE__ = np.zeros((maxpool_shape, maxpool_shape) )
while i < arr.shape[0]:
if i + size > arr.shape[0]:
# if the end of the matrix is reached, break
break
while j < arr.shape[1]:
# if the end of the matrix is reached, break
if j + size > arr.shape[1]:
break
# compute the maximum of the pooling matrix
SCREAMING_SNAKE_CASE__ = np.max(arr[i : i + size, j : j + size] )
# shift the pooling matrix by stride of column pixels
j += stride
mat_j += 1
# shift the pooling matrix by stride of row pixels
i += stride
mat_i += 1
# reset the column index to 0
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = 0
return updated_arr
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : np.ndarray , __UpperCamelCase : int , __UpperCamelCase : int ) -> np.ndarray:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = np.array(__UpperCamelCase )
if arr.shape[0] != arr.shape[1]:
raise ValueError("""The input array is not a square matrix""" )
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = 0
# compute the shape of the output matrix
SCREAMING_SNAKE_CASE__ = (arr.shape[0] - size) // stride + 1
# initialize the output matrix with zeros of shape avgpool_shape
SCREAMING_SNAKE_CASE__ = np.zeros((avgpool_shape, avgpool_shape) )
while i < arr.shape[0]:
# if the end of the matrix is reached, break
if i + size > arr.shape[0]:
break
while j < arr.shape[1]:
# if the end of the matrix is reached, break
if j + size > arr.shape[1]:
break
# compute the average of the pooling matrix
SCREAMING_SNAKE_CASE__ = int(np.average(arr[i : i + size, j : j + size] ) )
# shift the pooling matrix by stride of column pixels
j += stride
mat_j += 1
# shift the pooling matrix by stride of row pixels
i += stride
mat_i += 1
# reset the column index to 0
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = 0
return updated_arr
# Main Function
if __name__ == "__main__":
from doctest import testmod
testmod(name='''avgpooling''', verbose=True)
# Loading the image
__lowerCamelCase : List[str] = Image.open('''path_to_image''')
# Converting the image to numpy array and maxpooling, displaying the result
# Ensure that the image is a square matrix
Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()
# Converting the image to numpy array and averagepooling, displaying the result
# Ensure that the image is a square matrix
Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
| 379 | import os
__lowerCamelCase : Union[str, Any] = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 100, '''D''': 500, '''M''': 1000}
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : str ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = 0
while index < len(__UpperCamelCase ) - 1:
SCREAMING_SNAKE_CASE__ = SYMBOLS[numerals[index]]
SCREAMING_SNAKE_CASE__ = SYMBOLS[numerals[index + 1]]
if current_value < next_value:
total_value -= current_value
else:
total_value += current_value
index += 1
total_value += SYMBOLS[numerals[index]]
return total_value
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : int ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = """"""
SCREAMING_SNAKE_CASE__ = num // 10_00
numerals += m_count * "M"
num %= 10_00
SCREAMING_SNAKE_CASE__ = num // 1_00
if c_count == 9:
numerals += "CM"
c_count -= 9
elif c_count == 4:
numerals += "CD"
c_count -= 4
if c_count >= 5:
numerals += "D"
c_count -= 5
numerals += c_count * "C"
num %= 1_00
SCREAMING_SNAKE_CASE__ = num // 10
if x_count == 9:
numerals += "XC"
x_count -= 9
elif x_count == 4:
numerals += "XL"
x_count -= 4
if x_count >= 5:
numerals += "L"
x_count -= 5
numerals += x_count * "X"
num %= 10
if num == 9:
numerals += "IX"
num -= 9
elif num == 4:
numerals += "IV"
num -= 4
if num >= 5:
numerals += "V"
num -= 5
numerals += num * "I"
return numerals
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : str = "/p089_roman.txt" ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = 0
with open(os.path.dirname(__UpperCamelCase ) + roman_numerals_filename ) as filea:
SCREAMING_SNAKE_CASE__ = filea.readlines()
for line in lines:
SCREAMING_SNAKE_CASE__ = line.strip()
SCREAMING_SNAKE_CASE__ = parse_roman_numerals(__UpperCamelCase )
SCREAMING_SNAKE_CASE__ = generate_roman_numerals(__UpperCamelCase )
savings += len(__UpperCamelCase ) - len(__UpperCamelCase )
return savings
if __name__ == "__main__":
print(F"""{solution() = }""")
| 379 | 1 |
from math import ceil, sqrt
def lowerCamelCase_ ( __UpperCamelCase = 1_00_00_00 ):
A_ = 0
for outer_width in range(3 , (limit // 4) + 2 ):
if outer_width**2 > limit:
A_ = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 )
else:
A_ = 1
if (outer_width - hole_width_lower_bound) % 2:
hole_width_lower_bound += 1
answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1
return answer
if __name__ == "__main__":
print(f'''{solution() = }''') | 141 |
import argparse
import tensorflow as tf
import torch
from transformers import BertConfig, BertForMaskedLM
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertPooler,
BertSelfAttention,
BertSelfOutput,
)
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
def get_masked_lm_array(__UpperCamelCase ):
A_ = F"masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE"
A_ = tf.train.load_variable(__UpperCamelCase , __UpperCamelCase )
if "kernel" in name:
A_ = array.transpose()
return torch.from_numpy(__UpperCamelCase )
def get_encoder_array(__UpperCamelCase ):
A_ = F"encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE"
A_ = tf.train.load_variable(__UpperCamelCase , __UpperCamelCase )
if "kernel" in name:
A_ = array.transpose()
return torch.from_numpy(__UpperCamelCase )
def get_encoder_layer_array(__UpperCamelCase , __UpperCamelCase ):
A_ = F"encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE"
A_ = tf.train.load_variable(__UpperCamelCase , __UpperCamelCase )
if "kernel" in name:
A_ = array.transpose()
return torch.from_numpy(__UpperCamelCase )
def get_encoder_attention_layer_array(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
A_ = F"encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE"
A_ = tf.train.load_variable(__UpperCamelCase , __UpperCamelCase )
A_ = array.reshape(__UpperCamelCase )
if "kernel" in name:
A_ = array.transpose()
return torch.from_numpy(__UpperCamelCase )
print(F"Loading model based on config from {config_path}..." )
A_ = BertConfig.from_json_file(__UpperCamelCase )
A_ = BertForMaskedLM(__UpperCamelCase )
# Layers
for layer_index in range(0 , config.num_hidden_layers ):
A_ = model.bert.encoder.layer[layer_index]
# Self-attention
A_ = layer.attention.self
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_query_dense/kernel''' , self_attn.query.weight.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_query_dense/bias''' , self_attn.query.bias.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_key_dense/kernel''' , self_attn.key.weight.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_key_dense/bias''' , self_attn.key.bias.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_value_dense/kernel''' , self_attn.value.weight.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_value_dense/bias''' , self_attn.value.bias.data.shape )
# Self-attention Output
A_ = layer.attention.output
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_output_dense/kernel''' , self_output.dense.weight.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_output_dense/bias''' , self_output.dense.bias.data.shape )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_attention_layer_norm/gamma''' )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_attention_layer_norm/beta''' )
# Intermediate
A_ = layer.intermediate
A_ = get_encoder_layer_array(__UpperCamelCase , '''_intermediate_dense/kernel''' )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_intermediate_dense/bias''' )
# Output
A_ = layer.output
A_ = get_encoder_layer_array(__UpperCamelCase , '''_output_dense/kernel''' )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_output_dense/bias''' )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_output_layer_norm/gamma''' )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_output_layer_norm/beta''' )
# Embeddings
A_ = get_encoder_array('''_position_embedding_layer/embeddings''' )
A_ = get_encoder_array('''_type_embedding_layer/embeddings''' )
A_ = get_encoder_array('''_embedding_norm_layer/gamma''' )
A_ = get_encoder_array('''_embedding_norm_layer/beta''' )
# LM Head
A_ = model.cls.predictions.transform
A_ = get_masked_lm_array('''dense/kernel''' )
A_ = get_masked_lm_array('''dense/bias''' )
A_ = get_masked_lm_array('''layer_norm/gamma''' )
A_ = get_masked_lm_array('''layer_norm/beta''' )
A_ = get_masked_lm_array('''embedding_table''' )
# Pooling
A_ = BertPooler(config=__UpperCamelCase )
A_ = get_encoder_array('''_pooler_layer/kernel''' )
A_ = get_encoder_array('''_pooler_layer/bias''' )
# Export final model
model.save_pretrained(__UpperCamelCase )
# Integration test - should load without any errors ;)
A_ = BertForMaskedLM.from_pretrained(__UpperCamelCase )
print(new_model.eval() )
print('''Model conversion was done sucessfully!''' )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser()
parser.add_argument(
"--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow Token Dropping checkpoint path."
)
parser.add_argument(
"--bert_config_file",
type=str,
required=True,
help="The config json file corresponding to the BERT model. This specifies the model architecture.",
)
parser.add_argument(
"--pytorch_dump_path",
type=str,
required=True,
help="Path to the output PyTorch model.",
)
SCREAMING_SNAKE_CASE : str = parser.parse_args()
convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path) | 141 | 1 |
"""simple docstring"""
from typing import Any
class __UpperCAmelCase :
'''simple docstring'''
def __init__( self , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =data
_SCREAMING_SNAKE_CASE =None
class __UpperCAmelCase :
'''simple docstring'''
def __init__( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =None
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.head
while temp is not None:
print(temp.data , end=''' ''' )
_SCREAMING_SNAKE_CASE =temp.next
print()
def UpperCamelCase_ ( self , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =Node(_A )
_SCREAMING_SNAKE_CASE =self.head
_SCREAMING_SNAKE_CASE =new_node
def UpperCamelCase_ ( self , _A , _A ):
'''simple docstring'''
if node_data_a == node_data_a:
return
else:
_SCREAMING_SNAKE_CASE =self.head
while node_a is not None and node_a.data != node_data_a:
_SCREAMING_SNAKE_CASE =node_a.next
_SCREAMING_SNAKE_CASE =self.head
while node_a is not None and node_a.data != node_data_a:
_SCREAMING_SNAKE_CASE =node_a.next
if node_a is None or node_a is None:
return
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =node_a.data, node_a.data
if __name__ == "__main__":
UpperCAmelCase_ : Optional[int] = LinkedList()
for i in range(5, 0, -1):
ll.push(i)
ll.print_list()
ll.swap_nodes(1, 4)
print('''After swapping''')
ll.print_list()
| 705 |
"""simple docstring"""
from __future__ import annotations
import unittest
import numpy as np
from transformers import LayoutLMConfig, 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.models.layoutlm.modeling_tf_layoutlm import (
TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
TFLayoutLMForMaskedLM,
TFLayoutLMForQuestionAnswering,
TFLayoutLMForSequenceClassification,
TFLayoutLMForTokenClassification,
TFLayoutLMModel,
)
class __UpperCAmelCase :
'''simple docstring'''
def __init__( self , _A , _A=1_3 , _A=7 , _A=True , _A=True , _A=True , _A=True , _A=9_9 , _A=3_2 , _A=2 , _A=4 , _A=3_7 , _A="gelu" , _A=0.1 , _A=0.1 , _A=5_1_2 , _A=1_6 , _A=2 , _A=0.02 , _A=3 , _A=4 , _A=None , _A=1_0_0_0 , ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =parent
_SCREAMING_SNAKE_CASE =batch_size
_SCREAMING_SNAKE_CASE =seq_length
_SCREAMING_SNAKE_CASE =is_training
_SCREAMING_SNAKE_CASE =use_input_mask
_SCREAMING_SNAKE_CASE =use_token_type_ids
_SCREAMING_SNAKE_CASE =use_labels
_SCREAMING_SNAKE_CASE =vocab_size
_SCREAMING_SNAKE_CASE =hidden_size
_SCREAMING_SNAKE_CASE =num_hidden_layers
_SCREAMING_SNAKE_CASE =num_attention_heads
_SCREAMING_SNAKE_CASE =intermediate_size
_SCREAMING_SNAKE_CASE =hidden_act
_SCREAMING_SNAKE_CASE =hidden_dropout_prob
_SCREAMING_SNAKE_CASE =attention_probs_dropout_prob
_SCREAMING_SNAKE_CASE =max_position_embeddings
_SCREAMING_SNAKE_CASE =type_vocab_size
_SCREAMING_SNAKE_CASE =type_sequence_label_size
_SCREAMING_SNAKE_CASE =initializer_range
_SCREAMING_SNAKE_CASE =num_labels
_SCREAMING_SNAKE_CASE =num_choices
_SCREAMING_SNAKE_CASE =scope
_SCREAMING_SNAKE_CASE =range_bbox
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
# convert bbox to numpy since TF does not support item assignment
_SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length, 4] , self.range_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 =bbox[i, j, 3]
_SCREAMING_SNAKE_CASE =bbox[i, j, 1]
_SCREAMING_SNAKE_CASE =t
if bbox[i, j, 2] < bbox[i, j, 0]:
_SCREAMING_SNAKE_CASE =bbox[i, j, 2]
_SCREAMING_SNAKE_CASE =bbox[i, j, 0]
_SCREAMING_SNAKE_CASE =t
_SCREAMING_SNAKE_CASE =tf.convert_to_tensor(_A )
_SCREAMING_SNAKE_CASE =None
if self.use_input_mask:
_SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] )
_SCREAMING_SNAKE_CASE =None
if self.use_token_type_ids:
_SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
_SCREAMING_SNAKE_CASE =None
_SCREAMING_SNAKE_CASE =None
_SCREAMING_SNAKE_CASE =None
if self.use_labels:
_SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.type_sequence_label_size )
_SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.num_choices )
_SCREAMING_SNAKE_CASE =LayoutLMConfig(
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 config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCamelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =TFLayoutLMModel(config=_A )
_SCREAMING_SNAKE_CASE =model(_A , _A , attention_mask=_A , token_type_ids=_A )
_SCREAMING_SNAKE_CASE =model(_A , _A , token_type_ids=_A )
_SCREAMING_SNAKE_CASE =model(_A , _A )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) )
def UpperCamelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =TFLayoutLMForMaskedLM(config=_A )
_SCREAMING_SNAKE_CASE =model(_A , _A , attention_mask=_A , token_type_ids=_A , labels=_A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def UpperCamelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.num_labels
_SCREAMING_SNAKE_CASE =TFLayoutLMForSequenceClassification(config=_A )
_SCREAMING_SNAKE_CASE =model(_A , _A , attention_mask=_A , token_type_ids=_A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def UpperCamelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.num_labels
_SCREAMING_SNAKE_CASE =TFLayoutLMForTokenClassification(config=_A )
_SCREAMING_SNAKE_CASE =model(_A , _A , attention_mask=_A , token_type_ids=_A , labels=_A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def UpperCamelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =TFLayoutLMForQuestionAnswering(config=_A )
_SCREAMING_SNAKE_CASE =model(_A , _A , attention_mask=_A , token_type_ids=_A )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =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
) ,
) =config_and_inputs
_SCREAMING_SNAKE_CASE ={
'''input_ids''': input_ids,
'''bbox''': bbox,
'''token_type_ids''': token_type_ids,
'''attention_mask''': input_mask,
}
return config, inputs_dict
@require_tf
class __UpperCAmelCase ( _lowerCamelCase, _lowerCamelCase, unittest.TestCase ):
'''simple docstring'''
lowercase : List[Any] = (
(
TFLayoutLMModel,
TFLayoutLMForMaskedLM,
TFLayoutLMForTokenClassification,
TFLayoutLMForSequenceClassification,
TFLayoutLMForQuestionAnswering,
)
if is_tf_available()
else ()
)
lowercase : str = (
{
"feature-extraction": TFLayoutLMModel,
"fill-mask": TFLayoutLMForMaskedLM,
"text-classification": TFLayoutLMForSequenceClassification,
"token-classification": TFLayoutLMForTokenClassification,
"zero-shot": TFLayoutLMForSequenceClassification,
}
if is_tf_available()
else {}
)
lowercase : Any = False
lowercase : List[str] = True
lowercase : Optional[int] = 10
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =TFLayoutLMModelTester(self )
_SCREAMING_SNAKE_CASE =ConfigTester(self , config_class=_A , hidden_size=3_7 )
def UpperCamelCase_ ( self ):
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_A )
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*_A )
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*_A )
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*_A )
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*_A )
@slow
def UpperCamelCase_ ( self ):
'''simple docstring'''
for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_SCREAMING_SNAKE_CASE =TFLayoutLMModel.from_pretrained(_A )
self.assertIsNotNone(_A )
@unittest.skip('''Onnx compliancy broke with TF 2.10''' )
def UpperCamelCase_ ( self ):
'''simple docstring'''
pass
def _lowerCAmelCase() -> str:
# Here we prepare a batch of 2 sequences to test a LayoutLM forward pass on:
# fmt: off
_SCREAMING_SNAKE_CASE =tf.convert_to_tensor([[101,1019,1014,1016,1037,1_2849,4747,1004,1_4246,2278,5439,4524,5002,2930,2193,2930,4341,3208,1005,1055,2171,2848,1_1300,3531,102],[101,4070,4034,7020,1024,3058,1015,1013,2861,1013,6070,1_9274,2772,6205,2_7814,1_6147,1_6147,4343,2047,1_0283,1_0969,1_4389,1012,2338,102]] ) # noqa: E231
_SCREAMING_SNAKE_CASE =tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 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: E231
_SCREAMING_SNAKE_CASE =tf.convert_to_tensor([[[0,0,0,0],[423,237,440,251],[427,272,441,287],[419,115,437,129],[961,885,992,912],[256,38,330,58],[256,38,330,58],[336,42,353,57],[360,39,401,56],[360,39,401,56],[411,39,471,59],[479,41,528,59],[533,39,630,60],[67,113,134,131],[141,115,209,132],[68,149,133,166],[141,149,187,164],[195,148,287,165],[195,148,287,165],[195,148,287,165],[295,148,349,165],[441,149,492,166],[497,149,546,164],[64,201,125,218],[1000,1000,1000,1000]],[[0,0,0,0],[662,150,754,166],[665,199,742,211],[519,213,554,228],[519,213,554,228],[134,433,187,454],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[314,469,376,482],[504,684,582,706],[941,825,973,900],[941,825,973,900],[941,825,973,900],[941,825,973,900],[610,749,652,765],[130,659,168,672],[176,657,237,672],[238,657,312,672],[443,653,628,672],[443,653,628,672],[716,301,825,317],[1000,1000,1000,1000]]] ) # noqa: E231
_SCREAMING_SNAKE_CASE =tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,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: E231
# these are sequence labels (i.e. at the token level)
_SCREAMING_SNAKE_CASE =tf.convert_to_tensor([[-100,10,10,10,9,1,-100,7,7,-100,7,7,4,2,5,2,8,8,-100,-100,5,0,3,2,-100],[-100,12,12,12,-100,12,10,-100,-100,-100,-100,10,12,9,-100,-100,-100,10,10,10,9,12,-100,10,-100]] ) # noqa: E231
# fmt: on
return input_ids, attention_mask, bbox, token_type_ids, labels
@require_tf
class __UpperCAmelCase ( unittest.TestCase ):
'''simple docstring'''
@slow
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =TFLayoutLMModel.from_pretrained('''microsoft/layoutlm-base-uncased''' )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =prepare_layoutlm_batch_inputs()
# forward pass
_SCREAMING_SNAKE_CASE =model(input_ids=_A , bbox=_A , attention_mask=_A , token_type_ids=_A )
# test the sequence output on [0, :3, :3]
_SCREAMING_SNAKE_CASE =tf.convert_to_tensor(
[[0.1785, -0.1947, -0.0425], [-0.3254, -0.2807, 0.2553], [-0.5391, -0.3322, 0.3364]] , )
self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , _A , atol=1E-3 ) )
# test the pooled output on [1, :3]
_SCREAMING_SNAKE_CASE =tf.convert_to_tensor([-0.6580, -0.0214, 0.8552] )
self.assertTrue(np.allclose(outputs.pooler_output[1, :3] , _A , atol=1E-3 ) )
@slow
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =TFLayoutLMForSequenceClassification.from_pretrained('''microsoft/layoutlm-base-uncased''' , num_labels=2 )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =prepare_layoutlm_batch_inputs()
# forward pass
_SCREAMING_SNAKE_CASE =model(
input_ids=_A , bbox=_A , attention_mask=_A , token_type_ids=_A , labels=tf.convert_to_tensor([1, 1] ) , )
# test whether we get a loss as a scalar
_SCREAMING_SNAKE_CASE =outputs.loss
_SCREAMING_SNAKE_CASE =(2,)
self.assertEqual(loss.shape , _A )
# test the shape of the logits
_SCREAMING_SNAKE_CASE =outputs.logits
_SCREAMING_SNAKE_CASE =(2, 2)
self.assertEqual(logits.shape , _A )
@slow
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =TFLayoutLMForTokenClassification.from_pretrained('''microsoft/layoutlm-base-uncased''' , num_labels=1_3 )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =prepare_layoutlm_batch_inputs()
# forward pass
_SCREAMING_SNAKE_CASE =model(
input_ids=_A , bbox=_A , attention_mask=_A , token_type_ids=_A , labels=_A )
# test the shape of the logits
_SCREAMING_SNAKE_CASE =outputs.logits
_SCREAMING_SNAKE_CASE =tf.convert_to_tensor((2, 2_5, 1_3) )
self.assertEqual(logits.shape , _A )
@slow
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =TFLayoutLMForQuestionAnswering.from_pretrained('''microsoft/layoutlm-base-uncased''' )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =prepare_layoutlm_batch_inputs()
# forward pass
_SCREAMING_SNAKE_CASE =model(input_ids=_A , bbox=_A , attention_mask=_A , token_type_ids=_A )
# test the shape of the logits
_SCREAMING_SNAKE_CASE =tf.convert_to_tensor((2, 2_5) )
self.assertEqual(outputs.start_logits.shape , _A )
self.assertEqual(outputs.end_logits.shape , _A )
| 165 | 0 |
'''simple docstring'''
import inspect
import jax
import jax.lax as lax
import jax.numpy as jnp
from ..utils import add_start_docstrings
from ..utils.logging import get_logger
_A: Optional[int] = get_logger(__name__)
_A: List[Any] = r"""
Args:
input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):
Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
search or log softmax for each vocabulary token when using beam search
kwargs (`Dict[str, Any]`, *optional*):
Additional logits processor specific kwargs.
Return:
`jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.
"""
class UpperCAmelCase :
@add_start_docstrings(__A )
def __call__( self , __A , __A ):
raise NotImplementedError(
f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' )
class UpperCAmelCase :
@add_start_docstrings(__A )
def __call__( self , __A , __A ):
raise NotImplementedError(
f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' )
class UpperCAmelCase ( UpperCAmelCase_ ):
@add_start_docstrings(__A )
def __call__( self , __A , __A , __A , **__A ):
for processor in self:
__UpperCAmelCase = inspect.signature(processor.__call__ ).parameters
if len(__A ) > 3:
if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ):
raise ValueError(
f'Make sure that all the required parameters: {list(function_args.keys() )} for '
f'{processor.__class__} are passed to the logits processor.' )
__UpperCAmelCase = processor(__A , __A , __A , **__A )
else:
__UpperCAmelCase = processor(__A , __A , __A )
return scores
class UpperCAmelCase ( UpperCAmelCase_ ):
def __init__( self , __A ):
if not isinstance(__A , __A ) or not (temperature > 0):
raise ValueError(f'`temperature` has to be a strictly positive float, but is {temperature}' )
__UpperCAmelCase = temperature
def __call__( self , __A , __A , __A ):
__UpperCAmelCase = scores / self.temperature
return scores
class UpperCAmelCase ( UpperCAmelCase_ ):
def __init__( self , __A , __A = -float('Inf' ) , __A = 1 ):
if not isinstance(__A , __A ) or (top_p < 0 or top_p > 1.0):
raise ValueError(f'`top_p` has to be a float > 0 and < 1, but is {top_p}' )
if not isinstance(__A , __A ) or (min_tokens_to_keep < 1):
raise ValueError(f'`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}' )
__UpperCAmelCase = top_p
__UpperCAmelCase = filter_value
__UpperCAmelCase = min_tokens_to_keep
def __call__( self , __A , __A , __A ):
__UpperCAmelCase , __UpperCAmelCase = lax.top_k(__A , scores.shape[-1] )
__UpperCAmelCase = jnp.full_like(__A , self.filter_value )
__UpperCAmelCase = jax.nn.softmax(__A , axis=-1 ).cumsum(axis=-1 )
__UpperCAmelCase = cumulative_probs < self.top_p
# include the token that is higher than top_p as well
__UpperCAmelCase = jnp.roll(__A , 1 )
score_mask |= score_mask.at[:, 0].set(__A )
# min tokens to keep
__UpperCAmelCase = score_mask.at[:, : self.min_tokens_to_keep].set(__A )
__UpperCAmelCase = jnp.where(__A , __A , __A )
__UpperCAmelCase = jax.lax.sort_key_val(__A , __A )[-1]
return next_scores
class UpperCAmelCase ( UpperCAmelCase_ ):
def __init__( self , __A , __A = -float('Inf' ) , __A = 1 ):
if not isinstance(__A , __A ) or top_k <= 0:
raise ValueError(f'`top_k` has to be a strictly positive integer, but is {top_k}' )
__UpperCAmelCase = max(__A , __A )
__UpperCAmelCase = filter_value
def __call__( self , __A , __A , __A ):
__UpperCAmelCase , __UpperCAmelCase = scores.shape
__UpperCAmelCase = jnp.full(batch_size * vocab_size , self.filter_value )
__UpperCAmelCase = min(self.top_k , scores.shape[-1] ) # Safety check
__UpperCAmelCase , __UpperCAmelCase = lax.top_k(__A , __A )
__UpperCAmelCase = jnp.broadcast_to((jnp.arange(__A ) * vocab_size)[:, None] , (batch_size, topk) ).flatten()
__UpperCAmelCase = topk_scores.flatten()
__UpperCAmelCase = topk_indices.flatten() + shift
__UpperCAmelCase = next_scores_flat.at[topk_indices_flat].set(__A )
__UpperCAmelCase = next_scores_flat.reshape(__A , __A )
return next_scores
class UpperCAmelCase ( UpperCAmelCase_ ):
def __init__( self , __A ):
__UpperCAmelCase = bos_token_id
def __call__( self , __A , __A , __A ):
__UpperCAmelCase = jnp.full(scores.shape , -float('inf' ) )
__UpperCAmelCase = 1 - jnp.bool_(cur_len - 1 )
__UpperCAmelCase = jnp.where(__A , new_scores.at[:, self.bos_token_id].set(0 ) , __A )
return scores
class UpperCAmelCase ( UpperCAmelCase_ ):
def __init__( self , __A , __A ):
__UpperCAmelCase = max_length
__UpperCAmelCase = eos_token_id
def __call__( self , __A , __A , __A ):
__UpperCAmelCase = jnp.full(scores.shape , -float('inf' ) )
__UpperCAmelCase = 1 - jnp.bool_(cur_len - self.max_length + 1 )
__UpperCAmelCase = jnp.where(__A , new_scores.at[:, self.eos_token_id].set(0 ) , __A )
return scores
class UpperCAmelCase ( UpperCAmelCase_ ):
def __init__( self , __A , __A ):
if not isinstance(__A , __A ) or min_length < 0:
raise ValueError(f'`min_length` has to be a positive integer, but is {min_length}' )
if not isinstance(__A , __A ) or eos_token_id < 0:
raise ValueError(f'`eos_token_id` has to be a positive integer, but is {eos_token_id}' )
__UpperCAmelCase = min_length
__UpperCAmelCase = eos_token_id
def __call__( self , __A , __A , __A ):
# create boolean flag to decide if min length penalty should be applied
__UpperCAmelCase = 1 - jnp.clip(cur_len - self.min_length , 0 , 1 )
__UpperCAmelCase = jnp.where(__A , scores.at[:, self.eos_token_id].set(-float('inf' ) ) , __A )
return scores
class UpperCAmelCase ( UpperCAmelCase_ ):
def __init__( self , __A , __A ):
__UpperCAmelCase = list(__A )
__UpperCAmelCase = begin_index
def __call__( self , __A , __A , __A ):
__UpperCAmelCase = 1 - jnp.bool_(cur_len - self.begin_index )
__UpperCAmelCase = jnp.where(__A , scores.at[:, self.begin_suppress_tokens].set(-float('inf' ) ) , __A )
return scores
class UpperCAmelCase ( UpperCAmelCase_ ):
def __init__( self , __A ):
__UpperCAmelCase = list(__A )
def __call__( self , __A , __A , __A ):
__UpperCAmelCase = scores.at[..., self.suppress_tokens].set(-float('inf' ) )
return scores
class UpperCAmelCase ( UpperCAmelCase_ ):
def __init__( self , __A ):
__UpperCAmelCase = dict(__A )
# Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
# index of the array corresponds to the index of the token to be forced, for XLA compatibility.
# Indexes without forced tokens will have a negative value.
__UpperCAmelCase = jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1
for index, token in force_token_map.items():
if token is not None:
__UpperCAmelCase = force_token_array.at[index].set(__A )
__UpperCAmelCase = jnp.intaa(__A )
def __call__( self , __A , __A , __A ):
def _force_token(__A ):
__UpperCAmelCase = scores.shape[0]
__UpperCAmelCase = self.force_token_array[generation_idx]
__UpperCAmelCase = jnp.ones_like(__A , dtype=scores.dtype ) * -float('inf' )
__UpperCAmelCase = jnp.zeros((batch_size, 1) , dtype=scores.dtype )
__UpperCAmelCase = lax.dynamic_update_slice(__A , __A , (0, current_token) )
return new_scores
__UpperCAmelCase = lax.cond(
cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond(
self.force_token_array[cur_len] >= 0 , lambda: _force_token(__A ) , lambda: scores , ) , )
return scores
class UpperCAmelCase ( UpperCAmelCase_ ):
def __init__( self , __A , __A , __A ):
__UpperCAmelCase = generate_config.eos_token_id
__UpperCAmelCase = generate_config.no_timestamps_token_id
__UpperCAmelCase = generate_config.no_timestamps_token_id + 1
__UpperCAmelCase = decoder_input_length + 1
if generate_config.is_multilingual:
# room for language token and task token
self.begin_index += 2
if hasattr(__A , 'max_initial_timestamp_index' ):
__UpperCAmelCase = generate_config.max_initial_timestamp_index
else:
__UpperCAmelCase = model_config.vocab_size
if self.max_initial_timestamp_index is None:
__UpperCAmelCase = model_config.vocab_size
def __call__( self , __A , __A , __A ):
# suppress <|notimestamps|> which is handled by without_timestamps
__UpperCAmelCase = scores.at[:, self.no_timestamps_token_id].set(-float('inf' ) )
def handle_pairs(__A , __A ):
__UpperCAmelCase = jnp.where((cur_len - self.begin_index) >= 1 , __A , __A )
__UpperCAmelCase = jnp.where(
input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , __A , )
__UpperCAmelCase = jnp.where((cur_len - self.begin_index) < 2 , __A , __A )
__UpperCAmelCase = jnp.where(
input_ids_k[cur_len - 2] >= self.timestamp_begin , __A , __A , )
return jnp.where(
__A , jnp.where(
penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float('inf' ) ) , scores_k.at[: self.eos_token_id].set(-float('inf' ) ) , ) , __A , )
__UpperCAmelCase = jax.vmap(__A )(__A , __A )
__UpperCAmelCase = jnp.where(cur_len == self.begin_index , __A , __A )
__UpperCAmelCase = jnp.where(
self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , __A , )
__UpperCAmelCase = self.timestamp_begin + self.max_initial_timestamp_index
__UpperCAmelCase = jnp.where(
__A , scores.at[:, last_allowed + 1 :].set(-float('inf' ) ) , __A , )
# if sum of probability over timestamps is above any other token, sample timestamp
__UpperCAmelCase = jax.nn.log_softmax(__A , axis=-1 )
def handle_cumulative_probs(__A , __A ):
__UpperCAmelCase = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 )
__UpperCAmelCase = jnp.max(logprobs_k[: self.timestamp_begin] )
return jnp.where(
timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float('inf' ) ) , __A , )
__UpperCAmelCase = jax.vmap(__A )(__A , __A )
return scores
| 126 |
'''simple docstring'''
import warnings
from typing import List
import numpy as np
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available
class UpperCAmelCase ( UpperCAmelCase_ ):
_A : str = ["""image_processor""", """tokenizer"""]
_A : str = """OwlViTImageProcessor"""
_A : List[str] = ("""CLIPTokenizer""", """CLIPTokenizerFast""")
def __init__( self , __A=None , __A=None , **__A ):
__UpperCAmelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' , __A , )
__UpperCAmelCase = kwargs.pop('feature_extractor' )
__UpperCAmelCase = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('You need to specify an `image_processor`.' )
if tokenizer is None:
raise ValueError('You need to specify a `tokenizer`.' )
super().__init__(__A , __A )
def __call__( self , __A=None , __A=None , __A=None , __A="max_length" , __A="np" , **__A ):
if text is None and query_images is None and images is None:
raise ValueError(
'You have to specify at least one text or query image or image. All three cannot be none.' )
if text is not None:
if isinstance(__A , __A ) or (isinstance(__A , __A ) and not isinstance(text[0] , __A )):
__UpperCAmelCase = [self.tokenizer(__A , padding=__A , return_tensors=__A , **__A )]
elif isinstance(__A , __A ) and isinstance(text[0] , __A ):
__UpperCAmelCase = []
# Maximum number of queries across batch
__UpperCAmelCase = max([len(__A ) for t in text] )
# Pad all batch samples to max number of text queries
for t in text:
if len(__A ) != max_num_queries:
__UpperCAmelCase = t + [' '] * (max_num_queries - len(__A ))
__UpperCAmelCase = self.tokenizer(__A , padding=__A , return_tensors=__A , **__A )
encodings.append(__A )
else:
raise TypeError('Input text should be a string, a list of strings or a nested list of strings' )
if return_tensors == "np":
__UpperCAmelCase = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 )
__UpperCAmelCase = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 )
elif return_tensors == "jax" and is_flax_available():
import jax.numpy as jnp
__UpperCAmelCase = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 )
__UpperCAmelCase = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 )
elif return_tensors == "pt" and is_torch_available():
import torch
__UpperCAmelCase = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 )
__UpperCAmelCase = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 )
elif return_tensors == "tf" and is_tf_available():
import tensorflow as tf
__UpperCAmelCase = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 )
__UpperCAmelCase = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 )
else:
raise ValueError('Target return tensor type could not be returned' )
__UpperCAmelCase = BatchEncoding()
__UpperCAmelCase = input_ids
__UpperCAmelCase = attention_mask
if query_images is not None:
__UpperCAmelCase = BatchEncoding()
__UpperCAmelCase = self.image_processor(
__A , return_tensors=__A , **__A ).pixel_values
__UpperCAmelCase = query_pixel_values
if images is not None:
__UpperCAmelCase = self.image_processor(__A , return_tensors=__A , **__A )
if text is not None and images is not None:
__UpperCAmelCase = image_features.pixel_values
return encoding
elif query_images is not None and images is not None:
__UpperCAmelCase = image_features.pixel_values
return encoding
elif text is not None or query_images is not None:
return encoding
else:
return BatchEncoding(data=dict(**__A ) , tensor_type=__A )
def __lowerCamelCase ( self , *__A , **__A ):
return self.image_processor.post_process(*__A , **__A )
def __lowerCamelCase ( self , *__A , **__A ):
return self.image_processor.post_process_object_detection(*__A , **__A )
def __lowerCamelCase ( self , *__A , **__A ):
return self.image_processor.post_process_image_guided_detection(*__A , **__A )
def __lowerCamelCase ( self , *__A , **__A ):
return self.tokenizer.batch_decode(*__A , **__A )
def __lowerCamelCase ( self , *__A , **__A ):
return self.tokenizer.decode(*__A , **__A )
@property
def __lowerCamelCase ( self ):
warnings.warn(
'`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , __A , )
return self.image_processor_class
@property
def __lowerCamelCase ( self ):
warnings.warn(
'`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , __A , )
return self.image_processor
| 126 | 1 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers.models.xglm.modeling_tf_xglm import (
TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
TFXGLMForCausalLM,
TFXGLMModel,
)
@require_tf
class lowercase__ :
_UpperCAmelCase :Dict = XGLMConfig
_UpperCAmelCase :List[Any] = {}
_UpperCAmelCase :str = "gelu"
def __init__( self : Tuple , snake_case__ : Any , snake_case__ : int=14 , snake_case__ : Union[str, Any]=7 , snake_case__ : Tuple=True , snake_case__ : List[Any]=True , snake_case__ : Optional[int]=True , snake_case__ : int=99 , snake_case__ : Optional[Any]=32 , snake_case__ : int=2 , snake_case__ : Union[str, Any]=4 , snake_case__ : Any=37 , snake_case__ : Optional[int]="gelu" , snake_case__ : Any=0.1 , snake_case__ : Union[str, Any]=0.1 , snake_case__ : Union[str, Any]=512 , snake_case__ : Tuple=0.02 , ):
lowerCamelCase_ : Optional[Any] =parent
lowerCamelCase_ : Dict =batch_size
lowerCamelCase_ : str =seq_length
lowerCamelCase_ : Union[str, Any] =is_training
lowerCamelCase_ : int =use_input_mask
lowerCamelCase_ : List[Any] =use_labels
lowerCamelCase_ : List[Any] =vocab_size
lowerCamelCase_ : Tuple =d_model
lowerCamelCase_ : List[Any] =num_hidden_layers
lowerCamelCase_ : Optional[int] =num_attention_heads
lowerCamelCase_ : Any =ffn_dim
lowerCamelCase_ : int =activation_function
lowerCamelCase_ : List[str] =activation_dropout
lowerCamelCase_ : List[Any] =attention_dropout
lowerCamelCase_ : Union[str, Any] =max_position_embeddings
lowerCamelCase_ : Any =initializer_range
lowerCamelCase_ : Optional[Any] =None
lowerCamelCase_ : Any =0
lowerCamelCase_ : int =2
lowerCamelCase_ : Optional[Any] =1
def UpperCAmelCase__ ( self : int ):
return XGLMConfig.from_pretrained("facebook/xglm-564M" )
def UpperCAmelCase__ ( self : str ):
lowerCamelCase_ : List[str] =tf.clip_by_value(
ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 )
lowerCamelCase_ : Any =None
if self.use_input_mask:
lowerCamelCase_ : Optional[Any] =random_attention_mask([self.batch_size, self.seq_length] )
lowerCamelCase_ : Any =self.get_config()
lowerCamelCase_ : Optional[Any] =floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 )
return (
config,
input_ids,
input_mask,
head_mask,
)
def UpperCAmelCase__ ( self : Union[str, Any] ):
return XGLMConfig(
vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=snake_case__ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=snake_case__ , )
def UpperCAmelCase__ ( self : int ):
lowerCamelCase_ : Tuple =self.prepare_config_and_inputs()
(
(
lowerCamelCase_
) , (
lowerCamelCase_
) , (
lowerCamelCase_
) , (
lowerCamelCase_
) ,
) : Tuple =config_and_inputs
lowerCamelCase_ : Optional[int] ={
"input_ids": input_ids,
"head_mask": head_mask,
}
return config, inputs_dict
@require_tf
class lowercase__ ( snake_case__, snake_case__, unittest.TestCase ):
_UpperCAmelCase :Any = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
_UpperCAmelCase :str = (TFXGLMForCausalLM,) if is_tf_available() else ()
_UpperCAmelCase :int = (
{"feature-extraction": TFXGLMModel, "text-generation": TFXGLMForCausalLM} if is_tf_available() else {}
)
_UpperCAmelCase :Tuple = False
_UpperCAmelCase :Tuple = False
_UpperCAmelCase :List[Any] = False
def UpperCAmelCase__ ( self : Optional[Any] ):
lowerCamelCase_ : Dict =TFXGLMModelTester(self )
lowerCamelCase_ : List[str] =ConfigTester(self , config_class=snake_case__ , n_embd=37 )
def UpperCAmelCase__ ( self : str ):
self.config_tester.run_common_tests()
@slow
def UpperCAmelCase__ ( self : Optional[Any] ):
for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCamelCase_ : List[Any] =TFXGLMModel.from_pretrained(snake_case__ )
self.assertIsNotNone(snake_case__ )
@unittest.skip(reason="Currently, model embeddings are going to undergo a major refactor." )
def UpperCAmelCase__ ( self : Optional[int] ):
super().test_resize_token_embeddings()
@require_tf
class lowercase__ ( unittest.TestCase ):
@slow
def UpperCAmelCase__ ( self : Tuple , snake_case__ : Tuple=True ):
lowerCamelCase_ : int =TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M" )
lowerCamelCase_ : Optional[int] =tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa ) # The dog
# </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
# fmt: off
lowerCamelCase_ : List[Any] =[2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581]
# fmt: on
lowerCamelCase_ : Optional[int] =model.generate(snake_case__ , do_sample=snake_case__ , num_beams=1 )
if verify_outputs:
self.assertListEqual(output_ids[0].numpy().tolist() , snake_case__ )
@slow
def UpperCAmelCase__ ( self : Dict ):
lowerCamelCase_ : int =XGLMTokenizer.from_pretrained("facebook/xglm-564M" )
lowerCamelCase_ : str =TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M" )
tf.random.set_seed(0 )
lowerCamelCase_ : Tuple =tokenizer("Today is a nice day and" , return_tensors="tf" )
lowerCamelCase_ : Dict =tokenized.input_ids
# forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
with tf.device(":/CPU:0" ):
lowerCamelCase_ : Optional[int] =model.generate(snake_case__ , do_sample=snake_case__ , seed=[7, 0] )
lowerCamelCase_ : Any =tokenizer.decode(output_ids[0] , skip_special_tokens=snake_case__ )
lowerCamelCase_ : int =(
"Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due"
)
self.assertEqual(snake_case__ , snake_case__ )
@slow
def UpperCAmelCase__ ( self : str ):
lowerCamelCase_ : Any =TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M" )
lowerCamelCase_ : Union[str, Any] =XGLMTokenizer.from_pretrained("facebook/xglm-564M" )
lowerCamelCase_ : Tuple ="left"
# use different length sentences to test batching
lowerCamelCase_ : Union[str, Any] =[
"This is an extremelly long sentence that only exists to test the ability of the model to cope with "
"left-padding, such as in batched generation. The output for the sequence below should be the same "
"regardless of whether left padding is applied or not. When",
"Hello, my dog is a little",
]
lowerCamelCase_ : Dict =tokenizer(snake_case__ , return_tensors="tf" , padding=snake_case__ )
lowerCamelCase_ : str =inputs["input_ids"]
lowerCamelCase_ : List[Any] =model.generate(input_ids=snake_case__ , attention_mask=inputs["attention_mask"] , max_new_tokens=12 )
lowerCamelCase_ : Any =tokenizer(sentences[0] , return_tensors="tf" ).input_ids
lowerCamelCase_ : int =model.generate(input_ids=snake_case__ , max_new_tokens=12 )
lowerCamelCase_ : int =tokenizer(sentences[1] , return_tensors="tf" ).input_ids
lowerCamelCase_ : List[str] =model.generate(input_ids=snake_case__ , max_new_tokens=12 )
lowerCamelCase_ : Optional[Any] =tokenizer.batch_decode(snake_case__ , skip_special_tokens=snake_case__ )
lowerCamelCase_ : Optional[Any] =tokenizer.decode(output_non_padded[0] , skip_special_tokens=snake_case__ )
lowerCamelCase_ : int =tokenizer.decode(output_padded[0] , skip_special_tokens=snake_case__ )
lowerCamelCase_ : Optional[Any] =[
"This is an extremelly long sentence that only exists to test the ability of the model to cope with "
"left-padding, such as in batched generation. The output for the sequence below should be the same "
"regardless of whether left padding is applied or not. When left padding is applied, the sequence will be "
"a single",
"Hello, my dog is a little bit of a shy one, but he is very friendly",
]
self.assertListEqual(snake_case__ , snake_case__ )
self.assertListEqual(snake_case__ , [non_padded_sentence, padded_sentence] )
| 244 |
"""simple docstring"""
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
A__ : Any = logging.get_logger(__name__)
A__ : Union[str, Any] = {
'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json',
# See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
}
class lowercase__ ( snake_case__ ):
_UpperCAmelCase :Union[str, Any] = "deformable_detr"
_UpperCAmelCase :int = {
"hidden_size": "d_model",
"num_attention_heads": "encoder_attention_heads",
}
def __init__( self : Any , snake_case__ : Dict=True , snake_case__ : str=None , snake_case__ : List[str]=3 , snake_case__ : Optional[int]=300 , snake_case__ : int=1024 , snake_case__ : List[str]=6 , snake_case__ : Any=1024 , snake_case__ : Optional[int]=8 , snake_case__ : Any=6 , snake_case__ : Any=1024 , snake_case__ : Any=8 , snake_case__ : Optional[int]=0.0 , snake_case__ : str=True , snake_case__ : Optional[int]="relu" , snake_case__ : List[Any]=256 , snake_case__ : Optional[int]=0.1 , snake_case__ : List[Any]=0.0 , snake_case__ : Dict=0.0 , snake_case__ : Tuple=0.02 , snake_case__ : int=1.0 , snake_case__ : Any=True , snake_case__ : int=False , snake_case__ : Optional[int]="sine" , snake_case__ : Tuple="resnet50" , snake_case__ : str=True , snake_case__ : Any=False , snake_case__ : Optional[int]=4 , snake_case__ : Optional[Any]=4 , snake_case__ : Optional[Any]=4 , snake_case__ : Optional[Any]=False , snake_case__ : int=300 , snake_case__ : Tuple=False , snake_case__ : List[str]=1 , snake_case__ : str=5 , snake_case__ : Dict=2 , snake_case__ : List[str]=1 , snake_case__ : List[str]=1 , snake_case__ : Union[str, Any]=5 , snake_case__ : Optional[int]=2 , snake_case__ : List[Any]=0.1 , snake_case__ : int=0.25 , snake_case__ : List[str]=False , **snake_case__ : Union[str, 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." )
lowerCamelCase_ : Dict =CONFIG_MAPPING["resnet"](out_features=["stage4"] )
elif isinstance(snake_case__ , snake_case__ ):
lowerCamelCase_ : Optional[int] =backbone_config.get("model_type" )
lowerCamelCase_ : Optional[Any] =CONFIG_MAPPING[backbone_model_type]
lowerCamelCase_ : List[str] =config_class.from_dict(snake_case__ )
lowerCamelCase_ : Any =use_timm_backbone
lowerCamelCase_ : str =backbone_config
lowerCamelCase_ : Tuple =num_channels
lowerCamelCase_ : List[Any] =num_queries
lowerCamelCase_ : str =max_position_embeddings
lowerCamelCase_ : Optional[int] =d_model
lowerCamelCase_ : Optional[int] =encoder_ffn_dim
lowerCamelCase_ : List[str] =encoder_layers
lowerCamelCase_ : Optional[Any] =encoder_attention_heads
lowerCamelCase_ : Any =decoder_ffn_dim
lowerCamelCase_ : List[Any] =decoder_layers
lowerCamelCase_ : Any =decoder_attention_heads
lowerCamelCase_ : List[Any] =dropout
lowerCamelCase_ : Union[str, Any] =attention_dropout
lowerCamelCase_ : str =activation_dropout
lowerCamelCase_ : List[str] =activation_function
lowerCamelCase_ : str =init_std
lowerCamelCase_ : Optional[Any] =init_xavier_std
lowerCamelCase_ : Optional[int] =encoder_layerdrop
lowerCamelCase_ : Optional[int] =auxiliary_loss
lowerCamelCase_ : List[Any] =position_embedding_type
lowerCamelCase_ : List[str] =backbone
lowerCamelCase_ : List[str] =use_pretrained_backbone
lowerCamelCase_ : int =dilation
# deformable attributes
lowerCamelCase_ : Union[str, Any] =num_feature_levels
lowerCamelCase_ : List[str] =encoder_n_points
lowerCamelCase_ : int =decoder_n_points
lowerCamelCase_ : Tuple =two_stage
lowerCamelCase_ : Union[str, Any] =two_stage_num_proposals
lowerCamelCase_ : Optional[int] =with_box_refine
if two_stage is True and with_box_refine is False:
raise ValueError("If two_stage is True, with_box_refine must be True." )
# Hungarian matcher
lowerCamelCase_ : Union[str, Any] =class_cost
lowerCamelCase_ : Any =bbox_cost
lowerCamelCase_ : str =giou_cost
# Loss coefficients
lowerCamelCase_ : int =mask_loss_coefficient
lowerCamelCase_ : Dict =dice_loss_coefficient
lowerCamelCase_ : List[str] =bbox_loss_coefficient
lowerCamelCase_ : Union[str, Any] =giou_loss_coefficient
lowerCamelCase_ : Tuple =eos_coefficient
lowerCamelCase_ : List[Any] =focal_alpha
lowerCamelCase_ : Union[str, Any] =disable_custom_kernels
super().__init__(is_encoder_decoder=snake_case__ , **snake_case__ )
@property
def UpperCAmelCase__ ( self : Dict ):
return self.encoder_attention_heads
@property
def UpperCAmelCase__ ( self : int ):
return self.d_model
def UpperCAmelCase__ ( self : Optional[Any] ):
lowerCamelCase_ : Union[str, Any] =copy.deepcopy(self.__dict__ )
if self.backbone_config is not None:
lowerCamelCase_ : Tuple =self.backbone_config.to_dict()
lowerCamelCase_ : int =self.__class__.model_type
return output
| 244 | 1 |
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import PoolFormerImageProcessor
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def __init__( self : str , __lowerCamelCase : Dict , __lowerCamelCase : List[Any]=7 , __lowerCamelCase : Any=3 , __lowerCamelCase : Any=30 , __lowerCamelCase : Any=400 , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[int]=0.9 , __lowerCamelCase : Dict=None , __lowerCamelCase : Dict=True , __lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , __lowerCamelCase : Dict=[0.5, 0.5, 0.5] , ):
SCREAMING_SNAKE_CASE = size if size is not None else {"shortest_edge": 30}
SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else {"height": 30, "width": 30}
SCREAMING_SNAKE_CASE = parent
SCREAMING_SNAKE_CASE = batch_size
SCREAMING_SNAKE_CASE = num_channels
SCREAMING_SNAKE_CASE = min_resolution
SCREAMING_SNAKE_CASE = max_resolution
SCREAMING_SNAKE_CASE = do_resize_and_center_crop
SCREAMING_SNAKE_CASE = size
SCREAMING_SNAKE_CASE = crop_pct
SCREAMING_SNAKE_CASE = crop_size
SCREAMING_SNAKE_CASE = do_normalize
SCREAMING_SNAKE_CASE = image_mean
SCREAMING_SNAKE_CASE = image_std
def _snake_case ( self : Dict ):
return {
"size": self.size,
"do_resize_and_center_crop": self.do_resize_and_center_crop,
"crop_pct": self.crop_pct,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
}
@require_torch
@require_vision
class _SCREAMING_SNAKE_CASE ( __snake_case , unittest.TestCase ):
'''simple docstring'''
lowerCamelCase__ = PoolFormerImageProcessor if is_vision_available() else None
def _snake_case ( self : List[Any] ):
SCREAMING_SNAKE_CASE = PoolFormerImageProcessingTester(self )
@property
def _snake_case ( self : Optional[int] ):
return self.image_processor_tester.prepare_image_processor_dict()
def _snake_case ( self : Union[str, Any] ):
SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__lowerCamelCase , "do_resize_and_center_crop" ) )
self.assertTrue(hasattr(__lowerCamelCase , "size" ) )
self.assertTrue(hasattr(__lowerCamelCase , "crop_pct" ) )
self.assertTrue(hasattr(__lowerCamelCase , "do_normalize" ) )
self.assertTrue(hasattr(__lowerCamelCase , "image_mean" ) )
self.assertTrue(hasattr(__lowerCamelCase , "image_std" ) )
def _snake_case ( self : Union[str, Any] ):
SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"shortest_edge": 30} )
self.assertEqual(image_processor.crop_size , {"height": 30, "width": 30} )
SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 )
self.assertEqual(image_processor.size , {"shortest_edge": 42} )
self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} )
def _snake_case ( self : List[str] ):
pass
def _snake_case ( self : List[Any] ):
# Initialize image_processing
SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(__lowerCamelCase , Image.Image )
# Test not batched input
SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , )
# Test batched
SCREAMING_SNAKE_CASE = image_processing(__lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , )
def _snake_case ( self : Optional[int] ):
# Initialize image_processing
SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(__lowerCamelCase , np.ndarray )
# Test not batched input
SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , )
# Test batched
SCREAMING_SNAKE_CASE = image_processing(__lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , )
def _snake_case ( self : str ):
# Initialize image_processing
SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(__lowerCamelCase , torch.Tensor )
# Test not batched input
SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , )
# Test batched
SCREAMING_SNAKE_CASE = image_processing(__lowerCamelCase , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , ) | 16 |
import argparse
import json
import logging
import os
import shutil
import sys
import tempfile
import unittest
from unittest import mock
import torch
from accelerate.utils import write_basic_config
from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device
from transformers.utils import is_apex_available
logging.basicConfig(level=logging.DEBUG)
lowerCamelCase__ = logging.getLogger()
def __A() -> str:
"""simple docstring"""
_UpperCamelCase = argparse.ArgumentParser()
parser.add_argument("""-f""" )
_UpperCamelCase = parser.parse_args()
return args.f
def __A(lowerCAmelCase ) -> Any:
"""simple docstring"""
_UpperCamelCase = {}
_UpperCamelCase = os.path.join(lowerCAmelCase , """all_results.json""" )
if os.path.exists(lowerCAmelCase ):
with open(lowerCAmelCase , """r""" ) as f:
_UpperCamelCase = json.load(lowerCAmelCase )
else:
raise ValueError(F'can\'t find {path}' )
return results
def __A() -> Tuple:
"""simple docstring"""
_UpperCamelCase = torch.cuda.is_available() and torch_device == """cuda"""
return is_using_cuda and is_apex_available()
lowerCamelCase__ = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class lowerCAmelCase__ ( __lowercase ):
@classmethod
def A_ ( cls ) -> Tuple:
'''simple docstring'''
_UpperCamelCase = tempfile.mkdtemp()
_UpperCamelCase = os.path.join(cls.tmpdir , """default_config.yml""" )
write_basic_config(save_location=cls.configPath )
_UpperCamelCase = ["""accelerate""", """launch""", """--config_file""", cls.configPath]
@classmethod
def A_ ( cls ) -> str:
'''simple docstring'''
shutil.rmtree(cls.tmpdir )
@mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} )
def A_ ( self ) -> Any:
'''simple docstring'''
_UpperCamelCase = self.get_auto_remove_tmp_dir()
_UpperCamelCase = F'\n {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --seed=42\n --checkpointing_steps epoch\n --with_tracking\n '.split()
if is_cuda_and_apex_available():
testargs.append("""--fp16""" )
run_command(self._launch_args + testargs )
_UpperCamelCase = get_results(a )
self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 )
self.assertTrue(os.path.exists(os.path.join(a , """epoch_0""" ) ) )
self.assertTrue(os.path.exists(os.path.join(a , """glue_no_trainer""" ) ) )
@mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} )
def A_ ( self ) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.get_auto_remove_tmp_dir()
_UpperCamelCase = F'\n {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py\n --model_name_or_path distilgpt2\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --block_size 128\n --per_device_train_batch_size 5\n --per_device_eval_batch_size 5\n --num_train_epochs 2\n --output_dir {tmp_dir}\n --checkpointing_steps epoch\n --with_tracking\n '.split()
if torch.cuda.device_count() > 1:
# Skipping because there are not enough batches to train the model + would need a drop_last to work.
return
run_command(self._launch_args + testargs )
_UpperCamelCase = get_results(a )
self.assertLess(result["""perplexity"""] , 1_00 )
self.assertTrue(os.path.exists(os.path.join(a , """epoch_0""" ) ) )
self.assertTrue(os.path.exists(os.path.join(a , """clm_no_trainer""" ) ) )
@mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} )
def A_ ( self ) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.get_auto_remove_tmp_dir()
_UpperCamelCase = F'\n {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py\n --model_name_or_path distilroberta-base\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --output_dir {tmp_dir}\n --num_train_epochs=1\n --checkpointing_steps epoch\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
_UpperCamelCase = get_results(a )
self.assertLess(result["""perplexity"""] , 42 )
self.assertTrue(os.path.exists(os.path.join(a , """epoch_0""" ) ) )
self.assertTrue(os.path.exists(os.path.join(a , """mlm_no_trainer""" ) ) )
@mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} )
def A_ ( self ) -> Dict:
'''simple docstring'''
_UpperCamelCase = 7 if get_gpu_count() > 1 else 2
_UpperCamelCase = self.get_auto_remove_tmp_dir()
_UpperCamelCase = F'\n {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/conll/sample.json\n --validation_file tests/fixtures/tests_samples/conll/sample.json\n --output_dir {tmp_dir}\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=2\n --num_train_epochs={epochs}\n --seed 7\n --checkpointing_steps epoch\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
_UpperCamelCase = get_results(a )
self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 )
self.assertLess(result["""train_loss"""] , 0.5 )
self.assertTrue(os.path.exists(os.path.join(a , """epoch_0""" ) ) )
self.assertTrue(os.path.exists(os.path.join(a , """ner_no_trainer""" ) ) )
@unittest.skip(reason="""Fix me @muellerzr""" )
@mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} )
def A_ ( self ) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.get_auto_remove_tmp_dir()
_UpperCamelCase = F'\n {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py\n --model_name_or_path bert-base-uncased\n --version_2_with_negative\n --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n --output_dir {tmp_dir}\n --seed=42\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
_UpperCamelCase = get_results(a )
# Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics.
self.assertGreaterEqual(result["""eval_f1"""] , 28 )
self.assertGreaterEqual(result["""eval_exact"""] , 28 )
self.assertTrue(os.path.exists(os.path.join(a , """epoch_0""" ) ) )
self.assertTrue(os.path.exists(os.path.join(a , """qa_no_trainer""" ) ) )
@mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} )
def A_ ( self ) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.get_auto_remove_tmp_dir()
_UpperCamelCase = F'\n {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/swag/sample.json\n --validation_file tests/fixtures/tests_samples/swag/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=20\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
_UpperCamelCase = get_results(a )
self.assertGreaterEqual(result["""eval_accuracy"""] , 0.8 )
self.assertTrue(os.path.exists(os.path.join(a , """swag_no_trainer""" ) ) )
@slow
@mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} )
def A_ ( self ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.get_auto_remove_tmp_dir()
_UpperCamelCase = F'\n {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py\n --model_name_or_path t5-small\n --train_file tests/fixtures/tests_samples/xsum/sample.json\n --validation_file tests/fixtures/tests_samples/xsum/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
_UpperCamelCase = get_results(a )
self.assertGreaterEqual(result["""eval_rouge1"""] , 10 )
self.assertGreaterEqual(result["""eval_rouge2"""] , 2 )
self.assertGreaterEqual(result["""eval_rougeL"""] , 7 )
self.assertGreaterEqual(result["""eval_rougeLsum"""] , 7 )
self.assertTrue(os.path.exists(os.path.join(a , """epoch_0""" ) ) )
self.assertTrue(os.path.exists(os.path.join(a , """summarization_no_trainer""" ) ) )
@slow
@mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} )
def A_ ( self ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.get_auto_remove_tmp_dir()
_UpperCamelCase = F'\n {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py\n --model_name_or_path sshleifer/student_marian_en_ro_6_1\n --source_lang en\n --target_lang ro\n --train_file tests/fixtures/tests_samples/wmt16/sample.json\n --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --num_beams=6\n --learning_rate=3e-3\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --source_lang en_XX\n --target_lang ro_RO\n --checkpointing_steps epoch\n --with_tracking\n '.split()
run_command(self._launch_args + testargs )
_UpperCamelCase = get_results(a )
self.assertGreaterEqual(result["""eval_bleu"""] , 30 )
self.assertTrue(os.path.exists(os.path.join(a , """epoch_0""" ) ) )
self.assertTrue(os.path.exists(os.path.join(a , """translation_no_trainer""" ) ) )
@slow
def A_ ( self ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = logging.StreamHandler(sys.stdout )
logger.addHandler(a )
_UpperCamelCase = self.get_auto_remove_tmp_dir()
_UpperCamelCase = F'\n {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py\n --dataset_name huggingface/semantic-segmentation-test-sample\n --output_dir {tmp_dir}\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n '.split()
run_command(self._launch_args + testargs )
_UpperCamelCase = get_results(a )
self.assertGreaterEqual(result["""eval_overall_accuracy"""] , 0.10 )
@mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} )
def A_ ( self ) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.get_auto_remove_tmp_dir()
_UpperCamelCase = F'\n {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py\n --model_name_or_path google/vit-base-patch16-224-in21k\n --dataset_name hf-internal-testing/cats_vs_dogs_sample\n --learning_rate 1e-4\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 1\n --max_train_steps 2\n --train_val_split 0.1\n --seed 42\n --output_dir {tmp_dir}\n --with_tracking\n --checkpointing_steps 1\n '.split()
if is_cuda_and_apex_available():
testargs.append("""--fp16""" )
run_command(self._launch_args + testargs )
_UpperCamelCase = get_results(a )
# The base model scores a 25%
self.assertGreaterEqual(result["""eval_accuracy"""] , 0.6 )
self.assertTrue(os.path.exists(os.path.join(a , """step_1""" ) ) )
self.assertTrue(os.path.exists(os.path.join(a , """image_classification_no_trainer""" ) ) )
| 612 | 0 |
import numpy as np
import torch
from ..models.clipseg import CLIPSegForImageSegmentation
from ..utils import is_vision_available, requires_backends
from .base import PipelineTool
if is_vision_available():
from PIL import Image
class _lowerCamelCase( _a ):
lowercase_ : Union[str, Any] = (
"""This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image."""
"""It takes two arguments named `image` which should be the original image, and `label` which should be a text """
"""describing the elements what should be identified in the segmentation mask. The tool returns the mask."""
)
lowercase_ : str = """CIDAS/clipseg-rd64-refined"""
lowercase_ : Optional[Any] = """image_segmenter"""
lowercase_ : str = CLIPSegForImageSegmentation
lowercase_ : Union[str, Any] = ["""image""", """text"""]
lowercase_ : Union[str, Any] = ["""image"""]
def __init__( self, *lowerCamelCase, **lowerCamelCase) -> List[str]:
"""simple docstring"""
requires_backends(self, ['vision'])
super().__init__(*_SCREAMING_SNAKE_CASE, **_SCREAMING_SNAKE_CASE)
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase) -> str:
"""simple docstring"""
return self.pre_processor(text=[label], images=[image], padding=_SCREAMING_SNAKE_CASE, return_tensors='pt')
def UpperCamelCase ( self, lowerCamelCase) -> Tuple:
"""simple docstring"""
with torch.no_grad():
_lowercase : Optional[Any] = self.model(**_SCREAMING_SNAKE_CASE).logits
return logits
def UpperCamelCase ( self, lowerCamelCase) -> Union[str, Any]:
"""simple docstring"""
_lowercase : int = outputs.cpu().detach().numpy()
_lowercase : List[Any] = 0
_lowercase : Union[str, Any] = 1
return Image.fromarray((array * 2_55).astype(np.uinta))
| 713 |
import subprocess
import sys
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch
class _lowerCamelCase( _a ):
@require_torch
def UpperCamelCase ( self) -> int:
"""simple docstring"""
_lowercase : Optional[Any] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n '
_lowercase : Union[str, Any] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n '
_lowercase : List[str] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n '
# Force fetching the files so that we can use the cache
_lowercase : Union[str, Any] = 'hf-internal-testing/tiny-random-bert'
BertConfig.from_pretrained(lowerCamelCase)
BertModel.from_pretrained(lowerCamelCase)
BertTokenizer.from_pretrained(lowerCamelCase)
pipeline(task='fill-mask', model=lowerCamelCase)
# baseline - just load from_pretrained with normal network
_lowercase : Any = [sys.executable, '-c', '\n'.join([load, run, mock])]
# should succeed
_lowercase : List[str] = self.get_env()
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
_lowercase : Any = '1'
_lowercase : List[Any] = subprocess.run(lowerCamelCase, env=lowerCamelCase, check=lowerCamelCase, capture_output=lowerCamelCase)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('success', result.stdout.decode())
@require_torch
def UpperCamelCase ( self) -> List[Any]:
"""simple docstring"""
_lowercase : int = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n '
_lowercase : Union[str, Any] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n '
_lowercase : List[Any] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n '
# Force fetching the files so that we can use the cache
_lowercase : Any = 'hf-internal-testing/tiny-random-bert'
BertConfig.from_pretrained(lowerCamelCase)
BertModel.from_pretrained(lowerCamelCase)
BertTokenizer.from_pretrained(lowerCamelCase)
pipeline(task='fill-mask', model=lowerCamelCase)
# baseline - just load from_pretrained with normal network
_lowercase : List[str] = [sys.executable, '-c', '\n'.join([load, run, mock])]
# should succeed
_lowercase : Any = self.get_env()
_lowercase : str = subprocess.run(lowerCamelCase, env=lowerCamelCase, check=lowerCamelCase, capture_output=lowerCamelCase)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('success', result.stdout.decode())
@require_torch
def UpperCamelCase ( self) -> Union[str, Any]:
"""simple docstring"""
_lowercase : Tuple = '\nfrom transformers import BertConfig, BertModel, BertTokenizer\n '
_lowercase : int = '\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n '
_lowercase : List[Any] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n '
# baseline - just load from_pretrained with normal network
_lowercase : int = [sys.executable, '-c', '\n'.join([load, run])]
# should succeed
_lowercase : List[str] = self.get_env()
_lowercase : Dict = subprocess.run(lowerCamelCase, env=lowerCamelCase, check=lowerCamelCase, capture_output=lowerCamelCase)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('success', result.stdout.decode())
# next emulate no network
_lowercase : Union[str, Any] = [sys.executable, '-c', '\n'.join([load, mock, run])]
# Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
# env["TRANSFORMERS_OFFLINE"] = "0"
# result = subprocess.run(cmd, env=env, check=False, capture_output=True)
# self.assertEqual(result.returncode, 1, result.stderr)
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
_lowercase : Optional[Any] = '1'
_lowercase : Optional[Any] = subprocess.run(lowerCamelCase, env=lowerCamelCase, check=lowerCamelCase, capture_output=lowerCamelCase)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('success', result.stdout.decode())
@require_torch
def UpperCamelCase ( self) -> Optional[Any]:
"""simple docstring"""
_lowercase : Optional[Any] = '\nfrom transformers import pipeline\n '
_lowercase : Dict = '\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n '
_lowercase : Optional[Any] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n '
_lowercase : Tuple = self.get_env()
_lowercase : Tuple = '1'
_lowercase : Union[str, Any] = [sys.executable, '-c', '\n'.join([load, mock, run])]
_lowercase : Tuple = subprocess.run(lowerCamelCase, env=lowerCamelCase, check=lowerCamelCase, capture_output=lowerCamelCase)
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn(
'You cannot infer task automatically within `pipeline` when using offline mode', result.stderr.decode().replace('\n', ''), )
@require_torch
def UpperCamelCase ( self) -> Tuple:
"""simple docstring"""
_lowercase : Dict = '\nfrom transformers import AutoModel\n '
_lowercase : int = '\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n '
# baseline - just load from_pretrained with normal network
_lowercase : Optional[int] = [sys.executable, '-c', '\n'.join([load, run])]
# should succeed
_lowercase : int = self.get_env()
_lowercase : List[str] = subprocess.run(lowerCamelCase, env=lowerCamelCase, check=lowerCamelCase, capture_output=lowerCamelCase)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('success', result.stdout.decode())
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
_lowercase : Tuple = '1'
_lowercase : Dict = subprocess.run(lowerCamelCase, env=lowerCamelCase, check=lowerCamelCase, capture_output=lowerCamelCase)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('success', result.stdout.decode())
| 354 | 0 |
"""simple docstring"""
import os
import sys
from contextlib import contextmanager
# Windows only
if os.name == "nt":
import ctypes
import msvcrt # noqa
class SCREAMING_SNAKE_CASE_ ( ctypes.Structure ):
"""simple docstring"""
__lowercase : Any = [('''size''', ctypes.c_int), ('''visible''', ctypes.c_byte)]
def _lowerCAmelCase ( ):
if os.name == "nt":
__SCREAMING_SNAKE_CASE = CursorInfo()
__SCREAMING_SNAKE_CASE = ctypes.windll.kernelaa.GetStdHandle(-11 )
ctypes.windll.kernelaa.GetConsoleCursorInfo(UpperCamelCase_ , ctypes.byref(UpperCamelCase_ ) )
__SCREAMING_SNAKE_CASE = False
ctypes.windll.kernelaa.SetConsoleCursorInfo(UpperCamelCase_ , ctypes.byref(UpperCamelCase_ ) )
elif os.name == "posix":
sys.stdout.write("""\033[?25l""" )
sys.stdout.flush()
def _lowerCAmelCase ( ):
if os.name == "nt":
__SCREAMING_SNAKE_CASE = CursorInfo()
__SCREAMING_SNAKE_CASE = ctypes.windll.kernelaa.GetStdHandle(-11 )
ctypes.windll.kernelaa.GetConsoleCursorInfo(UpperCamelCase_ , ctypes.byref(UpperCamelCase_ ) )
__SCREAMING_SNAKE_CASE = True
ctypes.windll.kernelaa.SetConsoleCursorInfo(UpperCamelCase_ , ctypes.byref(UpperCamelCase_ ) )
elif os.name == "posix":
sys.stdout.write("""\033[?25h""" )
sys.stdout.flush()
@contextmanager
def _lowerCAmelCase ( ):
try:
hide_cursor()
yield
finally:
show_cursor()
| 155 |
"""simple docstring"""
import io
import json
import unittest
from parameterized import parameterized
from transformers import FSMTForConditionalGeneration, FSMTTokenizer
from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device
from utils import calculate_bleu
__magic_name__ = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json"
with io.open(filename, "r", encoding="utf-8") as f:
__magic_name__ = json.load(f)
@require_torch
class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ):
"""simple docstring"""
def snake_case_ ( self , lowerCAmelCase__):
return FSMTTokenizer.from_pretrained(lowerCAmelCase__)
def snake_case_ ( self , lowerCAmelCase__):
__SCREAMING_SNAKE_CASE = FSMTForConditionalGeneration.from_pretrained(lowerCAmelCase__).to(lowerCAmelCase__)
if torch_device == "cuda":
model.half()
return model
@parameterized.expand(
[
["""en-ru""", 26.0],
["""ru-en""", 22.0],
["""en-de""", 22.0],
["""de-en""", 29.0],
])
@slow
def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__):
# note: this test is not testing the best performance since it only evals a small batch
# but it should be enough to detect a regression in the output quality
__SCREAMING_SNAKE_CASE = f"facebook/wmt19-{pair}"
__SCREAMING_SNAKE_CASE = self.get_tokenizer(lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = self.get_model(lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = bleu_data[pair]["""src"""]
__SCREAMING_SNAKE_CASE = bleu_data[pair]["""tgt"""]
__SCREAMING_SNAKE_CASE = tokenizer(lowerCAmelCase__ , return_tensors="""pt""" , truncation=lowerCAmelCase__ , padding="""longest""").to(lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = model.generate(
input_ids=batch.input_ids , num_beams=8 , )
__SCREAMING_SNAKE_CASE = tokenizer.batch_decode(
lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__)
__SCREAMING_SNAKE_CASE = calculate_bleu(lowerCAmelCase__ , lowerCAmelCase__)
print(lowerCAmelCase__)
self.assertGreaterEqual(scores["""bleu"""] , lowerCAmelCase__)
| 155 | 1 |
"""simple docstring"""
import unittest
import numpy as np
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision
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 DPTImageProcessor
class A_(unittest.TestCase ):
"""simple docstring"""
def __init__( self , A , A=7 , A=3 , A=18 , A=30 , A=400 , A=True , A=None , A=True , A=[0.5, 0.5, 0.5] , A=[0.5, 0.5, 0.5] , ):
_lowerCamelCase : Dict = size if size is not None else {'height': 18, 'width': 18}
_lowerCamelCase : str = parent
_lowerCamelCase : Optional[int] = batch_size
_lowerCamelCase : Optional[Any] = num_channels
_lowerCamelCase : Union[str, Any] = image_size
_lowerCamelCase : str = min_resolution
_lowerCamelCase : Tuple = max_resolution
_lowerCamelCase : Union[str, Any] = do_resize
_lowerCamelCase : int = size
_lowerCamelCase : Optional[Any] = do_normalize
_lowerCamelCase : int = image_mean
_lowerCamelCase : Union[str, Any] = image_std
def _lowerCAmelCase ( self ):
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
}
@require_torch
@require_vision
class A_(SCREAMING_SNAKE_CASE_ , unittest.TestCase ):
"""simple docstring"""
a_ : Dict = DPTImageProcessor if is_vision_available() else None
def _lowerCAmelCase ( self ):
_lowerCamelCase : Optional[int] = DPTImageProcessingTester(self )
@property
def _lowerCAmelCase ( self ):
return self.image_processor_tester.prepare_image_processor_dict()
def _lowerCAmelCase ( self ):
_lowerCamelCase : str = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(A , 'image_mean' ) )
self.assertTrue(hasattr(A , 'image_std' ) )
self.assertTrue(hasattr(A , 'do_normalize' ) )
self.assertTrue(hasattr(A , 'do_resize' ) )
self.assertTrue(hasattr(A , 'size' ) )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Tuple = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'height': 18, 'width': 18} )
_lowerCamelCase : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {'height': 42, 'width': 42} )
def _lowerCAmelCase ( self ):
# Initialize image_processing
_lowerCamelCase : Any = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_lowerCamelCase : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=A )
for image in image_inputs:
self.assertIsInstance(A , Image.Image )
# Test not batched input
_lowerCamelCase : str = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
_lowerCamelCase : List[str] = image_processing(A , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
def _lowerCAmelCase ( self ):
# Initialize image_processing
_lowerCamelCase : str = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_lowerCamelCase : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=A , numpify=A )
for image in image_inputs:
self.assertIsInstance(A , np.ndarray )
# Test not batched input
_lowerCamelCase : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
_lowerCamelCase : int = image_processing(A , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
def _lowerCAmelCase ( self ):
# Initialize image_processing
_lowerCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_lowerCamelCase : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=A , torchify=A )
for image in image_inputs:
self.assertIsInstance(A , torch.Tensor )
# Test not batched input
_lowerCamelCase : Tuple = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
_lowerCamelCase : List[Any] = image_processing(A , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
| 710 |
"""simple docstring"""
import argparse
import json
import os
import sys
import tempfile
import unittest
from argparse import Namespace
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import List, Literal, Optional
import yaml
from transformers import HfArgumentParser, TrainingArguments
from transformers.hf_argparser import make_choice_type_function, string_to_bool
# Since Python 3.10, we can use the builtin `|` operator for Union types
# See PEP 604: https://peps.python.org/pep-0604
a_ = sys.version_info >= (3, 10)
def UpperCAmelCase_ ( __a : List[str]=None , __a : List[str]=None ):
'''simple docstring'''
return field(default_factory=lambda: default , metadata=__a )
@dataclass
class A_:
"""simple docstring"""
a_ : int
a_ : float
a_ : str
a_ : bool
@dataclass
class A_:
"""simple docstring"""
a_ : int = 42
a_ : str = field(default="""toto""" , metadata={"""help""": """help message"""} )
@dataclass
class A_:
"""simple docstring"""
a_ : bool = False
a_ : bool = True
a_ : Optional[bool] = None
class A_(SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
a_ : Tuple = """titi"""
a_ : Tuple = """toto"""
class A_(SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
a_ : str = """titi"""
a_ : Union[str, Any] = """toto"""
a_ : Union[str, Any] = 42
@dataclass
class A_:
"""simple docstring"""
a_ : BasicEnum = "toto"
def _lowerCAmelCase ( self ):
_lowerCamelCase : Tuple = BasicEnum(self.foo )
@dataclass
class A_:
"""simple docstring"""
a_ : MixedTypeEnum = "toto"
def _lowerCAmelCase ( self ):
_lowerCamelCase : Tuple = MixedTypeEnum(self.foo )
@dataclass
class A_:
"""simple docstring"""
a_ : Optional[int] = None
a_ : Optional[float] = field(default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """help message"""} )
a_ : Optional[str] = None
a_ : Optional[List[str]] = list_field(default=[] )
a_ : Optional[List[int]] = list_field(default=[] )
@dataclass
class A_:
"""simple docstring"""
a_ : List[int] = list_field(default=[] )
a_ : List[int] = list_field(default=[1, 2, 3] )
a_ : List[str] = list_field(default=["""Hallo""", """Bonjour""", """Hello"""] )
a_ : List[float] = list_field(default=[0.1, 0.2, 0.3] )
@dataclass
class A_:
"""simple docstring"""
a_ : List[int] = field()
a_ : str = field()
a_ : BasicEnum = field()
def _lowerCAmelCase ( self ):
_lowerCamelCase : List[str] = BasicEnum(self.required_enum )
@dataclass
class A_:
"""simple docstring"""
a_ : int
a_ : "BasicEnum" = field()
a_ : "Optional[bool]" = None
a_ : "str" = field(default="""toto""" , metadata={"""help""": """help message"""} )
a_ : "List[str]" = list_field(default=["""Hallo""", """Bonjour""", """Hello"""] )
if is_python_no_less_than_3_10:
@dataclass
class A_:
"""simple docstring"""
a_ : bool = False
a_ : bool = True
a_ : bool | None = None
@dataclass
class A_:
"""simple docstring"""
a_ : int | None = None
a_ : float | None = field(default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """help message"""} )
a_ : str | None = None
a_ : list[str] | None = list_field(default=[] )
a_ : list[int] | None = list_field(default=[] )
class A_(unittest.TestCase ):
"""simple docstring"""
def _lowerCAmelCase ( self , A , A ):
self.assertEqual(len(a._actions ) , len(b._actions ) )
for x, y in zip(a._actions , b._actions ):
_lowerCamelCase : Dict = {k: v for k, v in vars(A ).items() if k != 'container'}
_lowerCamelCase : Optional[Any] = {k: v for k, v in vars(A ).items() if k != 'container'}
# Choices with mixed type have custom function as "type"
# So we need to compare results directly for equality
if xx.get('choices' , A ) and yy.get('choices' , A ):
for expected_choice in yy["choices"] + xx["choices"]:
self.assertEqual(xx['type'](A ) , yy['type'](A ) )
del xx["type"], yy["type"]
self.assertEqual(A , A )
def _lowerCAmelCase ( self ):
_lowerCamelCase : List[Any] = HfArgumentParser(A )
_lowerCamelCase : Any = argparse.ArgumentParser()
expected.add_argument('--foo' , type=A , required=A )
expected.add_argument('--bar' , type=A , required=A )
expected.add_argument('--baz' , type=A , required=A )
expected.add_argument('--flag' , type=A , default=A , const=A , nargs='?' )
self.argparsersEqual(A , A )
_lowerCamelCase : Optional[Any] = ['--foo', '1', '--baz', 'quux', '--bar', '0.5']
((_lowerCamelCase) , ) : str = parser.parse_args_into_dataclasses(A , look_for_args_file=A )
self.assertFalse(example.flag )
def _lowerCAmelCase ( self ):
_lowerCamelCase : List[str] = HfArgumentParser(A )
_lowerCamelCase : int = argparse.ArgumentParser()
expected.add_argument('--foo' , default=42 , type=A )
expected.add_argument('--baz' , default='toto' , type=A , help='help message' )
self.argparsersEqual(A , A )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Union[str, Any] = argparse.ArgumentParser()
expected.add_argument('--foo' , type=A , default=A , const=A , nargs='?' )
expected.add_argument('--baz' , type=A , default=A , const=A , nargs='?' )
# A boolean no_* argument always has to come after its "default: True" regular counter-part
# and its default must be set to False
expected.add_argument('--no_baz' , action='store_false' , default=A , dest='baz' )
expected.add_argument('--opt' , type=A , default=A )
_lowerCamelCase : Optional[Any] = [WithDefaultBoolExample]
if is_python_no_less_than_3_10:
dataclass_types.append(A )
for dataclass_type in dataclass_types:
_lowerCamelCase : List[Any] = HfArgumentParser(A )
self.argparsersEqual(A , A )
_lowerCamelCase : Union[str, Any] = parser.parse_args([] )
self.assertEqual(A , Namespace(foo=A , baz=A , opt=A ) )
_lowerCamelCase : List[Any] = parser.parse_args(['--foo', '--no_baz'] )
self.assertEqual(A , Namespace(foo=A , baz=A , opt=A ) )
_lowerCamelCase : Union[str, Any] = parser.parse_args(['--foo', '--baz'] )
self.assertEqual(A , Namespace(foo=A , baz=A , opt=A ) )
_lowerCamelCase : Dict = parser.parse_args(['--foo', 'True', '--baz', 'True', '--opt', 'True'] )
self.assertEqual(A , Namespace(foo=A , baz=A , opt=A ) )
_lowerCamelCase : Any = parser.parse_args(['--foo', 'False', '--baz', 'False', '--opt', 'False'] )
self.assertEqual(A , Namespace(foo=A , baz=A , opt=A ) )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Optional[int] = HfArgumentParser(A )
_lowerCamelCase : Tuple = argparse.ArgumentParser()
expected.add_argument(
'--foo' , default='toto' , choices=['titi', 'toto', 42] , type=make_choice_type_function(['titi', 'toto', 42] ) , )
self.argparsersEqual(A , A )
_lowerCamelCase : Optional[int] = parser.parse_args([] )
self.assertEqual(args.foo , 'toto' )
_lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses([] )[0]
self.assertEqual(enum_ex.foo , MixedTypeEnum.toto )
_lowerCamelCase : List[Any] = parser.parse_args(['--foo', 'titi'] )
self.assertEqual(args.foo , 'titi' )
_lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses(['--foo', 'titi'] )[0]
self.assertEqual(enum_ex.foo , MixedTypeEnum.titi )
_lowerCamelCase : Dict = parser.parse_args(['--foo', '42'] )
self.assertEqual(args.foo , 42 )
_lowerCamelCase : List[Any] = parser.parse_args_into_dataclasses(['--foo', '42'] )[0]
self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo )
def _lowerCAmelCase ( self ):
@dataclass
class A_:
"""simple docstring"""
a_ : Literal["titi", "toto", 42] = "toto"
_lowerCamelCase : Optional[int] = HfArgumentParser(A )
_lowerCamelCase : str = argparse.ArgumentParser()
expected.add_argument(
'--foo' , default='toto' , choices=('titi', 'toto', 42) , type=make_choice_type_function(['titi', 'toto', 42] ) , )
self.argparsersEqual(A , A )
_lowerCamelCase : Union[str, Any] = parser.parse_args([] )
self.assertEqual(args.foo , 'toto' )
_lowerCamelCase : List[Any] = parser.parse_args(['--foo', 'titi'] )
self.assertEqual(args.foo , 'titi' )
_lowerCamelCase : Dict = parser.parse_args(['--foo', '42'] )
self.assertEqual(args.foo , 42 )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Tuple = HfArgumentParser(A )
_lowerCamelCase : int = argparse.ArgumentParser()
expected.add_argument('--foo_int' , nargs='+' , default=[] , type=A )
expected.add_argument('--bar_int' , nargs='+' , default=[1, 2, 3] , type=A )
expected.add_argument('--foo_str' , nargs='+' , default=['Hallo', 'Bonjour', 'Hello'] , type=A )
expected.add_argument('--foo_float' , nargs='+' , default=[0.1, 0.2, 0.3] , type=A )
self.argparsersEqual(A , A )
_lowerCamelCase : List[str] = parser.parse_args([] )
self.assertEqual(
A , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=['Hallo', 'Bonjour', 'Hello'] , foo_float=[0.1, 0.2, 0.3] ) , )
_lowerCamelCase : Optional[int] = parser.parse_args('--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7'.split() )
self.assertEqual(A , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=['a', 'b', 'c'] , foo_float=[0.1, 0.7] ) )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Tuple = argparse.ArgumentParser()
expected.add_argument('--foo' , default=A , type=A )
expected.add_argument('--bar' , default=A , type=A , help='help message' )
expected.add_argument('--baz' , default=A , type=A )
expected.add_argument('--ces' , nargs='+' , default=[] , type=A )
expected.add_argument('--des' , nargs='+' , default=[] , type=A )
_lowerCamelCase : Any = [OptionalExample]
if is_python_no_less_than_3_10:
dataclass_types.append(A )
for dataclass_type in dataclass_types:
_lowerCamelCase : Optional[Any] = HfArgumentParser(A )
self.argparsersEqual(A , A )
_lowerCamelCase : List[Any] = parser.parse_args([] )
self.assertEqual(A , Namespace(foo=A , bar=A , baz=A , ces=[] , des=[] ) )
_lowerCamelCase : Union[str, Any] = parser.parse_args('--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3'.split() )
self.assertEqual(A , Namespace(foo=12 , bar=3.1_4 , baz='42' , ces=['a', 'b', 'c'] , des=[1, 2, 3] ) )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Union[str, Any] = HfArgumentParser(A )
_lowerCamelCase : Tuple = argparse.ArgumentParser()
expected.add_argument('--required_list' , nargs='+' , type=A , required=A )
expected.add_argument('--required_str' , type=A , required=A )
expected.add_argument(
'--required_enum' , type=make_choice_type_function(['titi', 'toto'] ) , choices=['titi', 'toto'] , required=A , )
self.argparsersEqual(A , A )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Optional[int] = HfArgumentParser(A )
_lowerCamelCase : List[str] = argparse.ArgumentParser()
expected.add_argument('--foo' , type=A , required=A )
expected.add_argument(
'--required_enum' , type=make_choice_type_function(['titi', 'toto'] ) , choices=['titi', 'toto'] , required=A , )
expected.add_argument('--opt' , type=A , default=A )
expected.add_argument('--baz' , default='toto' , type=A , help='help message' )
expected.add_argument('--foo_str' , nargs='+' , default=['Hallo', 'Bonjour', 'Hello'] , type=A )
self.argparsersEqual(A , A )
def _lowerCAmelCase ( self ):
_lowerCamelCase : List[str] = HfArgumentParser(A )
_lowerCamelCase : str = {
'foo': 12,
'bar': 3.1_4,
'baz': '42',
'flag': True,
}
_lowerCamelCase : Any = parser.parse_dict(A )[0]
_lowerCamelCase : Any = BasicExample(**A )
self.assertEqual(A , A )
def _lowerCAmelCase ( self ):
_lowerCamelCase : int = HfArgumentParser(A )
_lowerCamelCase : Optional[Any] = {
'foo': 12,
'bar': 3.1_4,
'baz': '42',
'flag': True,
'extra': 42,
}
self.assertRaises(A , parser.parse_dict , A , allow_extra_keys=A )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Dict = HfArgumentParser(A )
_lowerCamelCase : Tuple = {
'foo': 12,
'bar': 3.1_4,
'baz': '42',
'flag': True,
}
with tempfile.TemporaryDirectory() as tmp_dir:
_lowerCamelCase : Union[str, Any] = os.path.join(A , 'temp_json' )
os.mkdir(A )
with open(temp_local_path + '.json' , 'w+' ) as f:
json.dump(A , A )
_lowerCamelCase : Optional[Any] = parser.parse_yaml_file(Path(temp_local_path + '.json' ) )[0]
_lowerCamelCase : Union[str, Any] = BasicExample(**A )
self.assertEqual(A , A )
def _lowerCAmelCase ( self ):
_lowerCamelCase : Optional[int] = HfArgumentParser(A )
_lowerCamelCase : Dict = {
'foo': 12,
'bar': 3.1_4,
'baz': '42',
'flag': True,
}
with tempfile.TemporaryDirectory() as tmp_dir:
_lowerCamelCase : int = os.path.join(A , 'temp_yaml' )
os.mkdir(A )
with open(temp_local_path + '.yaml' , 'w+' ) as f:
yaml.dump(A , A )
_lowerCamelCase : Optional[int] = parser.parse_yaml_file(Path(temp_local_path + '.yaml' ) )[0]
_lowerCamelCase : Any = BasicExample(**A )
self.assertEqual(A , A )
def _lowerCAmelCase ( self ):
_lowerCamelCase : int = HfArgumentParser(A )
self.assertIsNotNone(A )
| 349 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_speech_available,
is_tf_available,
is_torch_available,
)
lowerCAmelCase_ = {
'''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''],
'''processing_speech_to_text''': ['''Speech2TextProcessor'''],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ = ['''Speech2TextTokenizer''']
try:
if not is_speech_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ = ['''Speech2TextFeatureExtractor''']
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ = [
'''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFSpeech2TextForConditionalGeneration''',
'''TFSpeech2TextModel''',
'''TFSpeech2TextPreTrainedModel''',
]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ = [
'''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''Speech2TextForConditionalGeneration''',
'''Speech2TextModel''',
'''Speech2TextPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig
from .processing_speech_to_text import SpeechaTextProcessor
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_speech_to_text import SpeechaTextTokenizer
try:
if not is_speech_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_speech_to_text import (
TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFSpeechaTextForConditionalGeneration,
TFSpeechaTextModel,
TFSpeechaTextPreTrainedModel,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_speech_to_text import (
SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
SpeechaTextForConditionalGeneration,
SpeechaTextModel,
SpeechaTextPreTrainedModel,
)
else:
import sys
lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 60 |
'''simple docstring'''
import glob
import os
import random
from string import ascii_lowercase, digits
import cva
import numpy as np
# Parrameters
_lowerCAmelCase = (7_2_0, 1_2_8_0) # Height, Width
_lowerCAmelCase = (0.4, 0.6) # if height or width lower than this scale, drop it.
_lowerCAmelCase = 1 / 1_0_0
_lowerCAmelCase = ""
_lowerCAmelCase = ""
_lowerCAmelCase = ""
_lowerCAmelCase = 2_5_0
def _lowerCAmelCase ( ) ->None:
"""simple docstring"""
lowercase__ , lowercase__ = get_dataset(lowercase , lowercase )
for index in range(lowercase ):
lowercase__ = random.sample(range(len(lowercase ) ) , 4 )
lowercase__ , lowercase__ , lowercase__ = update_image_and_anno(
lowercase , lowercase , lowercase , lowercase , lowercase , filter_scale=lowercase , )
# Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
lowercase__ = random_chars(3_2 )
lowercase__ = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0]
lowercase__ = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}'''
cva.imwrite(F'''{file_root}.jpg''' , lowercase , [cva.IMWRITE_JPEG_QUALITY, 8_5] )
print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' )
lowercase__ = []
for anno in new_annos:
lowercase__ = anno[3] - anno[1]
lowercase__ = anno[4] - anno[2]
lowercase__ = anno[1] + width / 2
lowercase__ = anno[2] + height / 2
lowercase__ = F'''{anno[0]} {x_center} {y_center} {width} {height}'''
annos_list.append(lowercase )
with open(F'''{file_root}.txt''' , '''w''' ) as outfile:
outfile.write('''\n'''.join(line for line in annos_list ) )
def _lowerCAmelCase ( lowercase : str , lowercase : str ) ->tuple[list, list]:
"""simple docstring"""
lowercase__ = []
lowercase__ = []
for label_file in glob.glob(os.path.join(lowercase , '''*.txt''' ) ):
lowercase__ = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0]
with open(lowercase ) as in_file:
lowercase__ = in_file.readlines()
lowercase__ = os.path.join(lowercase , F'''{label_name}.jpg''' )
lowercase__ = []
for obj_list in obj_lists:
lowercase__ = obj_list.rstrip('''\n''' ).split(''' ''' )
lowercase__ = float(obj[1] ) - float(obj[3] ) / 2
lowercase__ = float(obj[2] ) - float(obj[4] ) / 2
lowercase__ = float(obj[1] ) + float(obj[3] ) / 2
lowercase__ = float(obj[2] ) + float(obj[4] ) / 2
boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] )
if not boxes:
continue
img_paths.append(lowercase )
labels.append(lowercase )
return img_paths, labels
def _lowerCAmelCase ( lowercase : list , lowercase : list , lowercase : list[int] , lowercase : tuple[int, int] , lowercase : tuple[float, float] , lowercase : float = 0.0 , ) ->tuple[list, list, str]:
"""simple docstring"""
lowercase__ = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta )
lowercase__ = scale_range[0] + random.random() * (scale_range[1] - scale_range[0])
lowercase__ = scale_range[0] + random.random() * (scale_range[1] - scale_range[0])
lowercase__ = int(scale_x * output_size[1] )
lowercase__ = int(scale_y * output_size[0] )
lowercase__ = []
lowercase__ = []
for i, index in enumerate(lowercase ):
lowercase__ = all_img_list[index]
path_list.append(lowercase )
lowercase__ = all_annos[index]
lowercase__ = cva.imread(lowercase )
if i == 0: # top-left
lowercase__ = cva.resize(lowercase , (divid_point_x, divid_point_y) )
lowercase__ = img
for bbox in img_annos:
lowercase__ = bbox[1] * scale_x
lowercase__ = bbox[2] * scale_y
lowercase__ = bbox[3] * scale_x
lowercase__ = bbox[4] * scale_y
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
elif i == 1: # top-right
lowercase__ = cva.resize(lowercase , (output_size[1] - divid_point_x, divid_point_y) )
lowercase__ = img
for bbox in img_annos:
lowercase__ = scale_x + bbox[1] * (1 - scale_x)
lowercase__ = bbox[2] * scale_y
lowercase__ = scale_x + bbox[3] * (1 - scale_x)
lowercase__ = bbox[4] * scale_y
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
elif i == 2: # bottom-left
lowercase__ = cva.resize(lowercase , (divid_point_x, output_size[0] - divid_point_y) )
lowercase__ = img
for bbox in img_annos:
lowercase__ = bbox[1] * scale_x
lowercase__ = scale_y + bbox[2] * (1 - scale_y)
lowercase__ = bbox[3] * scale_x
lowercase__ = scale_y + bbox[4] * (1 - scale_y)
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
else: # bottom-right
lowercase__ = cva.resize(
lowercase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) )
lowercase__ = img
for bbox in img_annos:
lowercase__ = scale_x + bbox[1] * (1 - scale_x)
lowercase__ = scale_y + bbox[2] * (1 - scale_y)
lowercase__ = scale_x + bbox[3] * (1 - scale_x)
lowercase__ = scale_y + bbox[4] * (1 - scale_y)
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
# Remove bounding box small than scale of filter
if filter_scale > 0:
lowercase__ = [
anno
for anno in new_anno
if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2])
]
return output_img, new_anno, path_list[0]
def _lowerCAmelCase ( lowercase : int ) ->str:
"""simple docstring"""
assert number_char > 1, "The number of character should greater than 1"
lowercase__ = ascii_lowercase + digits
return "".join(random.choice(lowercase ) for _ in range(lowercase ) )
if __name__ == "__main__":
main()
print("DONE ✅")
| 161 | 0 |
def __UpperCamelCase ( _A : str ) ->list:
"""simple docstring"""
if n_term == "":
return []
lowerCamelCase_ =[]
for temp in range(int(_A ) ):
series.append(f'1/{temp + 1}' if series else """1""" )
return series
if __name__ == "__main__":
__A : List[Any] = input('Enter the last number (nth term) of the Harmonic Series')
print('Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n')
print(harmonic_series(nth_term))
| 75 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
__A : int = {
'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 _SCREAMING_SNAKE_CASE ( lowerCAmelCase__):
_UpperCamelCase:Any = "albert"
def __init__( self , _SCREAMING_SNAKE_CASE=3_0000 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=1_6384 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , **_SCREAMING_SNAKE_CASE , )-> Optional[int]:
super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
lowerCamelCase_ =vocab_size
lowerCamelCase_ =embedding_size
lowerCamelCase_ =hidden_size
lowerCamelCase_ =num_hidden_layers
lowerCamelCase_ =num_hidden_groups
lowerCamelCase_ =num_attention_heads
lowerCamelCase_ =inner_group_num
lowerCamelCase_ =hidden_act
lowerCamelCase_ =intermediate_size
lowerCamelCase_ =hidden_dropout_prob
lowerCamelCase_ =attention_probs_dropout_prob
lowerCamelCase_ =max_position_embeddings
lowerCamelCase_ =type_vocab_size
lowerCamelCase_ =initializer_range
lowerCamelCase_ =layer_norm_eps
lowerCamelCase_ =classifier_dropout_prob
lowerCamelCase_ =position_embedding_type
class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__):
@property
def _snake_case ( self )-> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
lowerCamelCase_ ={0: """batch""", 1: """choice""", 2: """sequence"""}
else:
lowerCamelCase_ ={0: """batch""", 1: """sequence"""}
return OrderedDict(
[
("""input_ids""", dynamic_axis),
("""attention_mask""", dynamic_axis),
("""token_type_ids""", dynamic_axis),
] )
| 75 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
A : List[str] = {
'''configuration_xlm_roberta''': [
'''XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''XLMRobertaConfig''',
'''XLMRobertaOnnxConfig''',
],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A : str = ['''XLMRobertaTokenizer''']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A : List[Any] = ['''XLMRobertaTokenizerFast''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A : Any = [
'''XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''XLMRobertaForCausalLM''',
'''XLMRobertaForMaskedLM''',
'''XLMRobertaForMultipleChoice''',
'''XLMRobertaForQuestionAnswering''',
'''XLMRobertaForSequenceClassification''',
'''XLMRobertaForTokenClassification''',
'''XLMRobertaModel''',
'''XLMRobertaPreTrainedModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A : Optional[int] = [
'''TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFXLMRobertaForCausalLM''',
'''TFXLMRobertaForMaskedLM''',
'''TFXLMRobertaForMultipleChoice''',
'''TFXLMRobertaForQuestionAnswering''',
'''TFXLMRobertaForSequenceClassification''',
'''TFXLMRobertaForTokenClassification''',
'''TFXLMRobertaModel''',
'''TFXLMRobertaPreTrainedModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A : Optional[Any] = [
'''FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''FlaxXLMRobertaForMaskedLM''',
'''FlaxXLMRobertaForCausalLM''',
'''FlaxXLMRobertaForMultipleChoice''',
'''FlaxXLMRobertaForQuestionAnswering''',
'''FlaxXLMRobertaForSequenceClassification''',
'''FlaxXLMRobertaForTokenClassification''',
'''FlaxXLMRobertaModel''',
'''FlaxXLMRobertaPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_xlm_roberta import (
XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
XLMRobertaConfig,
XLMRobertaOnnxConfig,
)
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_xlm_roberta import XLMRobertaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xlm_roberta import (
XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
XLMRobertaForCausalLM,
XLMRobertaForMaskedLM,
XLMRobertaForMultipleChoice,
XLMRobertaForQuestionAnswering,
XLMRobertaForSequenceClassification,
XLMRobertaForTokenClassification,
XLMRobertaModel,
XLMRobertaPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_xlm_roberta import (
TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
TFXLMRobertaForCausalLM,
TFXLMRobertaForMaskedLM,
TFXLMRobertaForMultipleChoice,
TFXLMRobertaForQuestionAnswering,
TFXLMRobertaForSequenceClassification,
TFXLMRobertaForTokenClassification,
TFXLMRobertaModel,
TFXLMRobertaPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_xlm_roberta import (
FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
FlaxXLMRobertaForCausalLM,
FlaxXLMRobertaForMaskedLM,
FlaxXLMRobertaForMultipleChoice,
FlaxXLMRobertaForQuestionAnswering,
FlaxXLMRobertaForSequenceClassification,
FlaxXLMRobertaForTokenClassification,
FlaxXLMRobertaModel,
FlaxXLMRobertaPreTrainedModel,
)
else:
import sys
A : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 128 |
'''simple docstring'''
from math import factorial
def lowerCAmelCase__ ( lowerCamelCase : int ,lowerCamelCase : int ,lowerCamelCase : float ):
if successes > trials:
raise ValueError('successes must be lower or equal to trials' )
if trials < 0 or successes < 0:
raise ValueError('the function is defined for non-negative integers' )
if not isinstance(lowerCamelCase ,lowerCamelCase ) or not isinstance(lowerCamelCase ,lowerCamelCase ):
raise ValueError('the function is defined for non-negative integers' )
if not 0 < prob < 1:
raise ValueError('prob has to be in range of 1 - 0' )
_A : str = (prob**successes) * ((1 - prob) ** (trials - successes))
# Calculate the binomial coefficient: n! / k!(n-k)!
_A : Any = float(factorial(lowerCamelCase ) )
coefficient /= factorial(lowerCamelCase ) * factorial(trials - successes )
return probability * coefficient
if __name__ == "__main__":
from doctest import testmod
testmod()
print('''Probability of 2 successes out of 4 trails''')
print('''with probability of 0.75 is:''', end=''' ''')
print(binomial_distribution(2, 4, 0.75))
| 128 | 1 |
'''simple docstring'''
from typing import Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format
from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images
from ...utils import TensorType, logging
a__ : Any = logging.get_logger(__name__)
class lowercase ( UpperCAmelCase_ ):
"""simple docstring"""
snake_case_ = ['pixel_values']
def __init__( self : str , a_ : bool = True , a_ : Union[int, float] = 1 / 2_55 , a_ : bool = True , a_ : int = 8 , **a_ : Optional[Any] , ):
"""simple docstring"""
super().__init__(**a_ )
lowerCamelCase__ = do_rescale
lowerCamelCase__ = rescale_factor
lowerCamelCase__ = do_pad
lowerCamelCase__ = pad_size
def _UpperCamelCase ( self : Dict , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : str ):
"""simple docstring"""
return rescale(a_ , scale=a_ , data_format=a_ , **a_ )
def _UpperCamelCase ( self : int , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None ):
"""simple docstring"""
lowerCamelCase__ , lowerCamelCase__ = get_image_size(a_ )
lowerCamelCase__ = (old_height // size + 1) * size - old_height
lowerCamelCase__ = (old_width // size + 1) * size - old_width
return pad(a_ , ((0, pad_height), (0, pad_width)) , mode="""symmetric""" , data_format=a_ )
def _UpperCamelCase ( self : int , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Tuple , ):
"""simple docstring"""
lowerCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale
lowerCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor
lowerCamelCase__ = do_pad if do_pad is not None else self.do_pad
lowerCamelCase__ = pad_size if pad_size is not None else self.pad_size
lowerCamelCase__ = make_list_of_images(a_ )
if not valid_images(a_ ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
# All transformations expect numpy arrays.
lowerCamelCase__ = [to_numpy_array(a_ ) for image in images]
if do_rescale:
lowerCamelCase__ = [self.rescale(image=a_ , scale=a_ ) for image in images]
if do_pad:
lowerCamelCase__ = [self.pad(a_ , size=a_ ) for image in images]
lowerCamelCase__ = [to_channel_dimension_format(a_ , a_ ) for image in images]
lowerCamelCase__ = {"""pixel_values""": images}
return BatchFeature(data=a_ , tensor_type=a_ )
| 710 |
def snake_case (UpperCamelCase : Union[str, Any] ):
'''simple docstring'''
lowerCamelCase__ = 0
lowerCamelCase__ = len(UpperCamelCase )
for i in range(n - 1 ):
for j in range(i + 1 , UpperCamelCase ):
if arr[i] > arr[j]:
num_inversions += 1
return num_inversions
def snake_case (UpperCamelCase : Optional[Any] ):
'''simple docstring'''
if len(UpperCamelCase ) <= 1:
return arr, 0
lowerCamelCase__ = len(UpperCamelCase ) // 2
lowerCamelCase__ = arr[0:mid]
lowerCamelCase__ = arr[mid:]
lowerCamelCase__ , lowerCamelCase__ = count_inversions_recursive(UpperCamelCase )
lowerCamelCase__ , lowerCamelCase__ = count_inversions_recursive(UpperCamelCase )
lowerCamelCase__ , lowerCamelCase__ = _count_cross_inversions(UpperCamelCase , UpperCamelCase )
lowerCamelCase__ = inversion_p + inversions_q + cross_inversions
return c, num_inversions
def snake_case (UpperCamelCase : str , UpperCamelCase : List[Any] ):
'''simple docstring'''
lowerCamelCase__ = []
lowerCamelCase__ = lowerCamelCase__ = lowerCamelCase__ = 0
while i < len(UpperCamelCase ) and j < len(UpperCamelCase ):
if p[i] > q[j]:
# if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P)
# These are all inversions. The claim emerges from the
# property that P is sorted.
num_inversion += len(UpperCamelCase ) - i
r.append(q[j] )
j += 1
else:
r.append(p[i] )
i += 1
if i < len(UpperCamelCase ):
r.extend(p[i:] )
else:
r.extend(q[j:] )
return r, num_inversion
def snake_case ():
'''simple docstring'''
lowerCamelCase__ = [10, 2, 1, 5, 5, 2, 11]
# this arr has 8 inversions:
# (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2)
lowerCamelCase__ = count_inversions_bf(UpperCamelCase )
lowerCamelCase__ , lowerCamelCase__ = count_inversions_recursive(UpperCamelCase )
assert num_inversions_bf == num_inversions_recursive == 8
print("""number of inversions = """ , UpperCamelCase )
# testing an array with zero inversion (a sorted arr_1)
arr_a.sort()
lowerCamelCase__ = count_inversions_bf(UpperCamelCase )
lowerCamelCase__ , lowerCamelCase__ = count_inversions_recursive(UpperCamelCase )
assert num_inversions_bf == num_inversions_recursive == 0
print("""number of inversions = """ , UpperCamelCase )
# an empty list should also have zero inversions
lowerCamelCase__ = []
lowerCamelCase__ = count_inversions_bf(UpperCamelCase )
lowerCamelCase__ , lowerCamelCase__ = count_inversions_recursive(UpperCamelCase )
assert num_inversions_bf == num_inversions_recursive == 0
print("""number of inversions = """ , UpperCamelCase )
if __name__ == "__main__":
main()
| 235 | 0 |
import shutil
import tempfile
import unittest
from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available
from transformers.testing_utils import (
get_tests_dir,
nested_simplify,
require_sentencepiece,
require_tokenizers,
require_torch,
)
from ...test_tokenization_common import TokenizerTesterMixin
UpperCAmelCase_ : Any = get_tests_dir("fixtures/test_sentencepiece.model")
if is_torch_available():
from transformers.models.mbart.modeling_mbart import shift_tokens_right
UpperCAmelCase_ : int = 250004
UpperCAmelCase_ : List[str] = 250020
@require_sentencepiece
@require_tokenizers
class __A ( UpperCamelCase__ , unittest.TestCase ):
UpperCamelCase = MBartTokenizer
UpperCamelCase = MBartTokenizerFast
UpperCamelCase = True
UpperCamelCase = True
def A__ ( self :Union[str, Any] ):
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
__magic_name__ : List[str] =MBartTokenizer(__snake_case , keep_accents=__snake_case )
tokenizer.save_pretrained(self.tmpdirname )
def A__ ( self :str ):
'''simple docstring'''
__magic_name__ : Any =MBartTokenizer(__snake_case , keep_accents=__snake_case )
__magic_name__ : int =tokenizer.tokenize("""This is a test""" )
self.assertListEqual(__snake_case , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(__snake_case ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , )
__magic_name__ : Optional[int] =tokenizer.tokenize("""I was born in 92000, and this is falsé.""" )
self.assertListEqual(
__snake_case , [
SPIECE_UNDERLINE + """I""",
SPIECE_UNDERLINE + """was""",
SPIECE_UNDERLINE + """b""",
"""or""",
"""n""",
SPIECE_UNDERLINE + """in""",
SPIECE_UNDERLINE + """""",
"""9""",
"""2""",
"""0""",
"""0""",
"""0""",
""",""",
SPIECE_UNDERLINE + """and""",
SPIECE_UNDERLINE + """this""",
SPIECE_UNDERLINE + """is""",
SPIECE_UNDERLINE + """f""",
"""al""",
"""s""",
"""é""",
""".""",
] , )
__magic_name__ : Optional[Any] =tokenizer.convert_tokens_to_ids(__snake_case )
self.assertListEqual(
__snake_case , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4]
# ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^
] , )
__magic_name__ : Any =tokenizer.convert_ids_to_tokens(__snake_case )
self.assertListEqual(
__snake_case , [
SPIECE_UNDERLINE + """I""",
SPIECE_UNDERLINE + """was""",
SPIECE_UNDERLINE + """b""",
"""or""",
"""n""",
SPIECE_UNDERLINE + """in""",
SPIECE_UNDERLINE + """""",
"""<unk>""",
"""2""",
"""0""",
"""0""",
"""0""",
""",""",
SPIECE_UNDERLINE + """and""",
SPIECE_UNDERLINE + """this""",
SPIECE_UNDERLINE + """is""",
SPIECE_UNDERLINE + """f""",
"""al""",
"""s""",
"""<unk>""",
""".""",
] , )
def A__ ( self :Tuple ):
'''simple docstring'''
if not self.test_slow_tokenizer:
# as we don't have a slow version, we can't compare the outputs between slow and fast versions
return
__magic_name__ : Tuple =(self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart""", {})
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ):
__magic_name__ : List[Any] =self.rust_tokenizer_class.from_pretrained(__snake_case , **__snake_case )
__magic_name__ : List[str] =self.tokenizer_class.from_pretrained(__snake_case , **__snake_case )
__magic_name__ : Optional[Any] =tempfile.mkdtemp()
__magic_name__ : Dict =tokenizer_r.save_pretrained(__snake_case )
__magic_name__ : Dict =tokenizer_p.save_pretrained(__snake_case )
# Checks it save with the same files + the tokenizer.json file for the fast one
self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) )
__magic_name__ : int =tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f )
self.assertSequenceEqual(__snake_case , __snake_case )
# Checks everything loads correctly in the same way
__magic_name__ : Any =tokenizer_r.from_pretrained(__snake_case )
__magic_name__ : List[Any] =tokenizer_p.from_pretrained(__snake_case )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(__snake_case , __snake_case ) )
# self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key))
# self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id"))
shutil.rmtree(__snake_case )
# Save tokenizer rust, legacy_format=True
__magic_name__ : List[str] =tempfile.mkdtemp()
__magic_name__ : Optional[int] =tokenizer_r.save_pretrained(__snake_case , legacy_format=__snake_case )
__magic_name__ : Dict =tokenizer_p.save_pretrained(__snake_case )
# Checks it save with the same files
self.assertSequenceEqual(__snake_case , __snake_case )
# Checks everything loads correctly in the same way
__magic_name__ : Any =tokenizer_r.from_pretrained(__snake_case )
__magic_name__ : int =tokenizer_p.from_pretrained(__snake_case )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(__snake_case , __snake_case ) )
shutil.rmtree(__snake_case )
# Save tokenizer rust, legacy_format=False
__magic_name__ : List[Any] =tempfile.mkdtemp()
__magic_name__ : Dict =tokenizer_r.save_pretrained(__snake_case , legacy_format=__snake_case )
__magic_name__ : List[str] =tokenizer_p.save_pretrained(__snake_case )
# Checks it saved the tokenizer.json file
self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) )
# Checks everything loads correctly in the same way
__magic_name__ : str =tokenizer_r.from_pretrained(__snake_case )
__magic_name__ : Optional[int] =tokenizer_p.from_pretrained(__snake_case )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(__snake_case , __snake_case ) )
shutil.rmtree(__snake_case )
@require_torch
@require_sentencepiece
@require_tokenizers
class __A ( unittest.TestCase ):
UpperCamelCase = """facebook/mbart-large-en-ro"""
UpperCamelCase = [
""" UN Chief Says There Is No Military Solution in Syria""",
""" Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""",
]
UpperCamelCase = [
"""Şeful ONU declară că nu există o soluţie militară în Siria""",
"""Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei"""
""" pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor"""
""" face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""",
]
UpperCamelCase = [8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2, EN_CODE]
@classmethod
def A__ ( cls :str ):
'''simple docstring'''
__magic_name__ : MBartTokenizer =MBartTokenizer.from_pretrained(
cls.checkpoint_name , src_lang="""en_XX""" , tgt_lang="""ro_RO""" )
__magic_name__ : Any =1
return cls
def A__ ( self :Any ):
'''simple docstring'''
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""] , 25_00_01 )
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""] , 25_00_04 )
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""] , 25_00_20 )
def A__ ( self :Optional[Any] ):
'''simple docstring'''
__magic_name__ : Any =self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0]
self.assertListEqual(self.expected_src_tokens , __snake_case )
def A__ ( self :List[Any] ):
'''simple docstring'''
self.assertIn(__snake_case , self.tokenizer.all_special_ids )
__magic_name__ : Union[str, Any] =[RO_CODE, 8_84, 90_19, 96, 9, 9_16, 8_67_92, 36, 1_87_43, 1_55_96, 5, 2]
__magic_name__ : Optional[int] =self.tokenizer.decode(__snake_case , skip_special_tokens=__snake_case )
__magic_name__ : List[str] =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__snake_case )
self.assertEqual(__snake_case , __snake_case )
self.assertNotIn(self.tokenizer.eos_token , __snake_case )
def A__ ( self :Tuple ):
'''simple docstring'''
__magic_name__ : str =["""this is gunna be a long sentence """ * 20]
assert isinstance(src_text[0] , __snake_case )
__magic_name__ : Dict =10
__magic_name__ : Optional[Any] =self.tokenizer(__snake_case , max_length=__snake_case , truncation=__snake_case ).input_ids[0]
self.assertEqual(ids[-2] , 2 )
self.assertEqual(ids[-1] , __snake_case )
self.assertEqual(len(__snake_case ) , __snake_case )
def A__ ( self :Optional[Any] ):
'''simple docstring'''
self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [25_00_26, 25_00_01] )
def A__ ( self :Optional[Any] ):
'''simple docstring'''
__magic_name__ : Optional[int] =tempfile.mkdtemp()
__magic_name__ : Dict =self.tokenizer.fairseq_tokens_to_ids
self.tokenizer.save_pretrained(__snake_case )
__magic_name__ : Dict =MBartTokenizer.from_pretrained(__snake_case )
self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __snake_case )
@require_torch
def A__ ( self :List[Any] ):
'''simple docstring'''
__magic_name__ : Any =self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__snake_case , return_tensors="""pt""" )
__magic_name__ : str =shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id )
# fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE]
assert batch.decoder_input_ids[1][0].tolist() == RO_CODE
assert batch.decoder_input_ids[1][-1] == 2
assert batch.labels[1][-2:].tolist() == [2, RO_CODE]
@require_torch
def A__ ( self :Optional[Any] ):
'''simple docstring'''
__magic_name__ : List[Any] =self.tokenizer(
self.src_text , text_target=self.tgt_text , padding=__snake_case , truncation=__snake_case , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , )
__magic_name__ : Any =shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id )
self.assertIsInstance(__snake_case , __snake_case )
self.assertEqual((2, 14) , batch.input_ids.shape )
self.assertEqual((2, 14) , batch.attention_mask.shape )
__magic_name__ : int =batch.input_ids.tolist()[0]
self.assertListEqual(self.expected_src_tokens , __snake_case )
self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS
# Test that special tokens are reset
self.assertEqual(self.tokenizer.prefix_tokens , [] )
self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] )
def A__ ( self :List[str] ):
'''simple docstring'''
__magic_name__ : Tuple =self.tokenizer(self.src_text , padding=__snake_case , truncation=__snake_case , max_length=3 , return_tensors="""pt""" )
__magic_name__ : Tuple =self.tokenizer(
text_target=self.tgt_text , padding=__snake_case , truncation=__snake_case , max_length=10 , return_tensors="""pt""" )
__magic_name__ : List[Any] =targets["""input_ids"""]
__magic_name__ : List[str] =shift_tokens_right(__snake_case , self.tokenizer.pad_token_id )
self.assertEqual(batch.input_ids.shape[1] , 3 )
self.assertEqual(batch.decoder_input_ids.shape[1] , 10 )
@require_torch
def A__ ( self :str ):
'''simple docstring'''
__magic_name__ : Union[str, Any] =self.tokenizer._build_translation_inputs(
"""A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""ar_AR""" )
self.assertEqual(
nested_simplify(__snake_case ) , {
# A, test, EOS, en_XX
"""input_ids""": [[62, 30_34, 2, 25_00_04]],
"""attention_mask""": [[1, 1, 1, 1]],
# ar_AR
"""forced_bos_token_id""": 25_00_01,
} , )
| 21 |
import string
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = """"""
for i in sequence:
__magic_name__ = ord(A_ )
if 65 <= extract <= 90:
output += chr(155 - extract )
elif 97 <= extract <= 122:
output += chr(219 - extract )
else:
output += i
return output
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = string.ascii_letters
__magic_name__ = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
return "".join(
letters_reversed[letters.index(A_ )] if c in letters else c for c in sequence )
def a__ ( ):
'''simple docstring'''
from timeit import timeit
print("""Running performance benchmarks...""" )
__magic_name__ = """from string import printable ; from __main__ import atbash, atbash_slow"""
print(f'''> atbash_slow(): {timeit('atbash_slow(printable)', setup=A_ )} seconds''' )
print(f'''> atbash(): {timeit('atbash(printable)', setup=A_ )} seconds''' )
if __name__ == "__main__":
for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
print(F'''{example} encrypted in atbash: {atbash(example)}''')
benchmark()
| 529 | 0 |
'''simple docstring'''
def lowerCAmelCase (__A):
"""simple docstring"""
_a = [0] * len(__A)
_a = []
_a = []
_a = 0
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(__A)):
if indegree[i] == 0:
queue.append(__A)
while queue:
_a = queue.pop(0)
cnt += 1
topo.append(__A)
for x in graph[vertex]:
indegree[x] -= 1
if indegree[x] == 0:
queue.append(__A)
if cnt != len(__A):
print('''Cycle exists''')
else:
print(__A)
# Adjacency List of Graph
lowercase_ = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
topological_sort(graph)
| 705 |
'''simple docstring'''
from __future__ import annotations
import math
def lowerCAmelCase (__A , __A , __A , __A , __A):
"""simple docstring"""
if depth < 0:
raise ValueError('''Depth cannot be less than 0''')
if not scores:
raise ValueError('''Scores cannot be empty''')
if depth == height:
return scores[node_index]
return (
max(
minimax(depth + 1 , node_index * 2 , __A , __A , __A) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A) , )
if is_max
else min(
minimax(depth + 1 , node_index * 2 , __A , __A , __A) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A) , )
)
def lowerCAmelCase ():
"""simple docstring"""
_a = [90, 23, 6, 33, 21, 65, 123, 34_423]
_a = math.log(len(__A) , 2)
print(F'''Optimal value : {minimax(0 , 0 , __A , __A , __A)}''')
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 352 | 0 |
import argparse
import json
from pathlib import Path
import torch
import torchaudio
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification
from transformers.utils import logging
logging.set_verbosity_info()
lowerCamelCase__ = logging.get_logger(__name__)
def UpperCamelCase ( snake_case__ : int ):
'''simple docstring'''
__snake_case :Dict = ASTConfig()
if "10-10" in model_name:
pass
elif "speech-commands" in model_name:
__snake_case :int = 128
elif "12-12" in model_name:
__snake_case :int = 12
__snake_case :Optional[Any] = 12
elif "14-14" in model_name:
__snake_case :List[str] = 14
__snake_case :str = 14
elif "16-16" in model_name:
__snake_case :List[Any] = 16
__snake_case :Dict = 16
else:
raise ValueError("""Model not supported""" )
__snake_case :Optional[int] = '''huggingface/label-files'''
if "speech-commands" in model_name:
__snake_case :List[str] = 35
__snake_case :int = '''speech-commands-v2-id2label.json'''
else:
__snake_case :List[Any] = 527
__snake_case :List[Any] = '''audioset-id2label.json'''
__snake_case :List[Any] = json.load(open(hf_hub_download(UpperCamelCase__ ,UpperCamelCase__ ,repo_type="""dataset""" ) ,"""r""" ) )
__snake_case :Optional[int] = {int(UpperCamelCase__ ): v for k, v in idalabel.items()}
__snake_case :Union[str, Any] = idalabel
__snake_case :str = {v: k for k, v in idalabel.items()}
return config
def UpperCamelCase ( snake_case__ : Dict ):
'''simple docstring'''
if "module.v" in name:
__snake_case :Optional[int] = name.replace("""module.v""" ,"""audio_spectrogram_transformer""" )
if "cls_token" in name:
__snake_case :List[Any] = name.replace("""cls_token""" ,"""embeddings.cls_token""" )
if "dist_token" in name:
__snake_case :List[str] = name.replace("""dist_token""" ,"""embeddings.distillation_token""" )
if "pos_embed" in name:
__snake_case :Optional[int] = name.replace("""pos_embed""" ,"""embeddings.position_embeddings""" )
if "patch_embed.proj" in name:
__snake_case :Optional[Any] = name.replace("""patch_embed.proj""" ,"""embeddings.patch_embeddings.projection""" )
# transformer blocks
if "blocks" in name:
__snake_case :Optional[Any] = name.replace("""blocks""" ,"""encoder.layer""" )
if "attn.proj" in name:
__snake_case :List[Any] = name.replace("""attn.proj""" ,"""attention.output.dense""" )
if "attn" in name:
__snake_case :List[Any] = name.replace("""attn""" ,"""attention.self""" )
if "norm1" in name:
__snake_case :Tuple = name.replace("""norm1""" ,"""layernorm_before""" )
if "norm2" in name:
__snake_case :Any = name.replace("""norm2""" ,"""layernorm_after""" )
if "mlp.fc1" in name:
__snake_case :Optional[Any] = name.replace("""mlp.fc1""" ,"""intermediate.dense""" )
if "mlp.fc2" in name:
__snake_case :Dict = name.replace("""mlp.fc2""" ,"""output.dense""" )
# final layernorm
if "audio_spectrogram_transformer.norm" in name:
__snake_case :Optional[Any] = name.replace("""audio_spectrogram_transformer.norm""" ,"""audio_spectrogram_transformer.layernorm""" )
# classifier head
if "module.mlp_head.0" in name:
__snake_case :int = name.replace("""module.mlp_head.0""" ,"""classifier.layernorm""" )
if "module.mlp_head.1" in name:
__snake_case :List[Any] = name.replace("""module.mlp_head.1""" ,"""classifier.dense""" )
return name
def UpperCamelCase ( snake_case__ : Optional[int] ,snake_case__ : Optional[Any] ):
'''simple docstring'''
for key in orig_state_dict.copy().keys():
__snake_case :Any = orig_state_dict.pop(UpperCamelCase__ )
if "qkv" in key:
__snake_case :Tuple = key.split(""".""" )
__snake_case :str = int(key_split[3] )
__snake_case :Union[str, Any] = config.hidden_size
if "weight" in key:
__snake_case :Optional[int] = val[:dim, :]
__snake_case :List[Any] = val[dim : dim * 2, :]
__snake_case :List[str] = val[-dim:, :]
else:
__snake_case :str = val[:dim]
__snake_case :Optional[int] = val[dim : dim * 2]
__snake_case :Any = val[-dim:]
else:
__snake_case :List[str] = val
return orig_state_dict
def UpperCamelCase ( snake_case__ : Union[str, Any] ):
'''simple docstring'''
__snake_case :Union[str, Any] = [
'''module.v.head.weight''',
'''module.v.head.bias''',
'''module.v.head_dist.weight''',
'''module.v.head_dist.bias''',
]
for k in ignore_keys:
state_dict.pop(UpperCamelCase__ ,UpperCamelCase__ )
@torch.no_grad()
def UpperCamelCase ( snake_case__ : int ,snake_case__ : Optional[Any] ,snake_case__ : List[str]=False ):
'''simple docstring'''
__snake_case :List[str] = get_audio_spectrogram_transformer_config(UpperCamelCase__ )
__snake_case :Union[str, Any] = {
'''ast-finetuned-audioset-10-10-0.4593''': (
'''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.450''': (
'''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.448''': (
'''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.448-v2''': (
'''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1'''
),
'''ast-finetuned-audioset-12-12-0.447''': (
'''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1'''
),
'''ast-finetuned-audioset-14-14-0.443''': (
'''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1'''
),
'''ast-finetuned-audioset-16-16-0.442''': (
'''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1'''
),
'''ast-finetuned-speech-commands-v2''': (
'''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1'''
),
}
# load original state_dict
__snake_case :Optional[Any] = model_name_to_url[model_name]
__snake_case :str = torch.hub.load_state_dict_from_url(UpperCamelCase__ ,map_location="""cpu""" )
# remove some keys
remove_keys(UpperCamelCase__ )
# rename some keys
__snake_case :List[str] = convert_state_dict(UpperCamelCase__ ,UpperCamelCase__ )
# load 🤗 model
__snake_case :Optional[int] = ASTForAudioClassification(UpperCamelCase__ )
model.eval()
model.load_state_dict(UpperCamelCase__ )
# verify outputs on dummy input
# source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62
__snake_case :Any = -4.2_6_7_7_3_9_3 if '''speech-commands''' not in model_name else -6.8_4_5_9_7_8
__snake_case :List[Any] = 4.5_6_8_9_9_7_4 if '''speech-commands''' not in model_name else 5.5_6_5_4_5_2_6
__snake_case :str = 1024 if '''speech-commands''' not in model_name else 128
__snake_case :int = ASTFeatureExtractor(mean=UpperCamelCase__ ,std=UpperCamelCase__ ,max_length=UpperCamelCase__ )
if "speech-commands" in model_name:
__snake_case :Tuple = load_dataset("""speech_commands""" ,"""v0.02""" ,split="""validation""" )
__snake_case :List[str] = dataset[0]['''audio''']['''array''']
else:
__snake_case :Dict = hf_hub_download(
repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" ,filename="""sample_audio.flac""" ,repo_type="""dataset""" ,)
__snake_case :Union[str, Any] = torchaudio.load(UpperCamelCase__ )
__snake_case :str = waveform.squeeze().numpy()
__snake_case :Any = feature_extractor(UpperCamelCase__ ,sampling_rate=1_6000 ,return_tensors="""pt""" )
# forward pass
__snake_case :Optional[Any] = model(**UpperCamelCase__ )
__snake_case :str = outputs.logits
if model_name == "ast-finetuned-audioset-10-10-0.4593":
__snake_case :Any = torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2] )
elif model_name == "ast-finetuned-audioset-10-10-0.450":
__snake_case :Union[str, Any] = torch.tensor([-1.1_9_8_6, -7.0_9_0_3, -8.2_7_1_8] )
elif model_name == "ast-finetuned-audioset-10-10-0.448":
__snake_case :str = torch.tensor([-2.6_1_2_8, -8.0_0_8_0, -9.4_3_4_4] )
elif model_name == "ast-finetuned-audioset-10-10-0.448-v2":
__snake_case :List[str] = torch.tensor([-1.5_0_8_0, -7.4_5_3_4, -8.8_9_1_7] )
elif model_name == "ast-finetuned-audioset-12-12-0.447":
__snake_case :Optional[Any] = torch.tensor([-0.5_0_5_0, -6.5_8_3_3, -8.0_8_4_3] )
elif model_name == "ast-finetuned-audioset-14-14-0.443":
__snake_case :Tuple = torch.tensor([-0.3_8_2_6, -7.0_3_3_6, -8.2_4_1_3] )
elif model_name == "ast-finetuned-audioset-16-16-0.442":
__snake_case :str = torch.tensor([-1.2_1_1_3, -6.9_1_0_1, -8.3_4_7_0] )
elif model_name == "ast-finetuned-speech-commands-v2":
__snake_case :int = torch.tensor([6.1_5_8_9, -8.0_5_6_6, -8.7_9_8_4] )
else:
raise ValueError("""Unknown model name""" )
if not torch.allclose(logits[0, :3] ,UpperCamelCase__ ,atol=1e-4 ):
raise ValueError("""Logits don\'t match""" )
print("""Looks ok!""" )
if pytorch_dump_folder_path is not None:
Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ )
print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(UpperCamelCase__ )
print(f'''Saving feature extractor to {pytorch_dump_folder_path}''' )
feature_extractor.save_pretrained(UpperCamelCase__ )
if push_to_hub:
print("""Pushing model and feature extractor to the hub...""" )
model.push_to_hub(f'''MIT/{model_name}''' )
feature_extractor.push_to_hub(f'''MIT/{model_name}''' )
if __name__ == "__main__":
lowerCamelCase__ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--model_name""",
default="""ast-finetuned-audioset-10-10-0.4593""",
type=str,
help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
parser.add_argument(
"""--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
)
lowerCamelCase__ = parser.parse_args()
convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 455 |
def lowerCAmelCase ( UpperCamelCase__ : int , UpperCamelCase__ : float , UpperCamelCase__ : float ) -> float:
"""simple docstring"""
return round(float(moles / volume ) * nfactor )
def lowerCAmelCase ( UpperCamelCase__ : float , UpperCamelCase__ : float , UpperCamelCase__ : float ) -> float:
"""simple docstring"""
return round(float((moles * 0.08_21 * temperature) / (volume) ) )
def lowerCAmelCase ( UpperCamelCase__ : float , UpperCamelCase__ : float , UpperCamelCase__ : float ) -> float:
"""simple docstring"""
return round(float((moles * 0.08_21 * temperature) / (pressure) ) )
def lowerCAmelCase ( UpperCamelCase__ : float , UpperCamelCase__ : float , UpperCamelCase__ : float ) -> float:
"""simple docstring"""
return round(float((pressure * volume) / (0.08_21 * moles) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 202 | 0 |
"""simple docstring"""
from collections import Counter
from pathlib import Path
from typing import Optional, Tuple
import yaml
class _lowercase ( yaml.SafeLoader ):
"""simple docstring"""
def UpperCAmelCase_ ( self : Any , UpperCamelCase__ : Dict ) -> Optional[Any]:
'''simple docstring'''
__UpperCamelCase =[self.constructed_objects[key_node] for key_node, _ in node.value]
__UpperCamelCase =[tuple(UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else key for key in keys]
__UpperCamelCase =Counter(UpperCamelCase__ )
__UpperCamelCase =[key for key in counter if counter[key] > 1]
if duplicate_keys:
raise TypeError(f"""Got duplicate yaml keys: {duplicate_keys}""" )
def UpperCAmelCase_ ( self : Dict , UpperCamelCase__ : int , UpperCamelCase__ : Tuple=False ) -> Dict:
'''simple docstring'''
__UpperCamelCase =super().construct_mapping(UpperCamelCase__ , deep=UpperCamelCase__ )
self._check_no_duplicates_on_constructed_node(UpperCamelCase__ )
return mapping
def lowerCAmelCase (__UpperCamelCase : str ):
"""simple docstring"""
__UpperCamelCase =list(readme_content.splitlines() )
if full_content and full_content[0] == "---" and "---" in full_content[1:]:
__UpperCamelCase =full_content[1:].index('''---''' ) + 1
__UpperCamelCase ='''\n'''.join(full_content[1:sep_idx] )
return yamlblock, "\n".join(full_content[sep_idx + 1 :] )
return None, "\n".join(__UpperCamelCase )
class _lowercase ( __a ):
"""simple docstring"""
lowercase__ = {'''train_eval_index'''} # train-eval-index in the YAML metadata
@classmethod
def UpperCAmelCase_ ( cls : int , UpperCamelCase__ : Path ) -> "DatasetMetadata":
'''simple docstring'''
with open(UpperCamelCase__ , encoding='''utf-8''' ) as readme_file:
__UpperCamelCase , __UpperCamelCase =_split_yaml_from_readme(readme_file.read() )
if yaml_string is not None:
return cls.from_yaml_string(UpperCamelCase__ )
else:
return cls()
def UpperCAmelCase_ ( self : Union[str, Any] , UpperCamelCase__ : Path ) -> Any:
'''simple docstring'''
if path.exists():
with open(UpperCamelCase__ , encoding='''utf-8''' ) as readme_file:
__UpperCamelCase =readme_file.read()
else:
__UpperCamelCase =None
__UpperCamelCase =self._to_readme(UpperCamelCase__ )
with open(UpperCamelCase__ , '''w''' , encoding='''utf-8''' ) as readme_file:
readme_file.write(UpperCamelCase__ )
def UpperCAmelCase_ ( self : Optional[Any] , UpperCamelCase__ : Optional[str] = None ) -> str:
'''simple docstring'''
if readme_content is not None:
__UpperCamelCase , __UpperCamelCase =_split_yaml_from_readme(UpperCamelCase__ )
__UpperCamelCase ='''---\n''' + self.to_yaml_string() + '''---\n''' + content
else:
__UpperCamelCase ='''---\n''' + self.to_yaml_string() + '''---\n'''
return full_content
@classmethod
def UpperCAmelCase_ ( cls : Dict , UpperCamelCase__ : str ) -> "DatasetMetadata":
'''simple docstring'''
__UpperCamelCase =yaml.load(UpperCamelCase__ , Loader=_NoDuplicateSafeLoader ) or {}
# Convert the YAML keys to DatasetMetadata fields
__UpperCamelCase ={
(key.replace('''-''' , '''_''' ) if key.replace('''-''' , '''_''' ) in cls._FIELDS_WITH_DASHES else key): value
for key, value in metadata_dict.items()
}
return cls(**UpperCamelCase__ )
def UpperCAmelCase_ ( self : Dict ) -> str:
'''simple docstring'''
return yaml.safe_dump(
{
(key.replace('''_''' , '''-''' ) if key in self._FIELDS_WITH_DASHES else key): value
for key, value in self.items()
} , sort_keys=UpperCamelCase__ , allow_unicode=UpperCamelCase__ , encoding='''utf-8''' , ).decode('''utf-8''' )
__lowercase = {
'''image-classification''': [],
'''translation''': [],
'''image-segmentation''': [],
'''fill-mask''': [],
'''automatic-speech-recognition''': [],
'''token-classification''': [],
'''sentence-similarity''': [],
'''audio-classification''': [],
'''question-answering''': [],
'''summarization''': [],
'''zero-shot-classification''': [],
'''table-to-text''': [],
'''feature-extraction''': [],
'''other''': [],
'''multiple-choice''': [],
'''text-classification''': [],
'''text-to-image''': [],
'''text2text-generation''': [],
'''zero-shot-image-classification''': [],
'''tabular-classification''': [],
'''tabular-regression''': [],
'''image-to-image''': [],
'''tabular-to-text''': [],
'''unconditional-image-generation''': [],
'''text-retrieval''': [],
'''text-to-speech''': [],
'''object-detection''': [],
'''audio-to-audio''': [],
'''text-generation''': [],
'''conversational''': [],
'''table-question-answering''': [],
'''visual-question-answering''': [],
'''image-to-text''': [],
'''reinforcement-learning''': [],
'''voice-activity-detection''': [],
'''time-series-forecasting''': [],
'''document-question-answering''': [],
}
if __name__ == "__main__":
from argparse import ArgumentParser
__lowercase = ArgumentParser(usage='''Validate the yaml metadata block of a README.md file.''')
ap.add_argument('''readme_filepath''')
__lowercase = ap.parse_args()
__lowercase = Path(args.readme_filepath)
__lowercase = DatasetMetadata.from_readme(readme_filepath)
print(dataset_metadata)
dataset_metadata.to_readme(readme_filepath)
| 296 | """simple docstring"""
class _lowercase :
"""simple docstring"""
def __init__( self : Tuple , UpperCamelCase__ : Any ) -> int:
'''simple docstring'''
__UpperCamelCase =arr.split(''',''' )
def UpperCAmelCase_ ( self : List[Any] ) -> int:
'''simple docstring'''
__UpperCamelCase =[int(self.array[0] )] * len(self.array )
__UpperCamelCase =[int(self.array[0] )] * len(self.array )
for i in range(1 , len(self.array ) ):
__UpperCamelCase =max(
int(self.array[i] ) + sum_value[i - 1] , int(self.array[i] ) )
__UpperCamelCase =max(sum_value[i] , rear[i - 1] )
return rear[len(self.array ) - 1]
if __name__ == "__main__":
__lowercase = input('''please input some numbers:''')
__lowercase = SubArray(whole_array)
__lowercase = array.solve_sub_array()
print(('''the results is:''', re))
| 296 | 1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.