code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): pass class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): pass class __SCREAMING_SNAKE_CASE : def __init__( self : int ) ->Dict: lowerCamelCase__ : List[Any] = [ [], [], [], ] def __lowerCamelCase ( self : Dict , A : int , A : int ) ->None: try: if len(self.queues[priority] ) >= 1_0_0: raise OverflowError('''Maximum queue size is 100''' ) self.queues[priority].append(A ) except IndexError: raise ValueError('''Valid priorities are 0, 1, and 2''' ) def __lowerCamelCase ( self : List[Any] ) ->int: for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('''All queues are empty''' ) def __str__( self : Union[str, Any] ) ->str: return "\n".join(F"Priority {i}: {q}" for i, q in enumerate(self.queues ) ) class __SCREAMING_SNAKE_CASE : def __init__( self : Tuple ) ->List[str]: lowerCamelCase__ : List[str] = [] def __lowerCamelCase ( self : int , A : int ) ->None: if len(self.queue ) == 1_0_0: raise OverFlowError('''Maximum queue size is 100''' ) self.queue.append(A ) def __lowerCamelCase ( self : str ) ->int: if not self.queue: raise UnderFlowError('''The queue is empty''' ) else: lowerCamelCase__ : Union[str, Any] = min(self.queue ) self.queue.remove(A ) return data def __str__( self : List[Any] ) ->str: return str(self.queue ) def _a ( ) -> Optional[int]: """simple docstring""" lowerCamelCase__ : Tuple = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 100 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 128 ) print(UpperCAmelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(UpperCAmelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ) -> int: """simple docstring""" lowerCamelCase__ : str = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(100 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(128 ) print(UpperCAmelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(UpperCAmelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
142
import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor _A : str = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): def __init__( self : Dict , *A : Any , **A : List[Any] ) ->None: warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , A , ) super().__init__(*A , **A )
142
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase : str = logging.get_logger(__name__) __UpperCAmelCase : Tuple = { "google/vivit-b-16x2-kinetics400": ( "https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class __snake_case ( __lowerCamelCase ): '''simple docstring''' lowerCAmelCase__ = """vivit""" def __init__( self : List[str] , A : int=224 , A : Optional[Any]=32 , A : Any=[2, 16, 16] , A : str=3 , A : Optional[Any]=768 , A : Any=12 , A : str=12 , A : Dict=3_072 , A : List[str]="gelu_fast" , A : List[str]=0.0 , A : str=0.0 , A : Dict=0.02 , A : int=1E-06 , A : Union[str, Any]=True , **A : Tuple , ): __snake_case: int = hidden_size __snake_case: Any = num_hidden_layers __snake_case: Optional[Any] = num_attention_heads __snake_case: str = intermediate_size __snake_case: Tuple = hidden_act __snake_case: Dict = hidden_dropout_prob __snake_case: Tuple = attention_probs_dropout_prob __snake_case: int = initializer_range __snake_case: List[str] = layer_norm_eps __snake_case: Dict = image_size __snake_case: Optional[int] = num_frames __snake_case: Dict = tubelet_size __snake_case: Any = num_channels __snake_case: Dict = qkv_bias super().__init__(**A )
293
import unittest from diffusers.models.unet_ad_blocks import * # noqa F403 from diffusers.utils import torch_device from .test_unet_blocks_common import UNetBlockTesterMixin class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = DownBlockaD # noqa F405 lowerCAmelCase__ = """down""" def UpperCAmelCase__ ( self : Any ): __snake_case: str = [-0.0232, -0.9869, 0.8054, -0.0637, -0.1688, -1.4264, 0.4470, -1.3394, 0.0904] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = ResnetDownsampleBlockaD # noqa F405 lowerCAmelCase__ = """down""" def UpperCAmelCase__ ( self : Optional[int] ): __snake_case: Union[str, Any] = [0.0710, 0.2410, -0.7320, -1.0757, -1.1343, 0.3540, -0.0133, -0.2576, 0.0948] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = AttnDownBlockaD # noqa F405 lowerCAmelCase__ = """down""" def UpperCAmelCase__ ( self : Any ): __snake_case: Union[str, Any] = [0.0636, 0.8964, -0.6234, -1.0131, 0.0844, 0.4935, 0.3437, 0.0911, -0.2957] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = CrossAttnDownBlockaD # noqa F405 lowerCAmelCase__ = """down""" def UpperCAmelCase__ ( self : List[str] ): __snake_case , __snake_case: List[str] = super().prepare_init_args_and_inputs_for_common() __snake_case: List[Any] = 32 return init_dict, inputs_dict def UpperCAmelCase__ ( self : Optional[Any] ): __snake_case: Optional[Any] = [0.2238, -0.7396, -0.2255, -0.3829, 0.1925, 1.1665, 0.0603, -0.7295, 0.1983] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = SimpleCrossAttnDownBlockaD # noqa F405 lowerCAmelCase__ = """down""" @property def UpperCAmelCase__ ( self : Tuple ): return super().get_dummy_input(include_encoder_hidden_states=A ) def UpperCAmelCase__ ( self : int ): __snake_case , __snake_case: Union[str, Any] = super().prepare_init_args_and_inputs_for_common() __snake_case: Optional[Any] = 32 return init_dict, inputs_dict @unittest.skipIf(torch_device == """mps""" , """MPS result is not consistent""" ) def UpperCAmelCase__ ( self : List[Any] ): __snake_case: Optional[Any] = [0.7921, -0.0992, -0.1962, -0.7695, -0.4242, 0.7804, 0.4737, 0.2765, 0.3338] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = SkipDownBlockaD # noqa F405 lowerCAmelCase__ = """down""" @property def UpperCAmelCase__ ( self : Any ): return super().get_dummy_input(include_skip_sample=A ) def UpperCAmelCase__ ( self : Any ): __snake_case: Optional[Any] = [-0.0845, -0.2087, -0.2465, 0.0971, 0.1900, -0.0484, 0.2664, 0.4179, 0.5069] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = AttnSkipDownBlockaD # noqa F405 lowerCAmelCase__ = """down""" @property def UpperCAmelCase__ ( self : List[Any] ): return super().get_dummy_input(include_skip_sample=A ) def UpperCAmelCase__ ( self : int ): __snake_case: str = [0.5539, 0.1609, 0.4924, 0.0537, -0.1995, 0.4050, 0.0979, -0.2721, -0.0642] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = DownEncoderBlockaD # noqa F405 lowerCAmelCase__ = """down""" @property def UpperCAmelCase__ ( self : Union[str, Any] ): return super().get_dummy_input(include_temb=A ) def UpperCAmelCase__ ( self : Optional[int] ): __snake_case: str = { """in_channels""": 32, """out_channels""": 32, } __snake_case: Dict = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase__ ( self : str ): __snake_case: Optional[int] = [1.1102, 0.5302, 0.4872, -0.0023, -0.8042, 0.0483, -0.3489, -0.5632, 0.7626] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = AttnDownEncoderBlockaD # noqa F405 lowerCAmelCase__ = """down""" @property def UpperCAmelCase__ ( self : List[str] ): return super().get_dummy_input(include_temb=A ) def UpperCAmelCase__ ( self : Optional[int] ): __snake_case: Optional[Any] = { """in_channels""": 32, """out_channels""": 32, } __snake_case: Tuple = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase__ ( self : Optional[int] ): __snake_case: Dict = [0.8966, -0.1486, 0.8568, 0.8141, -0.9046, -0.1342, -0.0972, -0.7417, 0.1538] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = UNetMidBlockaD # noqa F405 lowerCAmelCase__ = """mid""" def UpperCAmelCase__ ( self : str ): __snake_case: Optional[int] = { """in_channels""": 32, """temb_channels""": 128, } __snake_case: List[str] = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase__ ( self : str ): __snake_case: Tuple = [-0.1062, 1.7248, 0.3494, 1.4569, -0.0910, -1.2421, -0.9984, 0.6736, 1.0028] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = UNetMidBlockaDCrossAttn # noqa F405 lowerCAmelCase__ = """mid""" def UpperCAmelCase__ ( self : str ): __snake_case , __snake_case: int = super().prepare_init_args_and_inputs_for_common() __snake_case: int = 32 return init_dict, inputs_dict def UpperCAmelCase__ ( self : Dict ): __snake_case: Optional[Any] = [0.0187, 2.4220, 0.4484, 1.1203, -0.6121, -1.5122, -0.8270, 0.7851, 1.8335] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = UNetMidBlockaDSimpleCrossAttn # noqa F405 lowerCAmelCase__ = """mid""" @property def UpperCAmelCase__ ( self : Optional[int] ): return super().get_dummy_input(include_encoder_hidden_states=A ) def UpperCAmelCase__ ( self : str ): __snake_case , __snake_case: Any = super().prepare_init_args_and_inputs_for_common() __snake_case: str = 32 return init_dict, inputs_dict def UpperCAmelCase__ ( self : Dict ): __snake_case: Optional[Any] = [0.7143, 1.9974, 0.5448, 1.3977, 0.1282, -1.1237, -1.4238, 0.5530, 0.8880] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = UpBlockaD # noqa F405 lowerCAmelCase__ = """up""" @property def UpperCAmelCase__ ( self : Tuple ): return super().get_dummy_input(include_res_hidden_states_tuple=A ) def UpperCAmelCase__ ( self : Tuple ): __snake_case: Tuple = [-0.2041, -0.4165, -0.3022, 0.0041, -0.6628, -0.7053, 0.1928, -0.0325, 0.0523] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = ResnetUpsampleBlockaD # noqa F405 lowerCAmelCase__ = """up""" @property def UpperCAmelCase__ ( self : Tuple ): return super().get_dummy_input(include_res_hidden_states_tuple=A ) def UpperCAmelCase__ ( self : Union[str, Any] ): __snake_case: int = [0.2287, 0.3549, -0.1346, 0.4797, -0.1715, -0.9649, 0.7305, -0.5864, -0.6244] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = CrossAttnUpBlockaD # noqa F405 lowerCAmelCase__ = """up""" @property def UpperCAmelCase__ ( self : Optional[int] ): return super().get_dummy_input(include_res_hidden_states_tuple=A ) def UpperCAmelCase__ ( self : Dict ): __snake_case , __snake_case: Any = super().prepare_init_args_and_inputs_for_common() __snake_case: Optional[int] = 32 return init_dict, inputs_dict def UpperCAmelCase__ ( self : Union[str, Any] ): __snake_case: List[Any] = [-0.1403, -0.3515, -0.0420, -0.1425, 0.3167, 0.5094, -0.2181, 0.5931, 0.5582] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = SimpleCrossAttnUpBlockaD # noqa F405 lowerCAmelCase__ = """up""" @property def UpperCAmelCase__ ( self : Optional[Any] ): return super().get_dummy_input(include_res_hidden_states_tuple=A , include_encoder_hidden_states=A ) def UpperCAmelCase__ ( self : Dict ): __snake_case , __snake_case: Optional[Any] = super().prepare_init_args_and_inputs_for_common() __snake_case: str = 32 return init_dict, inputs_dict def UpperCAmelCase__ ( self : List[Any] ): __snake_case: Union[str, Any] = [0.2645, 0.1480, 0.0909, 0.8044, -0.9758, -0.9083, 0.0994, -1.1453, -0.7402] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = AttnUpBlockaD # noqa F405 lowerCAmelCase__ = """up""" @property def UpperCAmelCase__ ( self : int ): return super().get_dummy_input(include_res_hidden_states_tuple=A ) @unittest.skipIf(torch_device == """mps""" , """MPS result is not consistent""" ) def UpperCAmelCase__ ( self : List[str] ): __snake_case: Optional[Any] = [0.0979, 0.1326, 0.0021, 0.0659, 0.2249, 0.0059, 0.1132, 0.5952, 0.1033] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = SkipUpBlockaD # noqa F405 lowerCAmelCase__ = """up""" @property def UpperCAmelCase__ ( self : str ): return super().get_dummy_input(include_res_hidden_states_tuple=A ) def UpperCAmelCase__ ( self : Dict ): __snake_case: Optional[int] = [-0.0893, -0.1234, -0.1506, -0.0332, 0.0123, -0.0211, 0.0566, 0.0143, 0.0362] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = AttnSkipUpBlockaD # noqa F405 lowerCAmelCase__ = """up""" @property def UpperCAmelCase__ ( self : str ): return super().get_dummy_input(include_res_hidden_states_tuple=A ) def UpperCAmelCase__ ( self : Optional[Any] ): __snake_case: Optional[Any] = [0.0361, 0.0617, 0.2787, -0.0350, 0.0342, 0.3421, -0.0843, 0.0913, 0.3015] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = UpDecoderBlockaD # noqa F405 lowerCAmelCase__ = """up""" @property def UpperCAmelCase__ ( self : Optional[int] ): return super().get_dummy_input(include_temb=A ) def UpperCAmelCase__ ( self : str ): __snake_case: Union[str, Any] = {"""in_channels""": 32, """out_channels""": 32} __snake_case: Dict = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase__ ( self : Any ): __snake_case: Dict = [0.4404, 0.1998, -0.9886, -0.3320, -0.3128, -0.7034, -0.6955, -0.2338, -0.3137] super().test_output(A ) class __snake_case ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = AttnUpDecoderBlockaD # noqa F405 lowerCAmelCase__ = """up""" @property def UpperCAmelCase__ ( self : Optional[Any] ): return super().get_dummy_input(include_temb=A ) def UpperCAmelCase__ ( self : Optional[Any] ): __snake_case: Optional[Any] = {"""in_channels""": 32, """out_channels""": 32} __snake_case: Any = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase__ ( self : int ): __snake_case: Any = [0.6738, 0.4491, 0.1055, 1.0710, 0.7316, 0.3339, 0.3352, 0.1023, 0.3568] super().test_output(A )
293
1
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( _a): lowerCamelCase__ : Optional[Any] = (DDPMScheduler,) def _UpperCAmelCase ( self , **a ) -> str: lowercase__ : int = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'variance_type': 'fixed_small', 'clip_sample': True, } config.update(**a ) return config def _UpperCAmelCase ( self ) -> Any: for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=a ) def _UpperCAmelCase ( self ) -> Dict: for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=a , beta_end=a ) def _UpperCAmelCase ( self ) -> Any: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=a ) def _UpperCAmelCase ( self ) -> str: for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=a ) def _UpperCAmelCase ( self ) -> Any: for clip_sample in [True, False]: self.check_over_configs(clip_sample=a ) def _UpperCAmelCase ( self ) -> Optional[int]: self.check_over_configs(thresholding=a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=a , prediction_type=a , sample_max_value=a , ) def _UpperCAmelCase ( self ) -> List[str]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=a ) def _UpperCAmelCase ( self ) -> List[str]: for t in [0, 5_0_0, 9_9_9]: self.check_over_forward(time_step=a ) def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : Optional[Any] = self.scheduler_classes[0] lowercase__ : List[Any] = self.get_scheduler_config() lowercase__ : Union[str, Any] = scheduler_class(**a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.00_979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.02 ) ) < 1e-5 def _UpperCAmelCase ( self ) -> Any: lowercase__ : Optional[Any] = self.scheduler_classes[0] lowercase__ : Optional[Any] = self.get_scheduler_config() lowercase__ : Union[str, Any] = scheduler_class(**a ) lowercase__ : List[Any] = len(a ) lowercase__ : List[Any] = self.dummy_model() lowercase__ : str = self.dummy_sample_deter lowercase__ : List[Any] = torch.manual_seed(0 ) for t in reversed(range(a ) ): # 1. predict noise residual lowercase__ : Dict = model(a , a ) # 2. predict previous mean of sample x_t-1 lowercase__ : Optional[int] = scheduler.step(a , a , a , generator=a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance lowercase__ : List[str] = pred_prev_sample lowercase__ : Any = torch.sum(torch.abs(a ) ) lowercase__ : str = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 258.9_606 ) < 1e-2 assert abs(result_mean.item() - 0.3_372 ) < 1e-3 def _UpperCAmelCase ( self ) -> Optional[int]: lowercase__ : Any = self.scheduler_classes[0] lowercase__ : Optional[int] = self.get_scheduler_config(prediction_type='v_prediction' ) lowercase__ : Optional[Any] = scheduler_class(**a ) lowercase__ : int = len(a ) lowercase__ : Dict = self.dummy_model() lowercase__ : Optional[int] = self.dummy_sample_deter lowercase__ : List[Any] = torch.manual_seed(0 ) for t in reversed(range(a ) ): # 1. predict noise residual lowercase__ : Optional[Any] = model(a , a ) # 2. predict previous mean of sample x_t-1 lowercase__ : Optional[int] = scheduler.step(a , a , a , generator=a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance lowercase__ : List[Any] = pred_prev_sample lowercase__ : Dict = torch.sum(torch.abs(a ) ) lowercase__ : List[str] = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 202.0_296 ) < 1e-2 assert abs(result_mean.item() - 0.2_631 ) < 1e-3 def _UpperCAmelCase ( self ) -> Union[str, Any]: lowercase__ : Optional[Any] = self.scheduler_classes[0] lowercase__ : Any = self.get_scheduler_config() lowercase__ : List[Any] = scheduler_class(**a ) lowercase__ : Any = [1_0_0, 8_7, 5_0, 1, 0] scheduler.set_timesteps(timesteps=a ) lowercase__ : List[Any] = scheduler.timesteps for i, timestep in enumerate(a ): if i == len(a ) - 1: lowercase__ : Union[str, Any] = -1 else: lowercase__ : int = timesteps[i + 1] lowercase__ : Tuple = scheduler.previous_timestep(a ) lowercase__ : List[Any] = prev_t.item() self.assertEqual(a , a ) def _UpperCAmelCase ( self ) -> Optional[int]: lowercase__ : Union[str, Any] = self.scheduler_classes[0] lowercase__ : List[str] = self.get_scheduler_config() lowercase__ : Any = scheduler_class(**a ) lowercase__ : Optional[Any] = [1_0_0, 8_7, 5_0, 5_1, 0] with self.assertRaises(a , msg='`custom_timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=a ) def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : Tuple = self.scheduler_classes[0] lowercase__ : int = self.get_scheduler_config() lowercase__ : int = scheduler_class(**a ) lowercase__ : Dict = [1_0_0, 8_7, 5_0, 1, 0] lowercase__ : Dict = len(a ) with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `custom_timesteps`.' ): scheduler.set_timesteps(num_inference_steps=a , timesteps=a ) def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : Union[str, Any] = self.scheduler_classes[0] lowercase__ : str = self.get_scheduler_config() lowercase__ : List[Any] = scheduler_class(**a ) lowercase__ : Union[str, Any] = [scheduler.config.num_train_timesteps] with self.assertRaises( a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=a )
77
"""simple docstring""" import argparse import shutil import time from json import JSONDecodeError from logging import getLogger from pathlib import Path from typing import Dict, List import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import ( SeqaSeqDataset, calculate_bleu, calculate_rouge, chunks, lmap, load_json, parse_numeric_n_bool_cl_kwargs, save_json, use_task_specific_params, write_txt_file, ) SCREAMING_SNAKE_CASE : List[str] = getLogger(__name__) def lowercase ( _snake_case : Tuple , _snake_case : str , _snake_case : str , _snake_case : int = 8 , _snake_case : int = 1_024 , _snake_case : Any="val" , _snake_case : Tuple=None , _snake_case : Any=False , _snake_case : str="summarization" , _snake_case : Dict=None , _snake_case : Optional[Any]=1 , _snake_case : Dict = None , _snake_case : List[Any]="" , **_snake_case : int , ) ->Dict: """simple docstring""" __snake_case : int = str(_snake_case ) assert local_rank is not None torch.distributed.init_process_group(backend='''nccl''' , rank=_snake_case ) __snake_case : Optional[Any] = Path(_snake_case ) __snake_case : str = save_dir.joinpath(f"""rank_{local_rank}_output.json""" ) torch.cuda.set_device(_snake_case ) __snake_case : Tuple = AutoModelForSeqaSeqLM.from_pretrained(_snake_case ).cuda() if fpaa: __snake_case : List[str] = model.half() # determine if we need to increase num_beams use_task_specific_params(_snake_case , _snake_case ) # update config with task specific params __snake_case : Dict = generate_kwargs.pop('''num_beams''' , model.config.num_beams ) # AttributeError risk? if num_return_sequences > num_beams: __snake_case : Optional[Any] = num_return_sequences __snake_case : Dict = AutoTokenizer.from_pretrained(_snake_case ) logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. if max_source_length is None: __snake_case : List[str] = tokenizer.model_max_length if prefix is None: __snake_case : List[str] = prefix or getattr(model.config , '''prefix''' , '''''' ) or '''''' __snake_case : List[str] = SeqaSeqDataset( _snake_case , _snake_case , _snake_case , max_target_length=1_024 , type_path=_snake_case , n_obs=_snake_case , prefix=_snake_case , **_snake_case , ) # I set shuffle=True for a more accurate progress bar. # If all the longest samples are first, the prog bar estimate is too high at the beginning. __snake_case : Union[str, Any] = ds.make_sortish_sampler(_snake_case , distributed=_snake_case , add_extra_examples=_snake_case , shuffle=_snake_case ) __snake_case : List[Any] = DataLoader(_snake_case , sampler=_snake_case , batch_size=_snake_case , collate_fn=ds.collate_fn ) __snake_case : Union[str, Any] = [] for batch in tqdm(_snake_case ): __snake_case : Tuple = model.generate( input_ids=batch['''input_ids'''].to(model.device ) , attention_mask=batch['''attention_mask'''].to(model.device ) , num_return_sequences=_snake_case , num_beams=_snake_case , **_snake_case , ) __snake_case : List[Any] = tokenizer.batch_decode(_snake_case , skip_special_tokens=_snake_case , clean_up_tokenization_spaces=_snake_case ) __snake_case : List[str] = batch['''ids'''] if num_return_sequences > 1: __snake_case : Dict = chunks(_snake_case , _snake_case ) # batch size chunks, each of size num_return_seq for i, pred in enumerate(_snake_case ): results.append({'''pred''': pred, '''id''': ids[i].item()} ) save_json(_snake_case , _snake_case ) return results, sampler.num_replicas def lowercase ( ) ->int: """simple docstring""" __snake_case : Any = argparse.ArgumentParser( epilog='''Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate''' ) parser.add_argument('''--data_dir''' , type=_snake_case , help='''like cnn_dm/test.source''' ) parser.add_argument( '''--model_name''' , type=_snake_case , help='''like facebook/bart-large-cnn,t5-base, etc.''' , default='''sshleifer/distilbart-xsum-12-3''' , ) parser.add_argument('''--save_dir''' , type=_snake_case , help='''where to save''' , default='''tmp_gen''' ) parser.add_argument('''--max_source_length''' , type=_snake_case , default=_snake_case ) parser.add_argument( '''--type_path''' , type=_snake_case , default='''test''' , help='''which subset to evaluate typically train/val/test''' ) parser.add_argument('''--task''' , type=_snake_case , default='''summarization''' , help='''used for task_specific_params + metrics''' ) parser.add_argument('''--bs''' , type=_snake_case , default=8 , required=_snake_case , help='''batch size''' ) parser.add_argument( '''--local_rank''' , type=_snake_case , default=-1 , required=_snake_case , help='''should be passed by distributed.launch''' ) parser.add_argument( '''--n_obs''' , type=_snake_case , default=_snake_case , required=_snake_case , help='''How many observations. Defaults to all.''' ) parser.add_argument( '''--num_return_sequences''' , type=_snake_case , default=1 , required=_snake_case , help='''How many sequences to return''' ) parser.add_argument( '''--sync_timeout''' , type=_snake_case , default=600 , required=_snake_case , help='''How long should master process wait for other processes to finish.''' , ) parser.add_argument('''--src_lang''' , type=_snake_case , default=_snake_case , required=_snake_case ) parser.add_argument('''--tgt_lang''' , type=_snake_case , default=_snake_case , required=_snake_case ) parser.add_argument( '''--prefix''' , type=_snake_case , required=_snake_case , default=_snake_case , help='''will be added to the begininng of src examples''' ) parser.add_argument('''--fp16''' , action='''store_true''' ) parser.add_argument('''--debug''' , action='''store_true''' ) __snake_case : str = time.time() __snake_case , __snake_case : Any = parser.parse_known_args() __snake_case : List[Any] = parse_numeric_n_bool_cl_kwargs(_snake_case ) if generate_kwargs and args.local_rank <= 0: print(f"""parsed the following generate kwargs: {generate_kwargs}""" ) __snake_case : List[Any] = Path(args.save_dir + '''_tmp''' ) Path(_snake_case ).mkdir(exist_ok=_snake_case ) # this handles locking. __snake_case : Optional[int] = list(json_save_dir.glob('''rank_*.json''' ) ) if intermediate_files: raise ValueError(f"""Found files at {json_save_dir} please move or remove them.""" ) # In theory, a node could finish and save before another node hits this. If this happens, we can address later. __snake_case : Dict = {} if args.src_lang is not None: __snake_case : Dict = args.src_lang if args.tgt_lang is not None: __snake_case : Dict = args.tgt_lang Path(args.save_dir ).mkdir(exist_ok=_snake_case ) __snake_case , __snake_case : List[Any] = eval_data_dir( args.data_dir , _snake_case , args.model_name , type_path=args.type_path , bs=args.bs , fpaa=args.fpaa , task=args.task , local_rank=args.local_rank , n_obs=args.n_obs , max_source_length=args.max_source_length , num_return_sequences=args.num_return_sequences , prefix=args.prefix , dataset_kwargs=_snake_case , **_snake_case , ) if args.local_rank <= 0: __snake_case : int = Path(args.save_dir ) save_dir.mkdir(exist_ok=_snake_case ) __snake_case : Optional[Any] = gather_results_from_each_node(_snake_case , _snake_case , args.sync_timeout ) __snake_case : str = combine_partial_results(_snake_case ) if args.num_return_sequences > 1: __snake_case : List[Any] = save_dir.joinpath('''pseudolabel_results.json''' ) print(f"""Saving aggregated results at {save_path}, intermediate in {json_save_dir}/""" ) save_json(_snake_case , _snake_case ) return __snake_case : Tuple = Path(args.data_dir ).joinpath(args.type_path + '''.target''' ) with open(_snake_case ) as f: __snake_case : Optional[Any] = [x.rstrip() for x in f.readlines()][: len(_snake_case )] # Calculate metrics, save metrics, and save _generations.txt __snake_case : List[str] = '''translation''' in args.task __snake_case : List[Any] = calculate_bleu if calc_bleu else calculate_rouge __snake_case : Dict = '''bleu''' if calc_bleu else '''rouge''' __snake_case : Dict = score_fn(_snake_case , _snake_case ) __snake_case : int = len(_snake_case ) __snake_case : Dict = time.time() - start_time __snake_case : Optional[Any] = round(runtime / metrics['''n_obs'''] , 4 ) __snake_case : List[Any] = num_replicas # TODO(@stas00): add whatever metadata to metrics __snake_case : int = save_dir.joinpath(f"""{args.type_path}_{metric_name}.json""" ) save_json(_snake_case , _snake_case , indent=_snake_case ) print(_snake_case ) write_txt_file(_snake_case , save_dir.joinpath(f"""{args.type_path}_generations.txt""" ) ) if args.debug: write_txt_file(_snake_case , save_dir.joinpath(f"""{args.type_path}.target""" ) ) else: shutil.rmtree(_snake_case ) def lowercase ( _snake_case : Union[str, Any] ) ->List: """simple docstring""" __snake_case : List[Any] = [] for partial_result in partial_results: records.extend(_snake_case ) __snake_case : List[str] = sorted(_snake_case , key=lambda _snake_case : x["id"] ) __snake_case : Tuple = [x['''pred'''] for x in records] return preds def lowercase ( _snake_case : int , _snake_case : List[str] , _snake_case : List[Any] ) ->List[Dict[str, List]]: """simple docstring""" __snake_case : List[str] = time.time() logger.info('''waiting for all nodes to finish''' ) __snake_case : List[str] = None while (time.time() - start_wait) < timeout: __snake_case : Any = list(save_dir.glob('''rank_*.json''' ) ) if len(_snake_case ) < num_replicas: continue try: # make sure all json files are fully saved __snake_case : Tuple = lmap(_snake_case , _snake_case ) return json_data except JSONDecodeError: continue else: raise TimeoutError('''Rank 0 gave up on waiting for other processes''' ) # Unreachable if __name__ == "__main__": # Usage for MT: run_generate()
102
0
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class UpperCamelCase__ : _SCREAMING_SNAKE_CASE : Optional[int] = PegasusConfig _SCREAMING_SNAKE_CASE : Union[str, Any] = {} _SCREAMING_SNAKE_CASE : List[Any] = "gelu" def __init__(self : int , snake_case_ : List[Any] , snake_case_ : Union[str, Any]=1_3 , snake_case_ : List[str]=7 , snake_case_ : Optional[int]=True , snake_case_ : Optional[Any]=False , snake_case_ : int=9_9 , snake_case_ : Union[str, Any]=3_2 , snake_case_ : Optional[Any]=2 , snake_case_ : Optional[Any]=4 , snake_case_ : List[str]=3_7 , snake_case_ : Dict=0.1 , snake_case_ : Union[str, Any]=0.1 , snake_case_ : Union[str, Any]=4_0 , snake_case_ : Tuple=2 , snake_case_ : Dict=1 , snake_case_ : Union[str, Any]=0 , ): __a : List[Any] = parent __a : str = batch_size __a : int = seq_length __a : List[Any] = is_training __a : List[Any] = use_labels __a : List[str] = vocab_size __a : str = hidden_size __a : Dict = num_hidden_layers __a : Tuple = num_attention_heads __a : Any = intermediate_size __a : str = hidden_dropout_prob __a : int = attention_probs_dropout_prob __a : Optional[Any] = max_position_embeddings __a : Tuple = eos_token_id __a : Any = pad_token_id __a : str = bos_token_id def lowerCAmelCase (self : Tuple ): __a : List[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __a : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __a : Optional[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) __a : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : Union[str, Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __a : Tuple = prepare_pegasus_inputs_dict(snake_case_ , snake_case_ , snake_case_ ) return config, inputs_dict def lowerCAmelCase (self : str , snake_case_ : str , snake_case_ : List[str] ): __a : Tuple = TFPegasusModel(config=snake_case_ ).get_decoder() __a : Any = inputs_dict['''input_ids'''] __a : int = input_ids[:1, :] __a : Dict = inputs_dict['''attention_mask'''][:1, :] __a : Tuple = inputs_dict['''head_mask'''] __a : List[str] = 1 # first forward pass __a : Tuple = model(snake_case_ , attention_mask=snake_case_ , head_mask=snake_case_ , use_cache=snake_case_ ) __a : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __a : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) __a : Union[str, Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __a : Union[str, Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) __a : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __a : int = model(snake_case_ , attention_mask=snake_case_ )[0] __a : Optional[Any] = model(snake_case_ , attention_mask=snake_case_ , past_key_values=snake_case_ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __a : Any = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __a : str = output_from_no_past[:, -3:, random_slice_idx] __a : List[Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(snake_case_ , snake_case_ , rtol=1E-3 ) def __UpperCamelCase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any=None , lowerCAmelCase__ : Union[str, Any]=None , lowerCAmelCase__ : Dict=None , lowerCAmelCase__ : Tuple=None , lowerCAmelCase__ : Any=None , ): if attention_mask is None: __a : Dict = tf.cast(tf.math.not_equal(lowerCAmelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: __a : Optional[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: __a : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __a : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __a : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCamelCase__ ( __lowercase ,__lowercase ,unittest.TestCase ): _SCREAMING_SNAKE_CASE : Tuple = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () _SCREAMING_SNAKE_CASE : int = (TFPegasusForConditionalGeneration,) if is_tf_available() else () _SCREAMING_SNAKE_CASE : Optional[int] = ( { "conversational": TFPegasusForConditionalGeneration, "feature-extraction": TFPegasusModel, "summarization": TFPegasusForConditionalGeneration, "text2text-generation": TFPegasusForConditionalGeneration, "translation": TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) _SCREAMING_SNAKE_CASE : str = True _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : int = False def lowerCAmelCase (self : Optional[int] ): __a : Any = TFPegasusModelTester(self ) __a : List[str] = ConfigTester(self , config_class=snake_case_ ) def lowerCAmelCase (self : Optional[int] ): self.config_tester.run_common_tests() def lowerCAmelCase (self : List[Any] ): __a : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*snake_case_ ) @require_sentencepiece @require_tokenizers @require_tf class UpperCamelCase__ ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] _SCREAMING_SNAKE_CASE : List[str] = [ "California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to" " reduce the risk of wildfires.", "N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.", ] # differs slightly from pytorch, likely due to numerical differences in linear layers _SCREAMING_SNAKE_CASE : str = "google/pegasus-xsum" @cached_property def lowerCAmelCase (self : Tuple ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def lowerCAmelCase (self : Tuple ): __a : Union[str, Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def lowerCAmelCase (self : str , **snake_case_ : Optional[Any] ): __a : List[str] = self.translate_src_text(**snake_case_ ) assert self.expected_text == generated_words def lowerCAmelCase (self : Union[str, Any] , **snake_case_ : Optional[int] ): __a : str = self.tokenizer(self.src_text , **snake_case_ , padding=snake_case_ , return_tensors='''tf''' ) __a : str = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=snake_case_ , ) __a : List[str] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=snake_case_ ) return generated_words @slow def lowerCAmelCase (self : Any ): self._assert_generated_batch_equal_expected()
350
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def __UpperCamelCase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Any ): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a : Union[str, Any] = np.full((len(lowerCAmelCase__ ), sequence_length, 2) , lowerCAmelCase__ ) else: __a : str = np.full((len(lowerCAmelCase__ ), sequence_length) , lowerCAmelCase__ ) for i, tensor in enumerate(lowerCAmelCase__ ): if padding_side == "right": if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a : Any = tensor[:sequence_length] else: __a : List[Any] = tensor[:sequence_length] else: if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a : Dict = tensor[:sequence_length] else: __a : int = tensor[:sequence_length] return out_tensor.tolist() def __UpperCamelCase ( lowerCAmelCase__ : Optional[Any] ): __a : str = ord(lowerCAmelCase__ ) if (cp >= 3_3 and cp <= 4_7) or (cp >= 5_8 and cp <= 6_4) or (cp >= 9_1 and cp <= 9_6) or (cp >= 1_2_3 and cp <= 1_2_6): return True __a : List[str] = unicodedata.category(lowerCAmelCase__ ) if cat.startswith('''P''' ): return True return False @dataclass class UpperCamelCase__ ( __lowercase ): _SCREAMING_SNAKE_CASE : PreTrainedTokenizerBase _SCREAMING_SNAKE_CASE : Union[bool, str, PaddingStrategy] = True _SCREAMING_SNAKE_CASE : Optional[int] = None _SCREAMING_SNAKE_CASE : Optional[int] = None _SCREAMING_SNAKE_CASE : int = -100 _SCREAMING_SNAKE_CASE : str = "pt" def lowerCAmelCase (self : str , snake_case_ : Tuple ): import torch __a : Union[str, Any] = '''label''' if '''label''' in features[0].keys() else '''labels''' __a : Tuple = [feature[label_name] for feature in features] if label_name in features[0].keys() else None __a : Union[str, Any] = self.tokenizer.pad( snake_case_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' if labels is None else None , ) if labels is None: return batch __a : List[str] = torch.tensor(batch['''entity_ids'''] ).shape[1] __a : Tuple = self.tokenizer.padding_side if padding_side == "right": __a : Union[str, Any] = [ list(snake_case_ ) + [self.label_pad_token_id] * (sequence_length - len(snake_case_ )) for label in labels ] else: __a : Dict = [ [self.label_pad_token_id] * (sequence_length - len(snake_case_ )) + list(snake_case_ ) for label in labels ] __a : Dict = [feature['''ner_tags'''] for feature in features] __a : Optional[Any] = padding_tensor(snake_case_ , -1 , snake_case_ , snake_case_ ) __a : Union[str, Any] = [feature['''original_entity_spans'''] for feature in features] __a : Optional[int] = padding_tensor(snake_case_ , (-1, -1) , snake_case_ , snake_case_ ) __a : List[str] = {k: torch.tensor(snake_case_ , dtype=torch.intaa ) for k, v in batch.items()} return batch
90
0
'''simple docstring''' import operator as op def _A ( A__ ): """simple docstring""" __lowercase = [] __lowercase = lambda A__ , A__ : int(x / y ) # noqa: E731 integer division operation __lowercase = { '''^''': 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: __lowercase = stack.pop() # pop stack # output in tabular format print(''''''.rjust(8 ) , ('''pop(''' + b + ''')''').ljust(12 ) , ''','''.join(A__ ) , sep=''' | ''' ) __lowercase = 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__": lowerCAmelCase__ = input('''\n\nEnter a Postfix Equation (space separated) = ''').split(''' ''') print('''\n\tResult = ''', solve(Postfix))
104
'''simple docstring''' import colorsys from PIL import Image # type: ignore def _A ( A__ , A__ , A__ ): """simple docstring""" __lowercase = x __lowercase = y for step in range(A__ ): # noqa: B007 __lowercase = a * a - b * b + x __lowercase = 2 * a * b + y __lowercase = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _A ( A__ ): """simple docstring""" if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def _A ( A__ ): """simple docstring""" if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(A__ , 1 , 1 ) ) def _A ( A__ = 800 , A__ = 600 , A__ = -0.6 , A__ = 0 , A__ = 3.2 , A__ = 50 , A__ = True , ): """simple docstring""" __lowercase = Image.new('''RGB''' , (image_width, image_height) ) __lowercase = img.load() # loop through the image-coordinates for image_x in range(A__ ): for image_y in range(A__ ): # determine the figure-coordinates based on the image-coordinates __lowercase = figure_width / image_width * image_height __lowercase = figure_center_x + (image_x / image_width - 0.5) * figure_width __lowercase = figure_center_y + (image_y / image_height - 0.5) * figure_height __lowercase = get_distance(A__ , A__ , A__ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: __lowercase = get_color_coded_rgb(A__ ) else: __lowercase = get_black_and_white_rgb(A__ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowerCAmelCase__ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
104
1
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 _lowercase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> str: '''simple docstring''' def get_masked_lm_array(UpperCamelCase_ ): SCREAMING_SNAKE_CASE__ = F'masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase_ , UpperCamelCase_ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase_ ) def get_encoder_array(UpperCamelCase_ ): SCREAMING_SNAKE_CASE__ = F'encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase_ , UpperCamelCase_ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase_ ) def get_encoder_layer_array(UpperCamelCase_ , UpperCamelCase_ ): SCREAMING_SNAKE_CASE__ = F'encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase_ , UpperCamelCase_ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase_ ) def get_encoder_attention_layer_array(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): SCREAMING_SNAKE_CASE__ = F'encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase_ , UpperCamelCase_ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase_ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase_ ) print(F'Loading model based on config from {config_path}...' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase_ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase_ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase_ , '_query_dense/kernel' , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase_ , '_query_dense/bias' , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase_ , '_key_dense/kernel' , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase_ , '_key_dense/bias' , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase_ , '_value_dense/kernel' , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase_ , '_value_dense/bias' , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase_ , '_output_dense/kernel' , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase_ , '_output_dense/bias' , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase_ , '_attention_layer_norm/gamma' ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase_ , '_attention_layer_norm/beta' ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase_ , '_intermediate_dense/kernel' ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase_ , '_intermediate_dense/bias' ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase_ , '_output_dense/kernel' ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase_ , '_output_dense/bias' ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase_ , '_output_layer_norm/gamma' ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase_ , '_output_layer_norm/beta' ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array('_position_embedding_layer/embeddings' ) SCREAMING_SNAKE_CASE__ = get_encoder_array('_type_embedding_layer/embeddings' ) SCREAMING_SNAKE_CASE__ = get_encoder_array('_embedding_norm_layer/gamma' ) SCREAMING_SNAKE_CASE__ = get_encoder_array('_embedding_norm_layer/beta' ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array('dense/kernel' ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array('dense/bias' ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array('layer_norm/gamma' ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array('layer_norm/beta' ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array('embedding_table' ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase_ ) SCREAMING_SNAKE_CASE__ = get_encoder_array('_pooler_layer/kernel' ) SCREAMING_SNAKE_CASE__ = get_encoder_array('_pooler_layer/bias' ) # Export final model model.save_pretrained(UpperCamelCase_ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase_ ) print(new_model.eval() ) print('Model conversion was done sucessfully!' ) if __name__ == "__main__": __snake_case = 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.""", ) __snake_case = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
169
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor __snake_case = logging.get_logger(__name__) class lowercase__ ( _UpperCAmelCase ): def __init__( self : Dict , *UpperCAmelCase_ : int , **UpperCAmelCase_ : List[Any] ): warnings.warn( 'The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use LayoutLMv2ImageProcessor instead.' , UpperCAmelCase_ , ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ )
169
1
'''simple docstring''' import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class SCREAMING_SNAKE_CASE (a__ , unittest.TestCase ): lowerCAmelCase = BioGptTokenizer lowerCAmelCase = False def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __A : int = [ '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>', ] __A : int = dict(zip(_UpperCAmelCase , range(len(_UpperCAmelCase)))) __A : Union[str, Any] = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] __A : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file']) __A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file']) with open(self.vocab_file , 'w') as fp: fp.write(json.dumps(_UpperCAmelCase)) with open(self.merges_file , 'w') as fp: fp.write('\n'.join(_UpperCAmelCase)) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase): '''simple docstring''' __A : List[str] = 'lower newer' __A : Optional[Any] = 'lower newer' return input_text, output_text def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Union[str, Any] = BioGptTokenizer(self.vocab_file , self.merges_file) __A : int = 'lower' __A : Union[str, Any] = ['low', 'er</w>'] __A : Union[str, Any] = tokenizer.tokenize(_UpperCAmelCase) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase) __A : Optional[int] = tokens + ['<unk>'] __A : Any = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase) , _UpperCAmelCase) @slow def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Any = BioGptTokenizer.from_pretrained('microsoft/biogpt') __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_UpperCAmelCase) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_UpperCAmelCase) __A : Tuple = tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase) __A : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase , _UpperCAmelCase) self.assertTrue(encoded_sentence == [2] + text) self.assertTrue(encoded_pair == [2] + text + [2] + text_a)
190
'''simple docstring''' import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class SCREAMING_SNAKE_CASE (unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Dict = tempfile.mkdtemp() __A : Optional[int] = BlipImageProcessor() __A : List[str] = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-BertModel') __A : Any = BlipProcessor(_UpperCAmelCase , _UpperCAmelCase) processor.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE ( self , **_UpperCAmelCase): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **_UpperCAmelCase).tokenizer def SCREAMING_SNAKE_CASE ( self , **_UpperCAmelCase): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **_UpperCAmelCase).image_processor def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta)] __A : Union[str, Any] = [Image.fromarray(np.moveaxis(_UpperCAmelCase , 0 , -1)) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : int = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor()) processor.save_pretrained(self.tmpdirname) __A : int = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') __A : List[Any] = self.get_image_processor(do_normalize=_UpperCAmelCase , padding_value=1.0) __A : Tuple = BlipProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_UpperCAmelCase , padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , _UpperCAmelCase) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , _UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : List[str] = self.get_image_processor() __A : str = self.get_tokenizer() __A : int = BlipProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) __A : List[str] = self.prepare_image_inputs() __A : str = image_processor(_UpperCAmelCase , return_tensors='np') __A : str = processor(images=_UpperCAmelCase , return_tensors='np') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Any = self.get_image_processor() __A : Tuple = self.get_tokenizer() __A : Union[str, Any] = BlipProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) __A : str = 'lower newer' __A : Dict = processor(text=_UpperCAmelCase) __A : Tuple = tokenizer(_UpperCAmelCase , return_token_type_ids=_UpperCAmelCase) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : List[Any] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Optional[Any] = BlipProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) __A : Dict = 'lower newer' __A : int = self.prepare_image_inputs() __A : List[Any] = processor(text=_UpperCAmelCase , images=_UpperCAmelCase) self.assertListEqual(list(inputs.keys()) , ['pixel_values', 'input_ids', 'attention_mask']) # test if it raises when no input is passed with pytest.raises(_UpperCAmelCase): processor() def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Union[str, Any] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = BlipProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) __A : Tuple = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : List[str] = processor.batch_decode(_UpperCAmelCase) __A : List[str] = tokenizer.batch_decode(_UpperCAmelCase) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Any = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : Optional[Any] = BlipProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase) __A : str = 'lower newer' __A : str = self.prepare_image_inputs() __A : Optional[int] = processor(text=_UpperCAmelCase , images=_UpperCAmelCase) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys()) , ['pixel_values', 'input_ids', 'attention_mask'])
190
1
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar _lowercase : Optional[int] = TypeVar("""T""") class UpperCamelCase__( Generic[T] ): def __init__( self : Any , lowerCAmelCase : T )-> str: """simple docstring""" UpperCAmelCase = data UpperCAmelCase = None def __str__( self : Optional[int] )-> str: """simple docstring""" return F"""{self.data}""" class UpperCamelCase__( Generic[T] ): def __init__( self : Optional[Any] )-> None: """simple docstring""" UpperCAmelCase = None def __iter__( self : Optional[int] )-> Iterator[T]: """simple docstring""" UpperCAmelCase = self.top while node: yield node.data UpperCAmelCase = node.next def __str__( self : Optional[Any] )-> str: """simple docstring""" return "->".join([str(lowerCAmelCase ) for item in self] ) def __len__( self : List[Any] )-> int: """simple docstring""" return len(tuple(iter(self ) ) ) def a__( self : int )-> bool: """simple docstring""" return self.top is None def a__( self : List[Any] , lowerCAmelCase : T )-> None: """simple docstring""" UpperCAmelCase = Node(lowerCAmelCase ) if not self.is_empty(): UpperCAmelCase = self.top UpperCAmelCase = node def a__( self : List[str] )-> T: """simple docstring""" if self.is_empty(): raise IndexError('''pop from empty stack''' ) assert isinstance(self.top , lowerCAmelCase ) UpperCAmelCase = self.top UpperCAmelCase = self.top.next return pop_node.data def a__( self : Tuple )-> T: """simple docstring""" if self.is_empty(): raise IndexError('''peek from empty stack''' ) assert self.top is not None return self.top.data def a__( self : str )-> None: """simple docstring""" UpperCAmelCase = None if __name__ == "__main__": from doctest import testmod testmod()
91
'''simple docstring''' def lowerCamelCase__ ( A : int , A : int ): '''simple docstring''' return int(input_a == input_a == 0 ) def lowerCamelCase__ ( ): '''simple docstring''' print('''Truth Table of NOR Gate:''' ) print('''| Input 1 | Input 2 | Output |''' ) print(f"""| 0 | 0 | {nor_gate(0 , 0 )} |""" ) print(f"""| 0 | 1 | {nor_gate(0 , 1 )} |""" ) print(f"""| 1 | 0 | {nor_gate(1 , 0 )} |""" ) print(f"""| 1 | 1 | {nor_gate(1 , 1 )} |""" ) if __name__ == "__main__": import doctest doctest.testmod() main()
91
1
"""simple docstring""" import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings __UpperCamelCase = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__ ) class lowerCAmelCase ( lowerCamelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = field(default=lowerCamelCase__ , metadata={"""help""": """Whether to use SortishSampler or not."""} ) SCREAMING_SNAKE_CASE_ : str = field( default=lowerCamelCase__ , metadata={"""help""": """Whether to use generate to calculate generative metrics (ROUGE, BLEU)."""} ) SCREAMING_SNAKE_CASE_ : Optional[Any] = field( default=lowerCamelCase__ , metadata={ """help""": ( """The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default """ """to the `max_length` value of the model configuration.""" ) } , ) SCREAMING_SNAKE_CASE_ : Any = field( default=lowerCamelCase__ , metadata={ """help""": ( """The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default """ """to the `num_beams` value of the model configuration.""" ) } , ) SCREAMING_SNAKE_CASE_ : str = field( default=lowerCamelCase__ , metadata={ """help""": """Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.""" } , ) def __A ( self ) -> str: SCREAMING_SNAKE_CASE = super().to_dict() for k, v in d.items(): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE = v.to_dict() return d
113
def __snake_case ( _lowerCAmelCase : list ) -> list: if len(_lowerCAmelCase ) <= 1: return [tuple(_lowerCAmelCase )] A_ : Tuple = [] def generate(_lowerCAmelCase : int , _lowerCAmelCase : list ): A_ : List[str] = [0] * n res.append(tuple(_lowerCAmelCase ) ) A_ : int = 0 while i < n: if c[i] < i: if i % 2 == 0: A_ , A_ : str = arr[i], arr[0] else: A_ , A_ : List[str] = arr[i], arr[c[i]] res.append(tuple(_lowerCAmelCase ) ) c[i] += 1 A_ : Tuple = 0 else: A_ : Dict = 0 i += 1 generate(len(_lowerCAmelCase ) , _lowerCAmelCase ) return res if __name__ == "__main__": _lowerCAmelCase : str = input('''Enter numbers separated by a comma:\n''').strip() _lowerCAmelCase : str = [int(item) for item in user_input.split(''',''')] print(heaps(arr))
300
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a : Union[str, Any] = { "configuration_bert": ["BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BertConfig", "BertOnnxConfig"], "tokenization_bert": ["BasicTokenizer", "BertTokenizer", "WordpieceTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : List[str] = ["BertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : Dict = [ "BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "BertForMaskedLM", "BertForMultipleChoice", "BertForNextSentencePrediction", "BertForPreTraining", "BertForQuestionAnswering", "BertForSequenceClassification", "BertForTokenClassification", "BertLayer", "BertLMHeadModel", "BertModel", "BertPreTrainedModel", "load_tf_weights_in_bert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : int = [ "TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBertEmbeddings", "TFBertForMaskedLM", "TFBertForMultipleChoice", "TFBertForNextSentencePrediction", "TFBertForPreTraining", "TFBertForQuestionAnswering", "TFBertForSequenceClassification", "TFBertForTokenClassification", "TFBertLMHeadModel", "TFBertMainLayer", "TFBertModel", "TFBertPreTrainedModel", ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : List[Any] = ["TFBertTokenizer"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : int = [ "FlaxBertForCausalLM", "FlaxBertForMaskedLM", "FlaxBertForMultipleChoice", "FlaxBertForNextSentencePrediction", "FlaxBertForPreTraining", "FlaxBertForQuestionAnswering", "FlaxBertForSequenceClassification", "FlaxBertForTokenClassification", "FlaxBertModel", "FlaxBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys a : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
350
"""simple docstring""" def _SCREAMING_SNAKE_CASE ( _lowercase : int ) ->bool: '''simple docstring''' return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
79
0
'''simple docstring''' import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging __SCREAMING_SNAKE_CASE :Union[str, Any] = logging.get_logger(__name__) class A_ ( lowerCAmelCase_ ): _lowerCamelCase : Optional[Any] = CLIPConfig _lowerCamelCase : Optional[Any] = ["""CLIPEncoderLayer"""] def __init__( self : Dict , snake_case_ : CLIPConfig ): super().__init__(snake_case_ ) _UpperCAmelCase = CLIPVisionModelWithProjection(config.vision_config ) _UpperCAmelCase = nn.Linear(config.vision_config.projection_dim , 1 ) _UpperCAmelCase = nn.Linear(config.vision_config.projection_dim , 1 ) @torch.no_grad() def lowercase ( self : List[Any] , snake_case_ : Optional[int] , snake_case_ : Union[str, Any] , snake_case_ : Optional[int]=0.5 , snake_case_ : List[str]=0.5 ): _UpperCAmelCase = self.vision_model(snake_case_ )[0] _UpperCAmelCase = self.p_head(snake_case_ ) _UpperCAmelCase = nsfw_detected.flatten() _UpperCAmelCase = nsfw_detected > p_threshold _UpperCAmelCase = nsfw_detected.tolist() if any(snake_case_ ): logger.warning( "Potential NSFW content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, nsfw_detected_ in enumerate(snake_case_ ): if nsfw_detected_: _UpperCAmelCase = np.zeros(images[idx].shape ) _UpperCAmelCase = self.w_head(snake_case_ ) _UpperCAmelCase = watermark_detected.flatten() _UpperCAmelCase = watermark_detected > w_threshold _UpperCAmelCase = watermark_detected.tolist() if any(snake_case_ ): logger.warning( "Potential watermarked content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, watermark_detected_ in enumerate(snake_case_ ): if watermark_detected_: _UpperCAmelCase = np.zeros(images[idx].shape ) return images, nsfw_detected, watermark_detected
22
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10**12 ): __UpperCamelCase =1 __UpperCamelCase =0 __UpperCamelCase =1 __UpperCamelCase =1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f"""{solution() = }""")
62
0
def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowercase__ = len(SCREAMING_SNAKE_CASE_ ) + 1 lowercase__ = len(SCREAMING_SNAKE_CASE_ ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. lowercase__ = [[0 for i in range(SCREAMING_SNAKE_CASE_ )] for j in range(SCREAMING_SNAKE_CASE_ )] # since string of zero length match pattern of zero length lowercase__ = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , SCREAMING_SNAKE_CASE_ ): lowercase__ = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , SCREAMING_SNAKE_CASE_ ): lowercase__ = dp[0][j - 2] if pattern[j - 1] == "*" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , SCREAMING_SNAKE_CASE_ ): for j in range(1 , SCREAMING_SNAKE_CASE_ ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": lowercase__ = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: lowercase__ = 1 elif pattern[j - 2] in (input_string[i - 1], "."): lowercase__ = dp[i - 1][j] else: lowercase__ = 0 else: lowercase__ = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") lowercase_ = """aab""" lowercase_ = """c*a*b""" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(F'{input_string} matches the given pattern {pattern}') else: print(F'{input_string} does not match with the given pattern {pattern}')
350
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 lowercase_ = logging.get_logger(__name__) lowercase_ = { """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 _snake_case ( lowercase__): UpperCamelCase__ : Any ="""perceiver""" def __init__( self : Any, __lowercase : Optional[Any]=256, __lowercase : List[str]=1280, __lowercase : Dict=768, __lowercase : int=1, __lowercase : Dict=26, __lowercase : Any=8, __lowercase : List[Any]=8, __lowercase : Dict=None, __lowercase : List[Any]=None, __lowercase : str="kv", __lowercase : str=1, __lowercase : Optional[Any]=1, __lowercase : str="gelu", __lowercase : List[str]=0.1, __lowercase : int=0.02, __lowercase : Union[str, Any]=1e-1_2, __lowercase : Optional[Any]=True, __lowercase : Optional[Any]=262, __lowercase : str=2048, __lowercase : Optional[Any]=56, __lowercase : str=[368, 496], __lowercase : str=16, __lowercase : int=1920, __lowercase : Dict=16, __lowercase : List[Any]=[1, 16, 224, 224], **__lowercase : str, ): super().__init__(**__lowercase ) lowercase__ = num_latents lowercase__ = d_latents lowercase__ = d_model lowercase__ = num_blocks lowercase__ = num_self_attends_per_block lowercase__ = num_self_attention_heads lowercase__ = num_cross_attention_heads lowercase__ = qk_channels lowercase__ = v_channels lowercase__ = cross_attention_shape_for_attention lowercase__ = self_attention_widening_factor lowercase__ = cross_attention_widening_factor lowercase__ = hidden_act lowercase__ = attention_probs_dropout_prob lowercase__ = initializer_range lowercase__ = layer_norm_eps lowercase__ = use_query_residual # masked language modeling attributes lowercase__ = vocab_size lowercase__ = max_position_embeddings # image classification attributes lowercase__ = image_size # flow attributes lowercase__ = train_size # multimodal autoencoding attributes lowercase__ = num_frames lowercase__ = audio_samples_per_frame lowercase__ = samples_per_patch lowercase__ = output_shape class _snake_case ( lowercase__): @property def A__ ( self : Optional[int] ): if self.task == "multiple-choice": lowercase__ = {0: "batch", 1: "choice", 2: "sequence"} else: lowercase__ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def A__ ( self : Optional[Any] ): return 1e-4 def A__ ( self : Tuple, __lowercase : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"], __lowercase : int = -1, __lowercase : int = -1, __lowercase : int = -1, __lowercase : bool = False, __lowercase : Optional[TensorType] = None, __lowercase : int = 3, __lowercase : int = 40, __lowercase : int = 40, ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__lowercase, __lowercase ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX lowercase__ = compute_effective_axis_dimension( __lowercase, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX lowercase__ = preprocessor.num_special_tokens_to_add(__lowercase ) lowercase__ = compute_effective_axis_dimension( __lowercase, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=__lowercase ) # Generate dummy inputs according to compute batch and sequence lowercase__ = [" ".join(["a"] ) * seq_length] * batch_size lowercase__ = dict(preprocessor(__lowercase, return_tensors=__lowercase ) ) lowercase__ = inputs.pop("input_ids" ) return inputs elif isinstance(__lowercase, __lowercase ) 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 lowercase__ = compute_effective_axis_dimension(__lowercase, fixed_dimension=OnnxConfig.default_fixed_batch ) lowercase__ = self._generate_dummy_images(__lowercase, __lowercase, __lowercase, __lowercase ) lowercase__ = dict(preprocessor(images=__lowercase, return_tensors=__lowercase ) ) lowercase__ = inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
224
0
"""simple docstring""" def lowercase__( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ): if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) lowercase_ : List[str] = str(bin(__SCREAMING_SNAKE_CASE ) )[2:] # remove the leading "0b" lowercase_ : Optional[Any] = str(bin(__SCREAMING_SNAKE_CASE ) )[2:] # remove the leading "0b" lowercase_ : Tuple = max(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) return "0b" + "".join( str(int(char_a != char_b ) ) for char_a, char_b in zip(a_binary.zfill(__SCREAMING_SNAKE_CASE ) , b_binary.zfill(__SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
213
"""simple docstring""" from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def lowercase__( __SCREAMING_SNAKE_CASE : Optional[int] ): return {key.lstrip('-' ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def lowercase__( ): lowercase_ : Any = ArgumentParser( 'HuggingFace Datasets CLI tool' , usage='datasets-cli <command> [<args>]' , allow_abbrev=__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = parser.add_subparsers(help='datasets-cli command helpers' ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) EnvironmentCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) TestCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) RunBeamCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) DummyDataCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) # Parse args lowercase_ , lowercase_ : Dict = parser.parse_known_args() if not hasattr(__SCREAMING_SNAKE_CASE , 'func' ): parser.print_help() exit(1 ) lowercase_ : int = parse_unknown_args(__SCREAMING_SNAKE_CASE ) # Run lowercase_ : List[Any] = args.func(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) service.run() if __name__ == "__main__": main()
213
1
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __magic_name__ ( snake_case ): def __init__( self , _lowercase , _lowercase , _lowercase )-> Optional[int]: super().__init__() self.register_modules(vqvae=_lowercase , unet=_lowercase , scheduler=_lowercase ) @torch.no_grad() def __call__( self , _lowercase = 1 , _lowercase = None , _lowercase = 0.0 , _lowercase = 50 , _lowercase = "pil" , _lowercase = True , **_lowercase , )-> Union[Tuple, ImagePipelineOutput]: UpperCamelCase_ = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=_lowercase , ) UpperCamelCase_ = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase_ = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_lowercase ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature UpperCamelCase_ = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase_ = {} if accepts_eta: UpperCamelCase_ = eta for t in self.progress_bar(self.scheduler.timesteps ): UpperCamelCase_ = self.scheduler.scale_model_input(_lowercase , _lowercase ) # predict the noise residual UpperCamelCase_ = self.unet(_lowercase , _lowercase ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase_ = self.scheduler.step(_lowercase , _lowercase , _lowercase , **_lowercase ).prev_sample # decode the image latents with the VAE UpperCamelCase_ = self.vqvae.decode(_lowercase ).sample UpperCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase_ = self.numpy_to_pil(_lowercase ) if not return_dict: return (image,) return ImagePipelineOutput(images=_lowercase )
60
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler SCREAMING_SNAKE_CASE :Tuple = 16 SCREAMING_SNAKE_CASE :Optional[Any] = 32 def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 1_6 , SCREAMING_SNAKE_CASE_ = "bert-base-cased" )-> Optional[int]: """simple docstring""" UpperCamelCase_ = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = load_dataset("glue" , "mrpc" ) def tokenize_function(SCREAMING_SNAKE_CASE_ ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase_ = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase_ = datasets.map( SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , remove_columns=["idx", "sentence1", "sentence2"] , load_from_cache_file=SCREAMING_SNAKE_CASE_ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase_ = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(SCREAMING_SNAKE_CASE_ ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(SCREAMING_SNAKE_CASE_ , padding="max_length" , max_length=1_2_8 , return_tensors="pt" ) return tokenizer.pad(SCREAMING_SNAKE_CASE_ , padding="longest" , return_tensors="pt" ) # Instantiate dataloaders. UpperCamelCase_ = DataLoader( tokenized_datasets["train"] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = DataLoader( tokenized_datasets["validation"] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) return train_dataloader, eval_dataloader def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )-> Any: """simple docstring""" model.eval() UpperCamelCase_ = 0 for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase_ = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCamelCase_ , UpperCamelCase_ = accelerator.gather( (predictions, batch["labels"]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(SCREAMING_SNAKE_CASE_ ) - 1: UpperCamelCase_ = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCamelCase_ = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=SCREAMING_SNAKE_CASE_ , references=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase_ = metric.compute() return eval_metric["accuracy"] def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )-> Optional[Any]: """simple docstring""" UpperCamelCase_ = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase_ = config["lr"] UpperCamelCase_ = int(config["num_epochs"] ) UpperCamelCase_ = int(config["seed"] ) UpperCamelCase_ = int(config["batch_size"] ) UpperCamelCase_ = args.model_name_or_path set_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ , UpperCamelCase_ = get_dataloaders(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase_ = AutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) # Instantiate optimizer UpperCamelCase_ = ( AdamW if accelerator.state.deepspeed_plugin is None or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase_ = optimizer_cls(params=model.parameters() , lr=SCREAMING_SNAKE_CASE_ ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase_ = accelerator.state.deepspeed_plugin.deepspeed_config[ "gradient_accumulation_steps" ] else: UpperCamelCase_ = 1 UpperCamelCase_ = (len(SCREAMING_SNAKE_CASE_ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase_ = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE_ , num_warmup_steps=0 , num_training_steps=SCREAMING_SNAKE_CASE_ , ) else: UpperCamelCase_ = DummyScheduler(SCREAMING_SNAKE_CASE_ , total_num_steps=SCREAMING_SNAKE_CASE_ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # We need to keep track of how many total steps we have iterated over UpperCamelCase_ = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase_ = 0 UpperCamelCase_ = evaluate.load("glue" , "mrpc" ) UpperCamelCase_ = num_epochs if args.partial_train_epoch is not None: UpperCamelCase_ = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) UpperCamelCase_ = args.resume_from_checkpoint.split("epoch_" )[1] UpperCamelCase_ = "" for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break UpperCamelCase_ = int(SCREAMING_SNAKE_CASE_ ) + 1 UpperCamelCase_ = evaluation_loop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.print("resumed checkpoint performance:" , SCREAMING_SNAKE_CASE_ ) accelerator.print("resumed checkpoint's scheduler's lr:" , lr_scheduler.get_lr()[0] ) accelerator.print("resumed optimizers's lr:" , optimizer.param_groups[0]["lr"] ) with open(os.path.join(args.output_dir , f"state_{starting_epoch-1}.json" ) , "r" ) as f: UpperCamelCase_ = json.load(SCREAMING_SNAKE_CASE_ ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model UpperCamelCase_ = {} for epoch in range(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): UpperCamelCase_ = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = outputs.loss UpperCamelCase_ = loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 UpperCamelCase_ = f"epoch_{epoch}" UpperCamelCase_ = os.path.join(args.output_dir , SCREAMING_SNAKE_CASE_ ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = evaluation_loop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = accuracy UpperCamelCase_ = lr_scheduler.get_lr()[0] UpperCamelCase_ = optimizer.param_groups[0]["lr"] UpperCamelCase_ = epoch UpperCamelCase_ = overall_step accelerator.print(f"epoch {epoch}:" , SCREAMING_SNAKE_CASE_ ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , f"state_{epoch}.json" ) , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase( )-> Union[str, Any]: """simple docstring""" UpperCamelCase_ = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage." ) parser.add_argument( "--model_name_or_path" , type=SCREAMING_SNAKE_CASE_ , default="bert-base-cased" , help="Path to pretrained model or model identifier from huggingface.co/models." , required=SCREAMING_SNAKE_CASE_ , ) parser.add_argument( "--output_dir" , type=SCREAMING_SNAKE_CASE_ , default="." , help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory." , ) parser.add_argument( "--resume_from_checkpoint" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , help="If the training should continue from a checkpoint folder." , ) parser.add_argument( "--partial_train_epoch" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , help="If passed, the training will stop after this number of epochs." , ) parser.add_argument( "--num_epochs" , type=SCREAMING_SNAKE_CASE_ , default=2 , help="Number of train epochs." , ) UpperCamelCase_ = parser.parse_args() UpperCamelCase_ = {"lr": 2E-5, "num_epochs": args.num_epochs, "seed": 4_2, "batch_size": 1_6} training_function(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
60
1
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __magic_name__ ( __lowerCAmelCase): A: List[str] = ["vqvae"] def __init__( self : int , lowerCamelCase__ : AutoencoderKL , lowerCamelCase__ : UNetaDConditionModel , lowerCamelCase__ : Mel , lowerCamelCase__ : Union[DDIMScheduler, DDPMScheduler] , ) -> List[Any]: '''simple docstring''' super().__init__() self.register_modules(unet=lowerCamelCase__ , scheduler=lowerCamelCase__ , mel=lowerCamelCase__ , vqvae=lowerCamelCase__ ) def UpperCAmelCase__ ( self : Optional[int] ) -> int: '''simple docstring''' return 50 if isinstance(self.scheduler , lowerCamelCase__ ) else 1000 @torch.no_grad() def __call__( self : Dict , lowerCamelCase__ : int = 1 , lowerCamelCase__ : str = None , lowerCamelCase__ : np.ndarray = None , lowerCamelCase__ : int = 0 , lowerCamelCase__ : int = 0 , lowerCamelCase__ : int = None , lowerCamelCase__ : torch.Generator = None , lowerCamelCase__ : float = 0 , lowerCamelCase__ : float = 0 , lowerCamelCase__ : torch.Generator = None , lowerCamelCase__ : float = 0 , lowerCamelCase__ : torch.Tensor = None , lowerCamelCase__ : torch.Tensor = None , lowerCamelCase__ : str=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: '''simple docstring''' UpperCamelCase__ : Tuple = steps or self.get_default_steps() self.scheduler.set_timesteps(lowerCamelCase__ ) UpperCamelCase__ : Any = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: UpperCamelCase__ : str = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: UpperCamelCase__ : Union[str, Any] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=lowerCamelCase__ , device=self.device , ) UpperCamelCase__ : Any = noise UpperCamelCase__ : Tuple = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ : Dict = self.mel.audio_slice_to_image(lowerCamelCase__ ) UpperCamelCase__ : Optional[Any] = np.frombuffer(input_image.tobytes() , dtype='''uint8''' ).reshape( (input_image.height, input_image.width) ) UpperCamelCase__ : Optional[Any] = (input_image / 255) * 2 - 1 UpperCamelCase__ : List[str] = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: UpperCamelCase__ : List[Any] = self.vqvae.encode(torch.unsqueeze(lowerCamelCase__ , 0 ) ).latent_dist.sample( generator=lowerCamelCase__ )[0] UpperCamelCase__ : Dict = self.vqvae.config.scaling_factor * input_images if start_step > 0: UpperCamelCase__ : Any = self.scheduler.add_noise(lowerCamelCase__ , lowerCamelCase__ , self.scheduler.timesteps[start_step - 1] ) UpperCamelCase__ : List[Any] = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) UpperCamelCase__ : str = int(mask_start_secs * pixels_per_second ) UpperCamelCase__ : Any = int(mask_end_secs * pixels_per_second ) UpperCamelCase__ : Optional[int] = self.scheduler.add_noise(lowerCamelCase__ , lowerCamelCase__ , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , lowerCamelCase__ ): UpperCamelCase__ : Any = self.unet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )['''sample'''] else: UpperCamelCase__ : Union[str, Any] = self.unet(lowerCamelCase__ , lowerCamelCase__ )['''sample'''] if isinstance(self.scheduler , lowerCamelCase__ ): UpperCamelCase__ : int = self.scheduler.step( model_output=lowerCamelCase__ , timestep=lowerCamelCase__ , sample=lowerCamelCase__ , eta=lowerCamelCase__ , generator=lowerCamelCase__ , )['''prev_sample'''] else: UpperCamelCase__ : List[Any] = self.scheduler.step( model_output=lowerCamelCase__ , timestep=lowerCamelCase__ , sample=lowerCamelCase__ , generator=lowerCamelCase__ , )['''prev_sample'''] if mask is not None: if mask_start > 0: UpperCamelCase__ : Dict = mask[:, step, :, :mask_start] if mask_end > 0: UpperCamelCase__ : List[Any] = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance UpperCamelCase__ : List[Any] = 1 / self.vqvae.config.scaling_factor * images UpperCamelCase__ : int = self.vqvae.decode(lowerCamelCase__ )['''sample'''] UpperCamelCase__ : int = (images / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase__ : List[Any] = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() UpperCamelCase__ : List[Any] = (images * 255).round().astype('''uint8''' ) UpperCamelCase__ : List[Any] = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(lowerCamelCase__ , mode='''RGB''' ).convert('''L''' ) for _ in images) ) UpperCamelCase__ : Tuple = [self.mel.image_to_audio(lowerCamelCase__ ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(lowerCamelCase__ )[:, np.newaxis, :] ) , **ImagePipelineOutput(lowerCamelCase__ ) ) @torch.no_grad() def UpperCAmelCase__ ( self : Any , lowerCamelCase__ : List[Image.Image] , lowerCamelCase__ : int = 50 ) -> np.ndarray: '''simple docstring''' assert isinstance(self.scheduler , lowerCamelCase__ ) self.scheduler.set_timesteps(lowerCamelCase__ ) UpperCamelCase__ : List[Any] = np.array( [np.frombuffer(image.tobytes() , dtype='''uint8''' ).reshape((1, image.height, image.width) ) for image in images] ) UpperCamelCase__ : Dict = (sample / 255) * 2 - 1 UpperCamelCase__ : Any = torch.Tensor(lowerCamelCase__ ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): UpperCamelCase__ : List[Any] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps UpperCamelCase__ : Optional[Any] = self.scheduler.alphas_cumprod[t] UpperCamelCase__ : Union[str, Any] = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) UpperCamelCase__ : Union[str, Any] = 1 - alpha_prod_t UpperCamelCase__ : Optional[Any] = self.unet(lowerCamelCase__ , lowerCamelCase__ )['''sample'''] UpperCamelCase__ : Union[str, Any] = (1 - alpha_prod_t_prev) ** 0.5 * model_output UpperCamelCase__ : int = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) UpperCamelCase__ : Optional[int] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def UpperCAmelCase__ ( lowerCamelCase__ : torch.Tensor , lowerCamelCase__ : torch.Tensor , lowerCamelCase__ : float ) -> torch.Tensor: '''simple docstring''' UpperCamelCase__ : List[Any] = acos(torch.dot(torch.flatten(lowerCamelCase__ ) , torch.flatten(lowerCamelCase__ ) ) / torch.norm(lowerCamelCase__ ) / torch.norm(lowerCamelCase__ ) ) return sin((1 - alpha) * theta ) * xa / sin(lowerCamelCase__ ) + sin(alpha * theta ) * xa / sin(lowerCamelCase__ )
146
import cmath import math def _a ( SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : float ): """simple docstring""" UpperCamelCase__ : Union[str, Any] = math.radians(SCREAMING_SNAKE_CASE ) UpperCamelCase__ : List[str] = math.radians(SCREAMING_SNAKE_CASE ) # Convert voltage and current to rectangular form UpperCamelCase__ : str = cmath.rect(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Any = cmath.rect(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
146
1
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __lowerCamelCase : Optional[Any] = open # noqa: we just need to have a builtin inside this module to test it properly
204
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 __lowerCamelCase : List[Any] = get_tests_dir('''fixtures''') __lowerCamelCase : Optional[int] = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''') __lowerCamelCase : Any = get_tests_dir('''fixtures/dummy-config.json''') class __snake_case ( unittest.TestCase ): def __a ( self : Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 0 def __a ( self : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h""" ) self.assertIsInstance(_lowercase , _lowercase ) def __a ( self : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained(_lowercase ) self.assertIsInstance(_lowercase , _lowercase ) def __a ( self : Optional[int] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ = WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained(_lowercase ).to_dict() config_dict.pop("""feature_extractor_type""" ) SCREAMING_SNAKE_CASE__ = WavaVecaFeatureExtractor(**_lowercase ) # save in new folder model_config.save_pretrained(_lowercase ) config.save_pretrained(_lowercase ) SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained(_lowercase ) # make sure private variable is not incorrectly saved SCREAMING_SNAKE_CASE__ = json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(_lowercase , _lowercase ) def __a ( self : Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained(_lowercase ) self.assertIsInstance(_lowercase , _lowercase ) def __a ( self : Dict ): """simple docstring""" with self.assertRaisesRegex( _lowercase , """bert-base is not a local folder and is not a valid model identifier""" ): SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained("""bert-base""" ) def __a ( self : Union[str, Any] ): """simple docstring""" with self.assertRaisesRegex( _lowercase , R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained(_lowercase , revision="""aaaaaa""" ) def __a ( self : List[Any] ): """simple docstring""" with self.assertRaisesRegex( _lowercase , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model""" ) def __a ( self : str ): """simple docstring""" with self.assertRaises(_lowercase ): SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowercase ): SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=_lowercase ) SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=_lowercase ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(_lowercase ) SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained(_lowercase , trust_remote_code=_lowercase ) self.assertEqual(reloaded_feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) def __a ( self : Union[str, Any] ): """simple docstring""" try: AutoConfig.register("""custom""" , _lowercase ) AutoFeatureExtractor.register(_lowercase , _lowercase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowercase ): AutoFeatureExtractor.register(_lowercase , _lowercase ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE__ = CustomFeatureExtractor.from_pretrained(_lowercase ) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(_lowercase ) SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained(_lowercase ) self.assertIsInstance(_lowercase , _lowercase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def __a ( self : Any ): """simple docstring""" class __snake_case ( lowerCamelCase_ ): lowerCAmelCase_ = True try: AutoConfig.register("""custom""" , _lowercase ) AutoFeatureExtractor.register(_lowercase , _lowercase ) # If remote code is not set, the default is to use local SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(feature_extractor.is_local ) # If remote code is disabled, we load the local one. SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=_lowercase ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(feature_extractor.is_local ) # If remote is enabled, we load from the Hub SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=_lowercase ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(not hasattr(_lowercase , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
204
1
"""simple docstring""" import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument( """--txt2img_unclip""", default="""kakaobrain/karlo-v1-alpha""", type=str, required=False, help="""The pretrained txt2img unclip.""", ) __A = parser.parse_args() __A = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) __A = CLIPImageProcessor() __A = CLIPVisionModelWithProjection.from_pretrained("""openai/clip-vit-large-patch14""") __A = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
293
"""simple docstring""" import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def __A (_SCREAMING_SNAKE_CASE ) ->Tuple: """simple docstring""" lowerCAmelCase__ :List[str] = np.max(_outputs , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[Any] = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Any = """sigmoid""" __magic_name__ :Optional[Any] = """softmax""" __magic_name__ :Optional[Any] = """none""" @add_end_docstrings( a , r""" return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `\"default\"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output. """ , ) class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Union[str, Any] = False __magic_name__ :Dict = ClassificationFunction.NONE def __init__( self , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def snake_case ( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="" , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = tokenizer_kwargs lowerCAmelCase__ :List[Any] = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: lowerCAmelCase__ :List[Any] = self.model.config.return_all_scores if isinstance(__UpperCAmelCase , __UpperCAmelCase ) or top_k is None: lowerCAmelCase__ :int = top_k lowerCAmelCase__ :Dict = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , __UpperCAmelCase , ) if return_all_scores: lowerCAmelCase__ :List[Any] = None else: lowerCAmelCase__ :Union[str, Any] = 1 if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: lowerCAmelCase__ :List[Any] = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = super().__call__(*__UpperCAmelCase , **__UpperCAmelCase ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. lowerCAmelCase__ :Optional[Any] = 'top_k' not in kwargs if isinstance(args[0] , __UpperCAmelCase ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def snake_case ( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = self.framework if isinstance(__UpperCAmelCase , __UpperCAmelCase ): return self.tokenizer(**__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ) and len(__UpperCAmelCase ) == 1 and isinstance(inputs[0] , __UpperCAmelCase ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return self.model(**__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 , __UpperCAmelCase=True ): '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: lowerCAmelCase__ :str = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: lowerCAmelCase__ :int = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: lowerCAmelCase__ :Optional[Any] = self.model.config.function_to_apply else: lowerCAmelCase__ :Dict = ClassificationFunction.NONE lowerCAmelCase__ :int = model_outputs['logits'][0] lowerCAmelCase__ :Union[str, Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: lowerCAmelCase__ :Dict = sigmoid(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.SOFTMAX: lowerCAmelCase__ :int = softmax(__UpperCAmelCase ) elif function_to_apply == ClassificationFunction.NONE: lowerCAmelCase__ :Tuple = outputs else: raise ValueError(F"Unrecognized `function_to_apply` argument: {function_to_apply}" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} lowerCAmelCase__ :Any = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__UpperCAmelCase ) ] if not _legacy: dict_scores.sort(key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase ) if top_k is not None: lowerCAmelCase__ :List[str] = dict_scores[:top_k] return dict_scores
293
1
"""simple docstring""" import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase_ =logging.get_logger(__name__) def a_ ( _lowercase , _lowercase , _lowercase , _lowercase ): _UpperCamelCase : int = original_name.split('''.''' )[0] _UpperCamelCase : Union[str, Any] = key.split('''.''' ) _UpperCamelCase : Dict = int(key_list[key_list.index(snake_case_ ) - 2] ) _UpperCamelCase : Optional[Any] = int(key_list[key_list.index(snake_case_ ) - 1] ) _UpperCamelCase : List[str] = orig_block_num - offset _UpperCamelCase : Tuple = key.replace(F"""{orig_block_num}.{layer_num}.{original_name}""" , F"""block.{new_block_num}.{layer_num}.{new_name}""" ) return key def a_ ( _lowercase ): _UpperCamelCase : List[Any] = OrderedDict() _UpperCamelCase : Optional[Any] = 0, 0 for key, value in state_dict.items(): if key.startswith('''network''' ): _UpperCamelCase : Tuple = key.replace('''network''' , '''poolformer.encoder''' ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith('''bias''' ) and "patch_embed" not in key: patch_emb_offset += 1 _UpperCamelCase : List[str] = key[: key.find('''proj''' )] _UpperCamelCase : List[str] = key.replace(snake_case_ , F"""patch_embeddings.{total_embed_found}.""" ) _UpperCamelCase : Tuple = key.replace('''proj''' , '''projection''' ) if key.endswith('''bias''' ): total_embed_found += 1 if "patch_embeddings" in key: _UpperCamelCase : str = """poolformer.encoder.""" + key if "mlp.fc1" in key: _UpperCamelCase : Union[str, Any] = replace_key_with_offset(snake_case_ , snake_case_ , '''mlp.fc1''' , '''output.conv1''' ) if "mlp.fc2" in key: _UpperCamelCase : Union[str, Any] = replace_key_with_offset(snake_case_ , snake_case_ , '''mlp.fc2''' , '''output.conv2''' ) if "norm1" in key: _UpperCamelCase : Tuple = replace_key_with_offset(snake_case_ , snake_case_ , '''norm1''' , '''before_norm''' ) if "norm2" in key: _UpperCamelCase : Any = replace_key_with_offset(snake_case_ , snake_case_ , '''norm2''' , '''after_norm''' ) if "layer_scale_1" in key: _UpperCamelCase : int = replace_key_with_offset(snake_case_ , snake_case_ , '''layer_scale_1''' , '''layer_scale_1''' ) if "layer_scale_2" in key: _UpperCamelCase : Any = replace_key_with_offset(snake_case_ , snake_case_ , '''layer_scale_2''' , '''layer_scale_2''' ) if "head" in key: _UpperCamelCase : Dict = key.replace('''head''' , '''classifier''' ) _UpperCamelCase : Any = value return new_state_dict def a_ ( ): _UpperCamelCase : List[str] = """http://images.cocodataset.org/val2017/000000039769.jpg""" _UpperCamelCase : Optional[Any] = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return image @torch.no_grad() def a_ ( _lowercase , _lowercase , _lowercase ): _UpperCamelCase : str = PoolFormerConfig() # set attributes based on model_name _UpperCamelCase : str = """huggingface/label-files""" _UpperCamelCase : Optional[Any] = model_name[-3:] _UpperCamelCase : Optional[int] = 1000 _UpperCamelCase : List[str] = """imagenet-1k-id2label.json""" _UpperCamelCase : Any = (1, 1000) # set config attributes _UpperCamelCase : int = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type='''dataset''' ) , '''r''' ) ) _UpperCamelCase : Union[str, Any] = {int(snake_case_ ): v for k, v in idalabel.items()} _UpperCamelCase : Optional[Any] = idalabel _UpperCamelCase : List[str] = {v: k for k, v in idalabel.items()} if size == "s12": _UpperCamelCase : Dict = [2, 2, 6, 2] _UpperCamelCase : List[Any] = [64, 128, 320, 512] _UpperCamelCase : Optional[Any] = 4.0 _UpperCamelCase : int = 0.9 elif size == "s24": _UpperCamelCase : Optional[int] = [4, 4, 12, 4] _UpperCamelCase : Any = [64, 128, 320, 512] _UpperCamelCase : Optional[Any] = 4.0 _UpperCamelCase : Tuple = 0.9 elif size == "s36": _UpperCamelCase : Union[str, Any] = [6, 6, 18, 6] _UpperCamelCase : Any = [64, 128, 320, 512] _UpperCamelCase : List[str] = 4.0 _UpperCamelCase : Optional[int] = 1E-6 _UpperCamelCase : List[str] = 0.9 elif size == "m36": _UpperCamelCase : Tuple = [6, 6, 18, 6] _UpperCamelCase : List[str] = [96, 192, 384, 768] _UpperCamelCase : int = 4.0 _UpperCamelCase : Dict = 1E-6 _UpperCamelCase : Optional[int] = 0.95 elif size == "m48": _UpperCamelCase : Any = [8, 8, 24, 8] _UpperCamelCase : str = [96, 192, 384, 768] _UpperCamelCase : List[Any] = 4.0 _UpperCamelCase : int = 1E-6 _UpperCamelCase : List[str] = 0.95 else: raise ValueError(F"""Size {size} not supported""" ) # load image processor _UpperCamelCase : Union[str, Any] = PoolFormerImageProcessor(crop_pct=snake_case_ ) # Prepare image _UpperCamelCase : int = prepare_img() _UpperCamelCase : Tuple = image_processor(images=snake_case_ , return_tensors='''pt''' ).pixel_values logger.info(F"""Converting model {model_name}...""" ) # load original state dict _UpperCamelCase : List[str] = torch.load(snake_case_ , map_location=torch.device('''cpu''' ) ) # rename keys _UpperCamelCase : str = rename_keys(snake_case_ ) # create HuggingFace model and load state dict _UpperCamelCase : List[Any] = PoolFormerForImageClassification(snake_case_ ) model.load_state_dict(snake_case_ ) model.eval() # Define image processor _UpperCamelCase : Union[str, Any] = PoolFormerImageProcessor(crop_pct=snake_case_ ) _UpperCamelCase : List[Any] = image_processor(images=prepare_img() , return_tensors='''pt''' ).pixel_values # forward pass _UpperCamelCase : Optional[int] = model(snake_case_ ) _UpperCamelCase : Union[str, Any] = outputs.logits # define expected logit slices for different models if size == "s12": _UpperCamelCase : List[Any] = torch.tensor([-0.3045, -0.6758, -0.4869] ) elif size == "s24": _UpperCamelCase : Any = torch.tensor([0.4402, -0.1374, -0.8045] ) elif size == "s36": _UpperCamelCase : Dict = torch.tensor([-0.6080, -0.5133, -0.5898] ) elif size == "m36": _UpperCamelCase : Tuple = torch.tensor([0.3952, 0.2263, -1.2668] ) elif size == "m48": _UpperCamelCase : Dict = torch.tensor([0.1167, -0.0656, -0.3423] ) else: raise ValueError(F"""Size {size} not supported""" ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , snake_case_ , atol=1E-2 ) # finally, save model and image processor logger.info(F"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) model.save_pretrained(snake_case_ ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase_ =argparse.ArgumentParser() parser.add_argument( """--model_name""", default="""poolformer_s12""", type=str, help="""Name of the model you\'d like to convert.""", ) parser.add_argument( """--checkpoint_path""", default=None, type=str, help="""Path to the original PyTorch checkpoint (.pth file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model.""" ) UpperCamelCase_ =parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
355
"""simple docstring""" class _a : def __init__( self : Optional[int], lowerCAmelCase__ : list ) -> None: '''simple docstring''' _UpperCamelCase : Optional[int] = set_counts _UpperCamelCase : Any = max(lowerCAmelCase__ ) _UpperCamelCase : int = len(lowerCAmelCase__ ) _UpperCamelCase : int = [1] * num_sets _UpperCamelCase : List[Any] = list(range(lowerCAmelCase__ ) ) def snake_case ( self : int, lowerCAmelCase__ : int, lowerCAmelCase__ : int ) -> bool: '''simple docstring''' _UpperCamelCase : Optional[Any] = self.get_parent(lowerCAmelCase__ ) _UpperCamelCase : Any = self.get_parent(lowerCAmelCase__ ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] _UpperCamelCase : List[Any] = 0 _UpperCamelCase : str = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 _UpperCamelCase : Union[str, Any] = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] _UpperCamelCase : Tuple = 0 _UpperCamelCase : Optional[Any] = src_parent _UpperCamelCase : int = self.set_counts[src_parent] _UpperCamelCase : Optional[Any] = max(self.max_set, lowerCAmelCase__ ) return True def snake_case ( self : Optional[Any], lowerCAmelCase__ : int ) -> int: '''simple docstring''' if self.parents[disj_set] == disj_set: return disj_set _UpperCamelCase : Union[str, Any] = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
128
0
import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class UpperCAmelCase_ ( _A , _A , unittest.TestCase ): '''simple docstring''' a__ = IFImgaImgSuperResolutionPipeline a__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""width""", """height"""} a__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""original_image"""} ) a__ = PipelineTesterMixin.required_optional_params - {"""latents"""} def _lowercase ( self : List[Any] ) -> Optional[int]: """simple docstring""" return self._get_superresolution_dummy_components() def _lowercase ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : Dict=0 ) -> Any: """simple docstring""" if str(UpperCamelCase__ ).startswith("""mps""" ): __magic_name__ = torch.manual_seed(UpperCamelCase__ ) else: __magic_name__ = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) __magic_name__ = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ ) __magic_name__ = floats_tensor((1, 3, 16, 16) , rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ ) __magic_name__ = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def _lowercase ( self : Optional[int] ) -> List[Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def _lowercase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def _lowercase ( self : Tuple ) -> Union[str, Any]: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1E-1 ) def _lowercase ( self : str ) -> Optional[Any]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def _lowercase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" self._test_save_load_local() def _lowercase ( self : str ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
88
import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version _UpperCAmelCase = version.parse(importlib_metadata.version("""nltk""")) if NLTK_VERSION >= version.Version("""3.6.4"""): from nltk import word_tokenize _UpperCAmelCase = """\ @inproceedings{banarjee2005, title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments}, author = {Banerjee, Satanjeev and Lavie, Alon}, booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization}, month = jun, year = {2005}, address = {Ann Arbor, Michigan}, publisher = {Association for Computational Linguistics}, url = {https://www.aclweb.org/anthology/W05-0909}, pages = {65--72}, } """ _UpperCAmelCase = """\ METEOR, an automatic metric for machine translation evaluation that is based on a generalized concept of unigram matching between the machine-produced translation and human-produced reference translations. Unigrams can be matched based on their surface forms, stemmed forms, and meanings; furthermore, METEOR can be easily extended to include more advanced matching strategies. Once all generalized unigram matches between the two strings have been found, METEOR computes a score for this matching using a combination of unigram-precision, unigram-recall, and a measure of fragmentation that is designed to directly capture how well-ordered the matched words in the machine translation are in relation to the reference. METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic data and 0.331 on the Chinese data. This is shown to be an improvement on using simply unigram-precision, unigram-recall and their harmonic F1 combination. """ _UpperCAmelCase = """ Computes METEOR score of translated segments against one or more references. Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. alpha: Parameter for controlling relative weights of precision and recall. default: 0.9 beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3 gamma: Relative weight assigned to fragmentation penalty. default: 0.5 Returns: 'meteor': meteor score. Examples: >>> meteor = datasets.load_metric('meteor') >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"] >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"] >>> results = meteor.compute(predictions=predictions, references=references) >>> print(round(results[\"meteor\"], 4)) 0.6944 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def lowerCAmelCase_ ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'] , reference_urls=[ 'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score', 'https://en.wikipedia.org/wiki/METEOR', ] , ) def lowerCAmelCase_ ( self , lowercase ): """simple docstring""" import nltk nltk.download('wordnet' ) if NLTK_VERSION >= version.Version('3.6.5' ): nltk.download('punkt' ) if NLTK_VERSION >= version.Version('3.6.6' ): nltk.download('omw-1.4' ) def lowerCAmelCase_ ( self , lowercase , lowercase , lowercase=0.9 , lowercase=3 , lowercase=0.5 ): """simple docstring""" if NLTK_VERSION >= version.Version('3.6.5' ): A_ : List[Any] = [ meteor_score.single_meteor_score( word_tokenize(lowercase ) , word_tokenize(lowercase ) , alpha=lowercase , beta=lowercase , gamma=lowercase ) for ref, pred in zip(lowercase , lowercase ) ] else: A_ : Optional[Any] = [ meteor_score.single_meteor_score(lowercase , lowercase , alpha=lowercase , beta=lowercase , gamma=lowercase ) for ref, pred in zip(lowercase , lowercase ) ] return {"meteor": np.mean(lowercase )}
140
0
import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.models.auto.modeling_flax_auto import FlaxAutoModel from transformers.models.bert.modeling_flax_bert import FlaxBertModel from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel @require_flax class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" @slow def _a ( self ): for model_name in ["bert-base-cased", "bert-large-uncased"]: with self.subTest(_lowerCamelCase ): UpperCamelCase_: Dict = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) UpperCamelCase_: List[Any] = FlaxAutoModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def _a ( self ): for model_name in ["roberta-base", "roberta-large"]: with self.subTest(_lowerCamelCase ): UpperCamelCase_: Tuple = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) UpperCamelCase_: Union[str, Any] = FlaxAutoModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def _a ( self ): for model_name in ["bert-base-cased", "bert-large-uncased"]: UpperCamelCase_: int = AutoTokenizer.from_pretrained(_lowerCamelCase ) UpperCamelCase_: Any = FlaxBertModel.from_pretrained(_lowerCamelCase ) UpperCamelCase_: List[str] = tokenizer('Do you support jax jitted function?' , return_tensors=TensorType.JAX ) @jax.jit def eval(**_lowerCamelCase ): return model(**_lowerCamelCase ) eval(**_lowerCamelCase ).block_until_ready() @slow def _a ( self ): for model_name in ["roberta-base", "roberta-large"]: UpperCamelCase_: List[Any] = AutoTokenizer.from_pretrained(_lowerCamelCase ) UpperCamelCase_: Any = FlaxRobertaModel.from_pretrained(_lowerCamelCase ) UpperCamelCase_: str = tokenizer('Do you support jax jitted function?' , return_tensors=TensorType.JAX ) @jax.jit def eval(**_lowerCamelCase ): return model(**_lowerCamelCase ) eval(**_lowerCamelCase ).block_until_ready() def _a ( self ): with self.assertRaisesRegex( _lowerCamelCase , 'bert-base is not a local folder and is not a valid model identifier' ): UpperCamelCase_: Any = FlaxAutoModel.from_pretrained('bert-base' ) def _a ( self ): with self.assertRaisesRegex( _lowerCamelCase , r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): UpperCamelCase_: int = FlaxAutoModel.from_pretrained(_lowerCamelCase , revision='aaaaaa' ) def _a ( self ): with self.assertRaisesRegex( _lowerCamelCase , 'hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack' , ): UpperCamelCase_: List[str] = FlaxAutoModel.from_pretrained('hf-internal-testing/config-no-model' ) def _a ( self ): with self.assertRaisesRegex(_lowerCamelCase , 'Use `from_pt=True` to load this model' ): UpperCamelCase_: Union[str, Any] = FlaxAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only' )
292
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : List[Any] = logging.get_logger(__name__) A_ : Optional[Any] = { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : str ='''convbert''' def __init__( self , _lowerCamelCase=3_0_5_2_2 , _lowerCamelCase=7_6_8 , _lowerCamelCase=1_2 , _lowerCamelCase=1_2 , _lowerCamelCase=3_0_7_2 , _lowerCamelCase="gelu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=5_1_2 , _lowerCamelCase=2 , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-12 , _lowerCamelCase=1 , _lowerCamelCase=0 , _lowerCamelCase=2 , _lowerCamelCase=7_6_8 , _lowerCamelCase=2 , _lowerCamelCase=9 , _lowerCamelCase=1 , _lowerCamelCase=None , **_lowerCamelCase , ): super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase , ) UpperCamelCase_: Dict = vocab_size UpperCamelCase_: Tuple = hidden_size UpperCamelCase_: Optional[int] = num_hidden_layers UpperCamelCase_: Optional[int] = num_attention_heads UpperCamelCase_: Optional[Any] = intermediate_size UpperCamelCase_: Tuple = hidden_act UpperCamelCase_: Any = hidden_dropout_prob UpperCamelCase_: Any = attention_probs_dropout_prob UpperCamelCase_: List[Any] = max_position_embeddings UpperCamelCase_: List[Any] = type_vocab_size UpperCamelCase_: Optional[int] = initializer_range UpperCamelCase_: Tuple = layer_norm_eps UpperCamelCase_: List[str] = embedding_size UpperCamelCase_: int = head_ratio UpperCamelCase_: Dict = conv_kernel_size UpperCamelCase_: List[Any] = num_groups UpperCamelCase_: Dict = classifier_dropout class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" @property def _a ( self ): if self.task == "multiple-choice": UpperCamelCase_: Dict = {0: 'batch', 1: 'choice', 2: 'sequence'} else: UpperCamelCase_: Dict = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
292
1
def _snake_case ( lowerCAmelCase : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = generate_pascal_triangle(lowerCAmelCase ) for row_idx in range(lowerCAmelCase ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=" " ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] , end=" " ) else: print(triangle[row_idx][col_idx] , end="" ) print() def _snake_case ( lowerCAmelCase : int ): """simple docstring""" if not isinstance(lowerCAmelCase , lowerCAmelCase ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) SCREAMING_SNAKE_CASE_ : list[list[int]] = [] for current_row_idx in range(lowerCAmelCase ): SCREAMING_SNAKE_CASE_ : str = populate_current_row(lowerCAmelCase , lowerCAmelCase ) triangle.append(lowerCAmelCase ) return triangle def _snake_case ( lowerCAmelCase : list[list[int]] , lowerCAmelCase : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = 1, 1 for current_col_idx in range(1 , lowerCAmelCase ): calculate_current_element( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return current_row def _snake_case ( lowerCAmelCase : list[list[int]] , lowerCAmelCase : list[int] , lowerCAmelCase : int , lowerCAmelCase : int , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = triangle[current_row_idx - 1][current_col_idx - 1] SCREAMING_SNAKE_CASE_ : List[Any] = triangle[current_row_idx - 1][current_col_idx] SCREAMING_SNAKE_CASE_ : Union[str, Any] = above_to_left_elt + above_to_right_elt def _snake_case ( lowerCAmelCase : int ): """simple docstring""" if not isinstance(lowerCAmelCase , lowerCAmelCase ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) SCREAMING_SNAKE_CASE_ : list[list[int]] = [[1]] for row_index in range(1 , lowerCAmelCase ): SCREAMING_SNAKE_CASE_ : Tuple = [0] + result[-1] + [0] SCREAMING_SNAKE_CASE_ : List[str] = row_index + 1 # Calculate the number of distinct elements in a row SCREAMING_SNAKE_CASE_ : Optional[Any] = sum(divmod(lowerCAmelCase , 2 ) ) SCREAMING_SNAKE_CASE_ : List[Any] = [ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 ) ] SCREAMING_SNAKE_CASE_ : Optional[Any] = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() SCREAMING_SNAKE_CASE_ : Tuple = row_first_half + row_second_half result.append(lowerCAmelCase ) return result def _snake_case ( ): """simple docstring""" from collections.abc import Callable from timeit import timeit def benchmark_a_function(lowerCAmelCase : Callable , lowerCAmelCase : int ) -> None: SCREAMING_SNAKE_CASE_ : Optional[int] = f'{func.__name__}({value})' SCREAMING_SNAKE_CASE_ : str = timeit(f'__main__.{call}' , setup="import __main__" ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f'{call:38} -- {timing:.4f} seconds' ) for value in range(1_5 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(lowerCAmelCase , lowerCAmelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
18
"""simple docstring""" from __future__ import annotations import unittest from transformers import 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 numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class UpperCamelCase__: def __init__( self ,__UpperCAmelCase ,__UpperCAmelCase=13 ,__UpperCAmelCase=7 ,__UpperCAmelCase=True ,__UpperCAmelCase=True ,__UpperCAmelCase=True ,__UpperCAmelCase=True ,__UpperCAmelCase=99 ,__UpperCAmelCase=32 ,__UpperCAmelCase=2 ,__UpperCAmelCase=4 ,__UpperCAmelCase=37 ,__UpperCAmelCase="gelu" ,__UpperCAmelCase=0.1 ,__UpperCAmelCase=0.1 ,__UpperCAmelCase=5_12 ,__UpperCAmelCase=16 ,__UpperCAmelCase=2 ,__UpperCAmelCase=0.0_2 ,__UpperCAmelCase=3 ,__UpperCAmelCase=4 ,__UpperCAmelCase=None ,__UpperCAmelCase=0 ,) -> Dict: A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = use_token_type_ids A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = type_vocab_size A__ = type_sequence_label_size A__ = initializer_range A__ = num_labels A__ = num_choices A__ = scope A__ = projection_dim def snake_case__ ( self ) -> Optional[Any]: A__ = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A__ = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py A__ = random_attention_mask([self.batch_size, self.seq_length] ) A__ = None if self.use_token_type_ids: A__ = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) A__ = None A__ = None A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A__ = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A__ = ids_tensor([self.batch_size] ,self.num_choices ) A__ = BertConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=__UpperCAmelCase ,initializer_range=self.initializer_range ,) A__ = DPRConfig(projection_dim=self.projection_dim ,**config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case__ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Tuple: A__ = TFDPRContextEncoder(config=__UpperCAmelCase ) A__ = model(__UpperCAmelCase ,attention_mask=__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ) A__ = model(__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ) A__ = model(__UpperCAmelCase ) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.projection_dim or self.hidden_size) ) def snake_case__ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Union[str, Any]: A__ = TFDPRQuestionEncoder(config=__UpperCAmelCase ) A__ = model(__UpperCAmelCase ,attention_mask=__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ) A__ = model(__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ) A__ = model(__UpperCAmelCase ) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.projection_dim or self.hidden_size) ) def snake_case__ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Optional[int]: A__ = TFDPRReader(config=__UpperCAmelCase ) A__ = model(__UpperCAmelCase ,attention_mask=__UpperCAmelCase ) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape ,(self.batch_size,) ) def snake_case__ ( self ) -> int: A__ = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = config_and_inputs A__ = {'input_ids': input_ids} return config, inputs_dict @require_tf class UpperCamelCase__( __A , __A , unittest.TestCase ): lowerCAmelCase__ : Optional[int] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) lowerCAmelCase__ : List[str] = {'feature-extraction': TFDPRQuestionEncoder} if is_tf_available() else {} lowerCAmelCase__ : Tuple = False lowerCAmelCase__ : Optional[int] = False lowerCAmelCase__ : List[str] = False lowerCAmelCase__ : int = False lowerCAmelCase__ : str = False def snake_case__ ( self ) -> str: A__ = TFDPRModelTester(self ) A__ = ConfigTester(self ,config_class=__UpperCAmelCase ,hidden_size=37 ) def snake_case__ ( self ) -> Optional[Any]: self.config_tester.run_common_tests() def snake_case__ ( self ) -> int: A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*__UpperCAmelCase ) def snake_case__ ( self ) -> Optional[Any]: A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*__UpperCAmelCase ) def snake_case__ ( self ) -> List[str]: A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*__UpperCAmelCase ) @slow def snake_case__ ( self ) -> int: for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = TFDPRContextEncoder.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = TFDPRContextEncoder.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = TFDPRQuestionEncoder.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = TFDPRReader.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @require_tf class UpperCamelCase__( unittest.TestCase ): @slow def snake_case__ ( self ) -> Optional[Any]: A__ = TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base' ) A__ = tf.constant( [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]] ) # [CLS] hello, is my dog cute? [SEP] A__ = model(__UpperCAmelCase )[0] # embedding shape = (1, 768) # compare the actual values for a slice. A__ = tf.constant( [ [ 0.0_3_2_3_6_2_5_3, 0.1_2_7_5_3_3_3_5, 0.1_6_8_1_8_5_0_9, 0.0_0_2_7_9_7_8_6, 0.3_8_9_6_9_3_3, 0.2_4_2_6_4_9_4_5, 0.2_1_7_8_9_7_1, -0.0_2_3_3_5_2_2_7, -0.0_8_4_8_1_9_5_9, -0.1_4_3_2_4_1_1_7, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() ,expected_slice.numpy() ,atol=1e-4 ) )
221
0
"""simple docstring""" import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=1024 , lowerCAmelCase_=1024 , lowerCAmelCase_=False , **lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path="train" , **lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = tok.pad_token_id def get_lens(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = tqdm( DataLoader(lowerCAmelCase_ , batch_size=512 , num_workers=8 , shuffle=lowerCAmelCase_ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) __SCREAMING_SNAKE_CASE = [] for batch in dl: __SCREAMING_SNAKE_CASE = batch["input_ids"].ne(lowerCAmelCase_ ).sum(1 ).tolist() __SCREAMING_SNAKE_CASE = batch["labels"].ne(lowerCAmelCase_ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(lowerCAmelCase_ , lowerCAmelCase_ ): max_lens.append(max(lowerCAmelCase_ , lowerCAmelCase_ ) ) else: max_lens.extend(lowerCAmelCase_ ) return max_lens __SCREAMING_SNAKE_CASE = get_lens(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path="val" , **lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = get_lens(lowerCAmelCase_ ) pickle_save(lowerCAmelCase_ , train_ds.len_file ) pickle_save(lowerCAmelCase_ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
195
"""simple docstring""" import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging a__ : Optional[Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : int = CLIPConfig snake_case__ : str = ["CLIPEncoderLayer"] def __init__( self : Optional[int] , UpperCAmelCase__ : CLIPConfig ) -> Dict: super().__init__(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = CLIPVisionModelWithProjection(config.vision_config ) __SCREAMING_SNAKE_CASE = nn.Linear(config.vision_config.projection_dim , 1 ) __SCREAMING_SNAKE_CASE = nn.Linear(config.vision_config.projection_dim , 1 ) @torch.no_grad() def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : int=0.5 , UpperCAmelCase__ : Optional[int]=0.5 ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.vision_model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = self.p_head(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = nsfw_detected.flatten() __SCREAMING_SNAKE_CASE = nsfw_detected > p_threshold __SCREAMING_SNAKE_CASE = nsfw_detected.tolist() if any(UpperCAmelCase__ ): logger.warning( "Potential NSFW content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, nsfw_detected_ in enumerate(UpperCAmelCase__ ): if nsfw_detected_: __SCREAMING_SNAKE_CASE = np.zeros(images[idx].shape ) __SCREAMING_SNAKE_CASE = self.w_head(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = watermark_detected.flatten() __SCREAMING_SNAKE_CASE = watermark_detected > w_threshold __SCREAMING_SNAKE_CASE = watermark_detected.tolist() if any(UpperCAmelCase__ ): logger.warning( "Potential watermarked content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, watermark_detected_ in enumerate(UpperCAmelCase__ ): if watermark_detected_: __SCREAMING_SNAKE_CASE = np.zeros(images[idx].shape ) return images, nsfw_detected, watermark_detected
195
1
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def UpperCamelCase ( __lowercase : float ,__lowercase : float ,__lowercase : bool = False ): '''simple docstring''' if radian_mode: return [magnitude * cos(__lowercase ), magnitude * sin(__lowercase )] return [magnitude * cos(radians(__lowercase ) ), magnitude * sin(radians(__lowercase ) )] def UpperCamelCase ( __lowercase : NDArray[floataa] ,__lowercase : NDArray[floataa] ,__lowercase : float = 10**-1 ): '''simple docstring''' A_ : NDArray[floataa] = cross(__lowercase ,__lowercase ) A_ : float = sum(__lowercase ) return abs(__lowercase ) < eps if __name__ == "__main__": # Test to check if it works _UpperCAmelCase = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) _UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg _UpperCAmelCase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) _UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg _UpperCAmelCase = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) _UpperCAmelCase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
140
import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) _UpperCAmelCase = { """sample_size""": 32, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 2, """num_class_embeds""": 1000, """block_out_channels""": [32, 64], """attention_head_dim""": 8, """down_block_types""": [ """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """scale_shift""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _UpperCAmelCase = { """sample_size""": 64, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 3, """num_class_embeds""": 1000, """block_out_channels""": [192, 192 * 2, 192 * 3, 192 * 4], """attention_head_dim""": 64, """down_block_types""": [ """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """AttnUpBlock2D""", """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """scale_shift""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _UpperCAmelCase = { """sample_size""": 256, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 2, """num_class_embeds""": None, """block_out_channels""": [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4], """attention_head_dim""": 64, """down_block_types""": [ """ResnetDownsampleBlock2D""", """ResnetDownsampleBlock2D""", """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """AttnUpBlock2D""", """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", """ResnetUpsampleBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """default""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } _UpperCAmelCase = { """num_train_timesteps""": 40, """sigma_min""": 0.002, """sigma_max""": 80.0, } _UpperCAmelCase = { """num_train_timesteps""": 201, """sigma_min""": 0.002, """sigma_max""": 80.0, } _UpperCAmelCase = { """num_train_timesteps""": 151, """sigma_min""": 0.002, """sigma_max""": 80.0, } def UpperCamelCase ( __lowercase : int ): '''simple docstring''' if isinstance(__lowercase ,__lowercase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError('boolean value expected' ) def UpperCamelCase ( __lowercase : Any ,__lowercase : Tuple ,__lowercase : Optional[int] ,__lowercase : Tuple ,__lowercase : Dict=False ): '''simple docstring''' A_ : str = checkpoint[f'''{old_prefix}.in_layers.0.weight'''] A_ : int = checkpoint[f'''{old_prefix}.in_layers.0.bias'''] A_ : int = checkpoint[f'''{old_prefix}.in_layers.2.weight'''] A_ : List[Any] = checkpoint[f'''{old_prefix}.in_layers.2.bias'''] A_ : Optional[int] = checkpoint[f'''{old_prefix}.emb_layers.1.weight'''] A_ : Tuple = checkpoint[f'''{old_prefix}.emb_layers.1.bias'''] A_ : List[Any] = checkpoint[f'''{old_prefix}.out_layers.0.weight'''] A_ : int = checkpoint[f'''{old_prefix}.out_layers.0.bias'''] A_ : Optional[Any] = checkpoint[f'''{old_prefix}.out_layers.3.weight'''] A_ : List[Any] = checkpoint[f'''{old_prefix}.out_layers.3.bias'''] if has_skip: A_ : Any = checkpoint[f'''{old_prefix}.skip_connection.weight'''] A_ : List[Any] = checkpoint[f'''{old_prefix}.skip_connection.bias'''] return new_checkpoint def UpperCamelCase ( __lowercase : Tuple ,__lowercase : List[str] ,__lowercase : int ,__lowercase : Optional[Any] ,__lowercase : Union[str, Any]=None ): '''simple docstring''' A_ , A_ , A_ : Tuple = checkpoint[f'''{old_prefix}.qkv.weight'''].chunk(3 ,dim=0 ) A_ , A_ , A_ : List[str] = checkpoint[f'''{old_prefix}.qkv.bias'''].chunk(3 ,dim=0 ) A_ : Any = checkpoint[f'''{old_prefix}.norm.weight'''] A_ : str = checkpoint[f'''{old_prefix}.norm.bias'''] A_ : int = weight_q.squeeze(-1 ).squeeze(-1 ) A_ : int = bias_q.squeeze(-1 ).squeeze(-1 ) A_ : List[str] = weight_k.squeeze(-1 ).squeeze(-1 ) A_ : Any = bias_k.squeeze(-1 ).squeeze(-1 ) A_ : List[Any] = weight_v.squeeze(-1 ).squeeze(-1 ) A_ : Dict = bias_v.squeeze(-1 ).squeeze(-1 ) A_ : Any = ( checkpoint[f'''{old_prefix}.proj_out.weight'''].squeeze(-1 ).squeeze(-1 ) ) A_ : Dict = checkpoint[f'''{old_prefix}.proj_out.bias'''].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def UpperCamelCase ( __lowercase : str ,__lowercase : Union[str, Any] ): '''simple docstring''' A_ : Union[str, Any] = torch.load(__lowercase ,map_location='cpu' ) A_ : Dict = {} A_ : Dict = checkpoint['time_embed.0.weight'] A_ : Any = checkpoint['time_embed.0.bias'] A_ : Union[str, Any] = checkpoint['time_embed.2.weight'] A_ : Tuple = checkpoint['time_embed.2.bias'] if unet_config["num_class_embeds"] is not None: A_ : Dict = checkpoint['label_emb.weight'] A_ : Tuple = checkpoint['input_blocks.0.0.weight'] A_ : Tuple = checkpoint['input_blocks.0.0.bias'] A_ : str = unet_config['down_block_types'] A_ : List[str] = unet_config['layers_per_block'] A_ : Any = unet_config['attention_head_dim'] A_ : int = unet_config['block_out_channels'] A_ : Union[str, Any] = 1 A_ : List[str] = channels_list[0] for i, layer_type in enumerate(__lowercase ): A_ : List[Any] = channels_list[i] A_ : int = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(__lowercase ): A_ : Any = f'''down_blocks.{i}.resnets.{j}''' A_ : str = f'''input_blocks.{current_layer}.0''' A_ : List[Any] = True if j == 0 and downsample_block_has_skip else False A_ : Any = convert_resnet(__lowercase ,__lowercase ,__lowercase ,__lowercase ,has_skip=__lowercase ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(__lowercase ): A_ : Dict = f'''down_blocks.{i}.resnets.{j}''' A_ : Optional[int] = f'''input_blocks.{current_layer}.0''' A_ : str = True if j == 0 and downsample_block_has_skip else False A_ : int = convert_resnet(__lowercase ,__lowercase ,__lowercase ,__lowercase ,has_skip=__lowercase ) A_ : Optional[Any] = f'''down_blocks.{i}.attentions.{j}''' A_ : Union[str, Any] = f'''input_blocks.{current_layer}.1''' A_ : Tuple = convert_attention( __lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase ) current_layer += 1 if i != len(__lowercase ) - 1: A_ : List[Any] = f'''down_blocks.{i}.downsamplers.0''' A_ : Dict = f'''input_blocks.{current_layer}.0''' A_ : Tuple = convert_resnet(__lowercase ,__lowercase ,__lowercase ,__lowercase ) current_layer += 1 A_ : Tuple = current_channels # hardcoded the mid-block for now A_ : int = 'mid_block.resnets.0' A_ : Dict = 'middle_block.0' A_ : int = convert_resnet(__lowercase ,__lowercase ,__lowercase ,__lowercase ) A_ : Tuple = 'mid_block.attentions.0' A_ : Any = 'middle_block.1' A_ : Tuple = convert_attention(__lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase ) A_ : Union[str, Any] = 'mid_block.resnets.1' A_ : Any = 'middle_block.2' A_ : int = convert_resnet(__lowercase ,__lowercase ,__lowercase ,__lowercase ) A_ : Tuple = 0 A_ : Optional[Any] = unet_config['up_block_types'] for i, layer_type in enumerate(__lowercase ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): A_ : Dict = f'''up_blocks.{i}.resnets.{j}''' A_ : Dict = f'''output_blocks.{current_layer}.0''' A_ : List[str] = convert_resnet(__lowercase ,__lowercase ,__lowercase ,__lowercase ,has_skip=__lowercase ) current_layer += 1 if i != len(__lowercase ) - 1: A_ : Union[str, Any] = f'''up_blocks.{i}.upsamplers.0''' A_ : List[str] = f'''output_blocks.{current_layer-1}.1''' A_ : Optional[Any] = convert_resnet(__lowercase ,__lowercase ,__lowercase ,__lowercase ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): A_ : int = f'''up_blocks.{i}.resnets.{j}''' A_ : Union[str, Any] = f'''output_blocks.{current_layer}.0''' A_ : Optional[int] = convert_resnet(__lowercase ,__lowercase ,__lowercase ,__lowercase ,has_skip=__lowercase ) A_ : Optional[Any] = f'''up_blocks.{i}.attentions.{j}''' A_ : Any = f'''output_blocks.{current_layer}.1''' A_ : List[str] = convert_attention( __lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase ) current_layer += 1 if i != len(__lowercase ) - 1: A_ : Dict = f'''up_blocks.{i}.upsamplers.0''' A_ : Any = f'''output_blocks.{current_layer-1}.2''' A_ : List[str] = convert_resnet(__lowercase ,__lowercase ,__lowercase ,__lowercase ) A_ : Any = checkpoint['out.0.weight'] A_ : Dict = checkpoint['out.0.bias'] A_ : int = checkpoint['out.2.weight'] A_ : List[str] = checkpoint['out.2.bias'] return new_checkpoint if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("""--unet_path""", default=None, type=str, required=True, help="""Path to the unet.pt to convert.""") parser.add_argument( """--dump_path""", default=None, type=str, required=True, help="""Path to output the converted UNet model.""" ) parser.add_argument("""--class_cond""", default=True, type=str, help="""Whether the model is class-conditional.""") _UpperCAmelCase = parser.parse_args() _UpperCAmelCase = strabool(args.class_cond) _UpperCAmelCase = os.path.basename(args.unet_path) print(F"""Checkpoint: {ckpt_name}""") # Get U-Net config if "imagenet64" in ckpt_name: _UpperCAmelCase = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): _UpperCAmelCase = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: _UpperCAmelCase = TEST_UNET_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") if not args.class_cond: _UpperCAmelCase = None _UpperCAmelCase = con_pt_to_diffuser(args.unet_path, unet_config) _UpperCAmelCase = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: _UpperCAmelCase = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: _UpperCAmelCase = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): _UpperCAmelCase = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") _UpperCAmelCase = CMStochasticIterativeScheduler(**scheduler_config) _UpperCAmelCase = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
140
1
"""simple docstring""" import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def _snake_case ( UpperCAmelCase_ : Dict ): def wrapper(*UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Dict ): A__ = timeit.default_timer() A__ = func(*UpperCAmelCase_ , **UpperCAmelCase_ ) A__ = timeit.default_timer() - starttime return delta A__ = func.__name__ return wrapper def _snake_case ( UpperCAmelCase_ : dict , UpperCAmelCase_ : int=100 , UpperCAmelCase_ : List[Any]=None ): A__ = [] A__ = seq_shapes or {} for i in range(UpperCAmelCase_ ): A__ = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(UpperCAmelCase_ , _ArrayXD ): A__ = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(UpperCAmelCase_ , datasets.Value ): if v.dtype == "string": A__ = '''The small grey turtle was surprisingly fast when challenged.''' else: A__ = np.random.randint(10 , size=1 ).astype(v.dtype ).item() elif isinstance(UpperCAmelCase_ , datasets.Sequence ): while isinstance(UpperCAmelCase_ , datasets.Sequence ): A__ = v.feature A__ = seq_shapes[k] A__ = np.random.rand(*UpperCAmelCase_ ).astype(v.dtype ) A__ = data dummy_data.append((i, example) ) return dummy_data def _snake_case ( UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[Any]=100 , UpperCAmelCase_ : List[Any]=None ): A__ = generate_examples(UpperCAmelCase_ , num_examples=UpperCAmelCase_ , seq_shapes=UpperCAmelCase_ ) with ArrowWriter(features=UpperCAmelCase_ , path=UpperCAmelCase_ ) as writer: for key, record in dummy_data: A__ = features.encode_example(UpperCAmelCase_ ) writer.write(UpperCAmelCase_ ) A__ = writer.finalize() if not num_final_examples == num_examples: raise ValueError( F"""Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.""" ) A__ = datasets.Dataset.from_file(filename=UpperCAmelCase_ , info=datasets.DatasetInfo(features=UpperCAmelCase_ ) ) return dataset
357
"""simple docstring""" import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class a ( _lowerCamelCase ): """simple docstring""" def __init__( self: int , UpperCamelCase: str = "▁" , UpperCamelCase: bool = True , UpperCamelCase: Union[str, AddedToken] = "<unk>" , UpperCamelCase: Union[str, AddedToken] = "</s>" , UpperCamelCase: Union[str, AddedToken] = "<pad>" , ): """simple docstring""" A__ = { """pad""": {"""id""": 0, """token""": pad_token}, """eos""": {"""id""": 1, """token""": eos_token}, """unk""": {"""id""": 2, """token""": unk_token}, } A__ = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): A__ = token_dict["""token"""] A__ = Tokenizer(Unigram() ) A__ = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(""" {2,}""" ) , """ """ ), normalizers.Lowercase(), ] ) A__ = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=UpperCamelCase , add_prefix_space=UpperCamelCase ), pre_tokenizers.Digits(individual_digits=UpperCamelCase ), pre_tokenizers.Punctuation(), ] ) A__ = decoders.Metaspace(replacement=UpperCamelCase , add_prefix_space=UpperCamelCase ) A__ = TemplateProcessing( single=f"""$A {self.special_tokens['eos']['token']}""" , special_tokens=[(self.special_tokens["""eos"""]["""token"""], self.special_tokens["""eos"""]["""id"""])] , ) A__ = { """model""": """SentencePieceUnigram""", """replacement""": replacement, """add_prefix_space""": add_prefix_space, } super().__init__(UpperCamelCase , UpperCamelCase ) def UpperCamelCase ( self: Tuple , UpperCamelCase: Union[str, List[str]] , UpperCamelCase: int = 80_00 , UpperCamelCase: bool = True , ): """simple docstring""" A__ = trainers.UnigramTrainer( vocab_size=UpperCamelCase , special_tokens=self.special_tokens_list , show_progress=UpperCamelCase , ) if isinstance(UpperCamelCase , UpperCamelCase ): A__ = [files] self._tokenizer.train(UpperCamelCase , trainer=UpperCamelCase ) self.add_unk_id() def UpperCamelCase ( self: Union[str, Any] , UpperCamelCase: Union[Iterator[str], Iterator[Iterator[str]]] , UpperCamelCase: int = 80_00 , UpperCamelCase: bool = True , ): """simple docstring""" A__ = trainers.UnigramTrainer( vocab_size=UpperCamelCase , special_tokens=self.special_tokens_list , show_progress=UpperCamelCase , ) self._tokenizer.train_from_iterator(UpperCamelCase , trainer=UpperCamelCase ) self.add_unk_id() def UpperCamelCase ( self: List[str] ): """simple docstring""" A__ = json.loads(self._tokenizer.to_str() ) A__ = self.special_tokens["""unk"""]["""id"""] A__ = Tokenizer.from_str(json.dumps(UpperCamelCase ) )
69
0
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version 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.17.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") _UpperCamelCase : Any = logging.getLogger(__name__) @dataclass class UpperCAmelCase_ : lowerCamelCase__ : Optional[str] = field( default="tab_fact" , metadata={"help": "The name of the dataset to use (via the datasets library)."}) lowerCamelCase__ : Optional[str] = field( default="tab_fact" , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} , ) lowerCamelCase__ : int = field( default=1_0_2_4 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) lowerCamelCase__ : bool = field( default=_a , metadata={"help": "Overwrite the cached preprocessed datasets or not."}) lowerCamelCase__ : bool = field( default=_a , 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." ) } , ) lowerCamelCase__ : Optional[int] = field( default=_a , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) lowerCamelCase__ : Optional[int] = field( default=_a , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) lowerCamelCase__ : Optional[int] = field( default=_a , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "A csv or a json file containing the training data."}) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "A csv or a json file containing the validation data."}) lowerCamelCase__ : Optional[str] = field(default=_a , metadata={"help": "A csv or a json file containing the test data."}) def _UpperCAmelCase ( self ) -> Optional[Any]: if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError('Need either a GLUE task, a training/validation file or a dataset name.' ) else: lowercase__ : Optional[int] = self.train_file.split('.' )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." lowercase__ : Optional[Any] = self.validation_file.split('.' )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class UpperCAmelCase_ : lowerCamelCase__ : str = field( default=_a , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "Pretrained config name or path if not the same as model_name"}) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) lowerCamelCase__ : bool = field( default=_a , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) lowerCamelCase__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) lowerCamelCase__ : bool = field( default=_a , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) def a_ ( ): '''simple docstring''' lowercase__ : Optional[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowercase__ , lowercase__ , lowercase__ : str = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowercase__ , lowercase__ , lowercase__ : List[Any] = parser.parse_args_into_dataclasses() # 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 )] , ) lowercase__ : int = training_args.get_process_log_level() logger.setLevel(_lowerCAmelCase ) datasets.utils.logging.set_verbosity(_lowerCAmelCase ) transformers.utils.logging.set_verbosity(_lowerCAmelCase ) 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. lowercase__ : Optional[int] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: lowercase__ : Any = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. lowercase__ : Optional[int] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. lowercase__ : Tuple = {'train': data_args.train_file, 'validation': data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: lowercase__ : List[Any] = data_args.train_file.split('.' )[-1] lowercase__ : Optional[int] = data_args.test_file.split('.' )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." lowercase__ : List[str] = data_args.test_file else: raise ValueError('Need either a GLUE task or a test file for `do_predict`.' ) for key in data_files.keys(): logger.info(f"""load a local file for {key}: {data_files[key]}""" ) if data_args.train_file.endswith('.csv' ): # Loading a dataset from local csv files lowercase__ : List[Any] = load_dataset('csv' , data_files=_lowerCAmelCase , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files lowercase__ : List[Any] = load_dataset('json' , data_files=_lowerCAmelCase , cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels lowercase__ : int = raw_datasets['train'].features['label'].names lowercase__ : Union[str, Any] = len(_lowerCAmelCase ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowercase__ : Union[str, Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=_lowerCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # load tapex tokenizer lowercase__ : List[str] = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=_lowerCAmelCase , ) lowercase__ : Optional[int] = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_lowerCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Padding strategy if data_args.pad_to_max_length: lowercase__ : Tuple = 'max_length' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch lowercase__ : Optional[int] = False # Some models have set the order of the labels to use, so let's make sure we do use it. lowercase__ : str = {'Refused': 0, 'Entailed': 1} lowercase__ : Dict = {0: 'Refused', 1: 'Entailed'} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) lowercase__ : Optional[Any] = min(data_args.max_seq_length , tokenizer.model_max_length ) def preprocess_tabfact_function(_lowerCAmelCase : Optional[int] ): # Tokenize the texts def _convert_table_text_to_pandas(_lowerCAmelCase : Union[str, Any] ): lowercase__ : Optional[int] = [_table_row.split('#' ) for _table_row in _table_text.strip('\n' ).split('\n' )] lowercase__ : str = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd lowercase__ : Tuple = examples['statement'] lowercase__ : int = list(map(_convert_table_text_to_pandas , examples['table_text'] ) ) lowercase__ : Optional[int] = tokenizer(_lowerCAmelCase , _lowerCAmelCase , padding=_lowerCAmelCase , max_length=_lowerCAmelCase , truncation=_lowerCAmelCase ) lowercase__ : str = examples['label'] return result with training_args.main_process_first(desc='dataset map pre-processing' ): lowercase__ : str = raw_datasets.map( _lowerCAmelCase , batched=_lowerCAmelCase , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on dataset' , ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError('--do_train requires a train dataset' ) lowercase__ : int = raw_datasets['train'] if data_args.max_train_samples is not None: lowercase__ : int = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError('--do_eval requires a validation dataset' ) lowercase__ : str = raw_datasets['validation'] if data_args.max_eval_samples is not None: lowercase__ : Any = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError('--do_predict requires a test dataset' ) lowercase__ : List[Any] = raw_datasets['test'] if data_args.max_predict_samples is not None: lowercase__ : Optional[int] = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(_lowerCAmelCase ) ) , 3 ): logger.info(f"""Sample {index} of the training set: {train_dataset[index]}.""" ) # 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(_lowerCAmelCase : EvalPrediction ): lowercase__ : Optional[int] = p.predictions[0] if isinstance(p.predictions , _lowerCAmelCase ) else p.predictions lowercase__ : List[str] = np.argmax(_lowerCAmelCase , axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: lowercase__ : List[str] = default_data_collator elif training_args.fpaa: lowercase__ : Optional[Any] = DataCollatorWithPadding(_lowerCAmelCase , pad_to_multiple_of=8 ) else: lowercase__ : str = None # Initialize our Trainer lowercase__ : int = Trainer( model=_lowerCAmelCase , args=_lowerCAmelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=_lowerCAmelCase , tokenizer=_lowerCAmelCase , data_collator=_lowerCAmelCase , ) # Training if training_args.do_train: lowercase__ : Union[str, Any] = None if training_args.resume_from_checkpoint is not None: lowercase__ : str = training_args.resume_from_checkpoint elif last_checkpoint is not None: lowercase__ : Optional[int] = last_checkpoint lowercase__ : Tuple = trainer.train(resume_from_checkpoint=_lowerCAmelCase ) lowercase__ : Tuple = train_result.metrics lowercase__ : str = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowerCAmelCase ) ) lowercase__ : Any = min(_lowerCAmelCase , len(_lowerCAmelCase ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('train' , _lowerCAmelCase ) trainer.save_metrics('train' , _lowerCAmelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) lowercase__ : Union[str, Any] = trainer.evaluate(eval_dataset=_lowerCAmelCase ) lowercase__ : str = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_lowerCAmelCase ) lowercase__ : List[str] = min(_lowerCAmelCase , len(_lowerCAmelCase ) ) trainer.log_metrics('eval' , _lowerCAmelCase ) trainer.save_metrics('eval' , _lowerCAmelCase ) if training_args.do_predict: logger.info('*** Predict ***' ) # Removing the `label` columns because it contains -1 and Trainer won't like that. lowercase__ : int = predict_dataset.remove_columns('label' ) lowercase__ : Any = trainer.predict(_lowerCAmelCase , metric_key_prefix='predict' ).predictions lowercase__ : str = np.argmax(_lowerCAmelCase , axis=1 ) lowercase__ : Optional[Any] = os.path.join(training_args.output_dir , 'predict_results_tabfact.txt' ) if trainer.is_world_process_zero(): with open(_lowerCAmelCase , 'w' ) as writer: logger.info('***** Predict Results *****' ) writer.write('index\tprediction\n' ) for index, item in enumerate(_lowerCAmelCase ): lowercase__ : Optional[int] = label_list[item] writer.write(f"""{index}\t{item}\n""" ) lowercase__ : Union[str, Any] = {'finetuned_from': model_args.model_name_or_path, 'tasks': 'text-classification'} if training_args.push_to_hub: trainer.push_to_hub(**_lowerCAmelCase ) else: trainer.create_model_card(**_lowerCAmelCase ) def a_ ( _lowerCAmelCase : List[Any] ): '''simple docstring''' main() if __name__ == "__main__": main()
77
'''simple docstring''' import comet # From: unbabel-comet import torch import datasets lowerCamelCase_ = datasets.logging.get_logger(__name__) lowerCamelCase_ = '''\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = {Unbabel\'s Participation in the WMT20 Metrics Shared Task}, booktitle = {Proceedings of the Fifth Conference on Machine Translation}, month = {November}, year = {2020}, address = {Online}, publisher = {Association for Computational Linguistics}, pages = {909--918}, } @inproceedings{rei-etal-2020-comet, title = "{COMET}: A Neural Framework for {MT} Evaluation", author = "Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon", booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)", month = nov, year = "2020", address = "Online", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/2020.emnlp-main.213", pages = "2685--2702", } ''' lowerCamelCase_ = '''\ Crosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM). With the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition. See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information. ''' lowerCamelCase_ = ''' COMET score. Args: `sources` (list of str): Source sentences `predictions` (list of str): candidate translations `references` (list of str): reference translations `cuda` (bool): If set to True, runs COMET using GPU `show_progress` (bool): Shows progress `model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None. Returns: `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`. `scores`: List of scores. Examples: >>> comet_metric = datasets.load_metric(\'comet\') >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\') # you can also choose which model to use >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."] >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"] >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"] >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source) >>> print([round(v, 2) for v in results["scores"]]) [0.19, 0.92] ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _UpperCAmelCase ( datasets.Metric ): """simple docstring""" def lowerCAmelCase ( self : int ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://unbabel.github.io/COMET/html/index.html" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "sources": datasets.Value("string" , id="sequence" ), "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/Unbabel/COMET"] , reference_urls=[ "https://github.com/Unbabel/COMET", "https://www.aclweb.org/anthology/2020.emnlp-main.213/", "http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6", ] , ) def lowerCAmelCase ( self : Any , __UpperCAmelCase : str ): '''simple docstring''' if self.config_name == "default": _A = comet.load_from_checkpoint(comet.download_model("wmt20-comet-da" ) ) else: _A = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def lowerCAmelCase ( self : str , __UpperCAmelCase : str , __UpperCAmelCase : int , __UpperCAmelCase : Any , __UpperCAmelCase : Tuple=None , __UpperCAmelCase : int=False ): '''simple docstring''' if gpus is None: _A = 1 if torch.cuda.is_available() else 0 _A = {"src": sources, "mt": predictions, "ref": references} _A = [dict(zip(__UpperCAmelCase , __UpperCAmelCase ) ) for t in zip(*data.values() )] _A , _A = self.scorer.predict(__UpperCAmelCase , gpus=__UpperCAmelCase , progress_bar=__UpperCAmelCase ) return {"mean_score": mean_score, "scores": scores}
79
0
from ..utils import DummyObject, requires_backends class UpperCAmelCase ( metaclass=__A ): '''simple docstring''' lowerCamelCase_ = ['''torch''', '''torchsde'''] def __init__( self , *lowercase , **lowercase ): """simple docstring""" requires_backends(self , ['torch', 'torchsde'] ) @classmethod def lowerCAmelCase_ ( cls , *lowercase , **lowercase ): """simple docstring""" requires_backends(cls , ['torch', 'torchsde'] ) @classmethod def lowerCAmelCase_ ( cls , *lowercase , **lowercase ): """simple docstring""" requires_backends(cls , ['torch', 'torchsde'] )
192
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} _UpperCAmelCase = { """vocab_file""": { """squeezebert/squeezebert-uncased""": ( """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt""" ), """squeezebert/squeezebert-mnli""": """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt""", """squeezebert/squeezebert-mnli-headless""": ( """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """squeezebert/squeezebert-uncased""": ( """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json""" ), """squeezebert/squeezebert-mnli""": ( """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json""" ), """squeezebert/squeezebert-mnli-headless""": ( """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json""" ), }, } _UpperCAmelCase = { """squeezebert/squeezebert-uncased""": 512, """squeezebert/squeezebert-mnli""": 512, """squeezebert/squeezebert-mnli-headless""": 512, } _UpperCAmelCase = { """squeezebert/squeezebert-uncased""": {"""do_lower_case""": True}, """squeezebert/squeezebert-mnli""": {"""do_lower_case""": True}, """squeezebert/squeezebert-mnli-headless""": {"""do_lower_case""": True}, } class UpperCAmelCase ( __A ): '''simple docstring''' lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = PRETRAINED_INIT_CONFIGURATION lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = SqueezeBertTokenizer def __init__( self , lowercase=None , lowercase=None , lowercase=True , lowercase="[UNK]" , lowercase="[SEP]" , lowercase="[PAD]" , lowercase="[CLS]" , lowercase="[MASK]" , lowercase=True , lowercase=None , **lowercase , ): """simple docstring""" super().__init__( lowercase , tokenizer_file=lowercase , do_lower_case=lowercase , unk_token=lowercase , sep_token=lowercase , pad_token=lowercase , cls_token=lowercase , mask_token=lowercase , tokenize_chinese_chars=lowercase , strip_accents=lowercase , **lowercase , ) A_ : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , lowercase ) != do_lower_case or normalizer_state.get('strip_accents' , lowercase ) != strip_accents or normalizer_state.get('handle_chinese_chars' , lowercase ) != tokenize_chinese_chars ): A_ : Dict = getattr(lowercase , normalizer_state.pop('type' ) ) A_ : Optional[int] = do_lower_case A_ : Optional[Any] = strip_accents A_ : str = tokenize_chinese_chars A_ : Any = normalizer_class(**lowercase ) A_ : Tuple = do_lower_case def lowerCAmelCase_ ( self , lowercase , lowercase=None ): """simple docstring""" A_ : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCAmelCase_ ( self , lowercase , lowercase = None ): """simple docstring""" A_ : Dict = [self.sep_token_id] A_ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase_ ( self , lowercase , lowercase = None ): """simple docstring""" A_ : Dict = self._tokenizer.model.save(lowercase , name=lowercase ) return tuple(lowercase )
192
1
"""simple docstring""" import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowerCamelCase__ = WebClient(token=os.environ["""CI_SLACK_BOT_TOKEN"""]) def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : List[str] = test_results.split(' ' ) __lowerCAmelCase : Tuple = 0 __lowerCAmelCase : List[Any] = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. __lowerCAmelCase : int = expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(_UpperCamelCase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : Optional[int] = {} __lowerCAmelCase : int = None __lowerCAmelCase : List[Any] = False for line in failures_short_lines.split('\n' ): if re.search(r'_ \[doctest\]' , _UpperCamelCase ): __lowerCAmelCase : List[str] = True __lowerCAmelCase : Union[str, Any] = line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): __lowerCAmelCase : Union[str, Any] = line __lowerCAmelCase : Any = False return failures class A__ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Optional[int] = title __lowerCAmelCase : List[Any] = doc_test_results['time_spent'].split(',' )[0] __lowerCAmelCase : Optional[int] = doc_test_results['success'] __lowerCAmelCase : Dict = doc_test_results['failures'] __lowerCAmelCase : Tuple = self.n_success + self.n_failures # Failures and success of the modeling tests __lowerCAmelCase : Optional[int] = doc_test_results @property def __lowerCamelCase ( self ): __lowerCAmelCase : Union[str, Any] = [self._time_spent] __lowerCAmelCase : int = 0 for time in time_spent: __lowerCAmelCase : Tuple = time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(_SCREAMING_SNAKE_CASE ) == 1: __lowerCAmelCase : Dict = [0, 0, time_parts[0]] __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Any = total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f"{int(_SCREAMING_SNAKE_CASE )}h{int(_SCREAMING_SNAKE_CASE )}m{int(_SCREAMING_SNAKE_CASE )}s" @property def __lowerCamelCase ( self ): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def __lowerCamelCase ( self ): return { "type": "section", "text": { "type": "plain_text", "text": f"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def __lowerCamelCase ( self ): return { "type": "section", "text": { "type": "plain_text", "text": ( f"There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in" f" {self.time}." ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def __lowerCamelCase ( self ): __lowerCAmelCase : Any = 40 __lowerCAmelCase : int = {k: v['failed'] for k, v in doc_test_results.items() if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} __lowerCAmelCase : Any = '' for category, failures in category_failures.items(): if len(_SCREAMING_SNAKE_CASE ) == 0: continue if report != "": report += "\n\n" report += f"*{category} failures*:".ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(_SCREAMING_SNAKE_CASE ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f"The following examples had failures:\n\n\n{report}\n", }, } @property def __lowerCamelCase ( self ): __lowerCAmelCase : List[Any] = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(_SCREAMING_SNAKE_CASE ) @staticmethod def __lowerCamelCase ( ): __lowerCAmelCase : Dict = [ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(_SCREAMING_SNAKE_CASE )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=_SCREAMING_SNAKE_CASE , ) def __lowerCamelCase ( self ): print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) __lowerCAmelCase : Any = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else 'All tests passed.' __lowerCAmelCase : Optional[Any] = client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=_SCREAMING_SNAKE_CASE , ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = '' for key, value in failures.items(): __lowerCAmelCase : str = value[:2_00] + ' [Truncated]' if len(_SCREAMING_SNAKE_CASE ) > 2_50 else value failures_text += f"*{key}*\n_{value}_\n\n" __lowerCAmelCase : int = job_name __lowerCAmelCase : str = {'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: __lowerCAmelCase : int = { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def __lowerCamelCase ( self ): if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) __lowerCAmelCase : int = self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) __lowerCAmelCase : Union[str, Any] = sorted(self.doc_test_results.items() , key=lambda _SCREAMING_SNAKE_CASE : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): __lowerCAmelCase : List[Any] = f"*Num failures* :{len(job_result['failed'] )} \n" __lowerCAmelCase : Optional[int] = job_result['failures'] __lowerCAmelCase : Dict = self.get_reply_blocks(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , text=_SCREAMING_SNAKE_CASE ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=f"Results for {job}" , blocks=_SCREAMING_SNAKE_CASE , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def __lowerCAmelCase (): __lowerCAmelCase : int = os.environ['GITHUB_RUN_ID'] __lowerCAmelCase : Optional[int] = F"https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100" __lowerCAmelCase : int = requests.get(_UpperCamelCase ).json() __lowerCAmelCase : int = {} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) __lowerCAmelCase : Optional[int] = math.ceil((result['total_count'] - 100) / 100 ) for i in range(_UpperCamelCase ): __lowerCAmelCase : int = requests.get(url + F"&page={i + 2}" ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.' , _UpperCamelCase ) return {} def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : List[str] = {} if os.path.exists(_UpperCamelCase ): __lowerCAmelCase : Any = os.listdir(_UpperCamelCase ) for file in files: try: with open(os.path.join(_UpperCamelCase , _UpperCamelCase ) , encoding='utf-8' ) as f: __lowerCAmelCase : List[str] = f.read() except UnicodeDecodeError as e: raise ValueError(F"Could not open {os.path.join(_UpperCamelCase , _UpperCamelCase )}." ) from e return _artifact def __lowerCAmelCase (): class A__ : def __init__( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = name __lowerCAmelCase : str = [] def __str__( self ): return self.name def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): self.paths.append({'name': self.name, 'path': path} ) __lowerCAmelCase : Dict[str, Artifact] = {} __lowerCAmelCase : Optional[Any] = filter(os.path.isdir , os.listdir() ) for directory in directories: __lowerCAmelCase : Optional[int] = directory if artifact_name not in _available_artifacts: __lowerCAmelCase : Union[str, Any] = Artifact(_UpperCamelCase ) _available_artifacts[artifact_name].add_path(_UpperCamelCase ) return _available_artifacts if __name__ == "__main__": lowerCamelCase__ = get_job_links() lowerCamelCase__ = retrieve_available_artifacts() lowerCamelCase__ = collections.OrderedDict( [ ("""*.py""", """API Examples"""), ("""*.md""", """MD Examples"""), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowerCamelCase__ = { v: { """failed""": [], """failures""": {}, } for v in docs.values() } # Link to the GitHub Action job lowerCamelCase__ = github_actions_job_links.get("""run_doctests""") lowerCamelCase__ = available_artifacts["""doc_tests_gpu_test_reports"""].paths[0] lowerCamelCase__ = retrieve_artifact(artifact_path["""name"""]) if "stats" in artifact: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = handle_test_results(artifact["""stats"""]) lowerCamelCase__ = failed lowerCamelCase__ = success lowerCamelCase__ = time_spent[1:-1] + """, """ lowerCamelCase__ = extract_first_line_failure(artifact["""failures_short"""]) for line in artifact["summary_short"].split("""\n"""): if re.search("""FAILED""", line): lowerCamelCase__ = line.replace("""FAILED """, """""") lowerCamelCase__ = line.split()[0].replace("""\n""", """""") if "::" in line: lowerCamelCase__ , lowerCamelCase__ = line.split("""::""") else: lowerCamelCase__ , lowerCamelCase__ = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowerCamelCase__ = docs[file_regex] doc_test_results[category]["failed"].append(test) lowerCamelCase__ = all_failures[test] if test in all_failures else """N/A""" lowerCamelCase__ = failure break lowerCamelCase__ = Message("""🤗 Results of the doc tests.""", doc_test_results) message.post() message.post_reply()
86
"""simple docstring""" 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 _A ( lowerCAmelCase , lowerCAmelCase ): snake_case__ : Tuple = 1 @register_to_config def __init__( self , __lowerCAmelCase = 1000 , __lowerCAmelCase = None ): """simple docstring""" self.set_timesteps(__lowerCAmelCase ) # standard deviation of the initial noise distribution lowercase = 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. lowercase = 4 # running values lowercase = [] def A__ ( self , __lowerCAmelCase , __lowerCAmelCase = None ): """simple docstring""" lowercase = num_inference_steps lowercase = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] lowercase = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: lowercase = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: lowercase = torch.sin(steps * math.pi / 2 ) ** 2 lowercase = (1.0 - self.betas**2) ** 0.5 lowercase = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] lowercase = timesteps.to(__lowerCAmelCase ) lowercase = [] def A__ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = True , ): """simple docstring""" 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""" ) lowercase = (self.timesteps == timestep).nonzero().item() lowercase = timestep_index + 1 lowercase = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(__lowerCAmelCase ) if len(self.ets ) == 1: lowercase = self.ets[-1] elif len(self.ets ) == 2: lowercase = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: lowercase = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: lowercase = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) lowercase = self._get_prev_sample(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__lowerCAmelCase ) def A__ ( self , __lowerCAmelCase , *__lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" return sample def A__ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" lowercase = self.alphas[timestep_index] lowercase = self.betas[timestep_index] lowercase = self.alphas[prev_timestep_index] lowercase = self.betas[prev_timestep_index] lowercase = (sample - sigma * ets) / max(__lowerCAmelCase , 1E-8 ) lowercase = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
197
0
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) 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 __snake_case : Optional[int] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt') __snake_case : List[str] = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) __snake_case : int = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowerCamelCase : '''simple docstring''' __snake_case = field( default='cifar10' , metadata={'help': 'Name of a dataset from the datasets package'} ) __snake_case = field( default=lowercase_ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) __snake_case = field( default=lowercase_ , metadata={'help': 'The column name of the images in the files. If not set, will try to use \'image\' or \'img\'.'} , ) __snake_case = field(default=lowercase_ , metadata={'help': 'A folder containing the training data.'} ) __snake_case = field(default=lowercase_ , metadata={'help': 'A folder containing the validation data.'} ) __snake_case = field( default=0.15 , metadata={'help': 'Percent to split off of train for validation.'} ) __snake_case = field(default=32 , metadata={'help': 'The size of the square patches to use for masking.'} ) __snake_case = field( default=0.6 , metadata={'help': 'Percentage of patches to mask.'} , ) __snake_case = field( default=lowercase_ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) __snake_case = field( default=lowercase_ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def lowercase__ ( self : str ) -> str: '''simple docstring''' A__ : List[Any] ={} if self.train_dir is not None: A__ : str =self.train_dir if self.validation_dir is not None: A__ : List[str] =self.validation_dir A__ : Union[str, Any] =data_files if data_files else None @dataclass class lowerCamelCase : '''simple docstring''' __snake_case = field( default=lowercase_ , metadata={ 'help': ( 'The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a ' 'checkpoint identifier on the hub. ' 'Don\'t set if you want to train a model from scratch.' ) } , ) __snake_case = field( default=lowercase_ , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(lowercase_ )} , ) __snake_case = field( default=lowercase_ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) __snake_case = field( default=lowercase_ , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) __snake_case = field( default=lowercase_ , metadata={'help': 'Where do you want to store (cache) the pretrained models/datasets downloaded from the hub'} , ) __snake_case = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) __snake_case = field(default=lowercase_ , metadata={'help': 'Name or path of preprocessor config.'} ) __snake_case = field( default=lowercase_ , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) __snake_case = field( default=lowercase_ , metadata={ 'help': ( 'The size (resolution) of each image. If not specified, will use `image_size` of the configuration.' ) } , ) __snake_case = field( default=lowercase_ , metadata={ 'help': ( 'The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration.' ) } , ) __snake_case = field( default=lowercase_ , metadata={'help': 'Stride to use for the encoder.'} , ) class lowerCamelCase : '''simple docstring''' def __init__( self : Dict , lowerCAmelCase_ : Optional[int]=1_92 , lowerCAmelCase_ : Dict=32 , lowerCAmelCase_ : Optional[int]=4 , lowerCAmelCase_ : int=0.6 ) -> str: '''simple docstring''' A__ : Tuple =input_size A__ : Union[str, Any] =mask_patch_size A__ : Union[str, Any] =model_patch_size A__ : int =mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError("""Input size must be divisible by mask patch size""" ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError("""Mask patch size must be divisible by model patch size""" ) A__ : str =self.input_size // self.mask_patch_size A__ : Optional[Any] =self.mask_patch_size // self.model_patch_size A__ : Optional[Any] =self.rand_size**2 A__ : Optional[int] =int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self : List[str] ) -> List[str]: '''simple docstring''' A__ : List[str] =np.random.permutation(self.token_count )[: self.mask_count] A__ : List[Any] =np.zeros(self.token_count , dtype=lowerCAmelCase_ ) A__ : List[Any] =1 A__ : Optional[int] =mask.reshape((self.rand_size, self.rand_size) ) A__ : List[str] =mask.repeat(self.scale , axis=0 ).repeat(self.scale , axis=1 ) return torch.tensor(mask.flatten() ) def __lowerCamelCase ( __snake_case : Optional[Any] ) -> List[str]: """simple docstring""" A__ : Tuple =torch.stack([example["""pixel_values"""] for example in examples] ) A__ : Tuple =torch.stack([example["""mask"""] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def __lowerCamelCase ( ) -> Dict: """simple docstring""" A__ : Optional[int] =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. A__ , A__ , A__ : Union[str, Any] =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: A__ , A__ , A__ : List[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_mim""", __snake_case, __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", handlers=[logging.StreamHandler(sys.stdout )], ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() A__ : List[str] =training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. A__ : str =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: A__ : Dict =get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. A__ : Union[str, Any] =load_dataset( data_args.dataset_name, data_args.dataset_config_name, data_files=data_args.data_files, cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) # If we don't have a validation split, split off a percentage of train as validation. A__ : List[Any] =None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split, __snake_case ) and data_args.train_val_split > 0.0: A__ : List[Any] =ds["""train"""].train_test_split(data_args.train_val_split ) A__ : Tuple =split["""train"""] A__ : Tuple =split["""test"""] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. A__ : str ={ """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name_or_path: A__ : List[Any] =AutoConfig.from_pretrained(model_args.config_name_or_path, **__snake_case ) elif model_args.model_name_or_path: A__ : str =AutoConfig.from_pretrained(model_args.model_name_or_path, **__snake_case ) else: A__ : List[Any] =CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}" ) config.update_from_string(model_args.config_overrides ) logger.info(f"New config: {config}" ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(__snake_case, """decoder_type""" ): A__ : Any ="""simmim""" # adapt config A__ : str =model_args.image_size if model_args.image_size is not None else config.image_size A__ : Tuple =model_args.patch_size if model_args.patch_size is not None else config.patch_size A__ : Optional[Any] =( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { """image_size""": model_args.image_size, """patch_size""": model_args.patch_size, """encoder_stride""": model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: A__ : Dict =AutoImageProcessor.from_pretrained(model_args.image_processor_name, **__snake_case ) elif model_args.model_name_or_path: A__ : str =AutoImageProcessor.from_pretrained(model_args.model_name_or_path, **__snake_case ) else: A__ : int ={ conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } A__ : str =IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: A__ : List[Any] =AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path, from_tf=bool(""".ckpt""" in model_args.model_name_or_path ), config=__snake_case, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) else: logger.info("""Training new model from scratch""" ) A__ : int =AutoModelForMaskedImageModeling.from_config(__snake_case ) if training_args.do_train: A__ : int =ds["""train"""].column_names else: A__ : List[Any] =ds["""validation"""].column_names if data_args.image_column_name is not None: A__ : str =data_args.image_column_name elif "image" in column_names: A__ : Dict ="""image""" elif "img" in column_names: A__ : Union[str, Any] ="""img""" else: A__ : List[str] =column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py A__ : Optional[Any] =Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size, scale=(0.67, 1.0), ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean, std=image_processor.image_std ), ] ) # create mask generator A__ : int =MaskGenerator( input_size=model_args.image_size, mask_patch_size=data_args.mask_patch_size, model_patch_size=model_args.patch_size, mask_ratio=data_args.mask_ratio, ) def preprocess_images(__snake_case : Tuple ): A__ : Union[str, Any] =[transforms(__snake_case ) for image in examples[image_column_name]] A__ : Tuple =[mask_generator() for i in range(len(examples[image_column_name] ) )] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: A__ : Any =ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: A__ : Optional[Any] =( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Initialize our trainer A__ : List[Any] =Trainer( model=__snake_case, args=__snake_case, train_dataset=ds["""train"""] if training_args.do_train else None, eval_dataset=ds["""validation"""] if training_args.do_eval else None, tokenizer=__snake_case, data_collator=__snake_case, ) # Training if training_args.do_train: A__ : Any =None if training_args.resume_from_checkpoint is not None: A__ : Optional[int] =training_args.resume_from_checkpoint elif last_checkpoint is not None: A__ : List[Any] =last_checkpoint A__ : Union[str, Any] =trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""", train_result.metrics ) trainer.save_metrics("""train""", train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: A__ : Tuple =trainer.evaluate() trainer.log_metrics("""eval""", __snake_case ) trainer.save_metrics("""eval""", __snake_case ) # Write model card and (optionally) push to hub A__ : Optional[int] ={ """finetuned_from""": model_args.model_name_or_path, """tasks""": """masked-image-modeling""", """dataset""": data_args.dataset_name, """tags""": ["""masked-image-modeling"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) if __name__ == "__main__": main()
136
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( lowercase_ , lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' __snake_case = StableDiffusionInstructPixaPixPipeline __snake_case = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} __snake_case = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __snake_case = IMAGE_TO_IMAGE_IMAGE_PARAMS __snake_case = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowercase__ ( self : Dict ) -> str: '''simple docstring''' torch.manual_seed(0 ) A__ : int =UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) A__ : str =PNDMScheduler(skip_prk_steps=lowerCAmelCase_ ) torch.manual_seed(0 ) A__ : Dict =AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) A__ : List[Any] =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) A__ : Tuple =CLIPTextModel(lowerCAmelCase_ ) A__ : int =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) A__ : Union[str, Any] ={ """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def lowercase__ ( self : Union[str, Any] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Dict=0 ) -> str: '''simple docstring''' A__ : Optional[Any] =floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCAmelCase_ ) ).to(lowerCAmelCase_ ) A__ : str =image.cpu().permute(0 , 2 , 3 , 1 )[0] A__ : List[str] =Image.fromarray(np.uinta(lowerCAmelCase_ ) ).convert("""RGB""" ) if str(lowerCAmelCase_ ).startswith("""mps""" ): A__ : Any =torch.manual_seed(lowerCAmelCase_ ) else: A__ : int =torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) A__ : Optional[Any] ={ """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """image_guidance_scale""": 1, """output_type""": """numpy""", } return inputs def lowercase__ ( self : Any ) -> str: '''simple docstring''' A__ : Any ="""cpu""" # ensure determinism for the device-dependent torch.Generator A__ : Any =self.get_dummy_components() A__ : List[str] =StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase_ ) A__ : Dict =sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) A__ : List[Any] =self.get_dummy_inputs(lowerCAmelCase_ ) A__ : List[Any] =sd_pipe(**lowerCAmelCase_ ).images A__ : Dict =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A__ : Tuple =np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase__ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' A__ : Optional[int] ="""cpu""" # ensure determinism for the device-dependent torch.Generator A__ : List[str] =self.get_dummy_components() A__ : Union[str, Any] =StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase_ ) A__ : Union[str, Any] =sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) A__ : Optional[Any] =self.get_dummy_inputs(lowerCAmelCase_ ) A__ : Optional[int] ="""french fries""" A__ : Tuple =sd_pipe(**lowerCAmelCase_ , negative_prompt=lowerCAmelCase_ ) A__ : Union[str, Any] =output.images A__ : List[str] =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A__ : Tuple =np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase__ ( self : Dict ) -> Dict: '''simple docstring''' A__ : str ="""cpu""" # ensure determinism for the device-dependent torch.Generator A__ : str =self.get_dummy_components() A__ : List[Any] =StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase_ ) A__ : Union[str, Any] =sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) A__ : Tuple =self.get_dummy_inputs(lowerCAmelCase_ ) A__ : Dict =[inputs["""prompt"""]] * 2 A__ : Optional[int] =np.array(inputs["""image"""] ).astype(np.floataa ) / 255.0 A__ : List[str] =torch.from_numpy(lowerCAmelCase_ ).unsqueeze(0 ).to(lowerCAmelCase_ ) A__ : Union[str, Any] =image / 2 + 0.5 A__ : Optional[int] =image.permute(0 , 3 , 1 , 2 ) A__ : Dict =image.repeat(2 , 1 , 1 , 1 ) A__ : int =sd_pipe(**lowerCAmelCase_ ).images A__ : List[Any] =image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) A__ : List[Any] =np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase__ ( self : str ) -> Tuple: '''simple docstring''' A__ : Optional[Any] ="""cpu""" # ensure determinism for the device-dependent torch.Generator A__ : List[str] =self.get_dummy_components() A__ : List[str] =EulerAncestralDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" ) A__ : str =StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase_ ) A__ : int =sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) A__ : Union[str, Any] =self.get_dummy_inputs(lowerCAmelCase_ ) A__ : Optional[Any] =sd_pipe(**lowerCAmelCase_ ).images A__ : Tuple =image[0, -3:, -3:, -1] A__ : List[str] =[round(lowerCAmelCase_ , 4 ) for x in image_slice.flatten().tolist()] print(""",""".join([str(lowerCAmelCase_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) A__ : Any =np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase__ ( self : List[Any] ) -> int: '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def lowercase__ ( self : List[str] ) -> List[Any]: '''simple docstring''' A__ : Union[str, Any] =self.get_dummy_components() A__ : Optional[Any] =StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase_ ) A__ : Any =VaeImageProcessor(do_resize=lowerCAmelCase_ , do_normalize=lowerCAmelCase_ ) A__ : Dict =pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) A__ : str =pipe(**self.get_dummy_inputs_by_type(lowerCAmelCase_ , input_image_type="""pt""" ) )[0] A__ : List[Any] =components["""vae"""] A__ : Dict =self.get_dummy_inputs_by_type(lowerCAmelCase_ , input_image_type="""pt""" ) for image_param in self.image_latents_params: if image_param in inputs.keys(): A__ : List[Any] =vae.encode(inputs[image_param] ).latent_dist.mode() A__ : Optional[Any] =pipe(**lowerCAmelCase_ )[0] A__ : Dict =np.abs(out - out_latents_inputs ).max() self.assertLess(lowerCAmelCase_ , 1e-4 , """passing latents as image input generate different result from passing image""" ) @slow @require_torch_gpu class lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def lowercase__ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase__ ( self : int , lowerCAmelCase_ : int=0 ) -> List[str]: '''simple docstring''' A__ : List[Any] =torch.manual_seed(lowerCAmelCase_ ) A__ : Optional[Any] =load_image( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg""" ) A__ : List[Any] ={ """prompt""": """turn him into a cyborg""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """image_guidance_scale""": 1.0, """output_type""": """numpy""", } return inputs def lowercase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' A__ : List[Any] =StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=lowerCAmelCase_ ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe.enable_attention_slicing() A__ : Optional[Any] =self.get_inputs() A__ : Optional[Any] =pipe(**lowerCAmelCase_ ).images A__ : Tuple =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) A__ : Dict =np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowercase__ ( self : str ) -> Optional[int]: '''simple docstring''' A__ : List[str] =StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=lowerCAmelCase_ ) A__ : str =LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe.enable_attention_slicing() A__ : Union[str, Any] =self.get_inputs() A__ : Tuple =pipe(**lowerCAmelCase_ ).images A__ : List[Any] =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) A__ : List[Any] =np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowercase__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' A__ : List[str] =StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=lowerCAmelCase_ ) A__ : str =DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe.enable_attention_slicing() A__ : Optional[Any] =self.get_inputs() A__ : List[str] =pipe(**lowerCAmelCase_ ).images A__ : List[Any] =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) A__ : Any =np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowercase__ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' A__ : int =0 def callback_fn(lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : torch.FloatTensor ) -> None: A__ : Any =True nonlocal number_of_steps number_of_steps += 1 if step == 1: A__ : List[str] =latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) A__ : Optional[Any] =latents[0, -3:, -3:, -1] A__ : Tuple =np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: A__ : List[Any] =latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) A__ : Dict =latents[0, -3:, -3:, -1] A__ : List[Any] =np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 A__ : List[str] =False A__ : Optional[Any] =StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=lowerCAmelCase_ , torch_dtype=torch.floataa ) A__ : int =pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe.enable_attention_slicing() A__ : Optional[Any] =self.get_inputs() pipe(**lowerCAmelCase_ , callback=lowerCAmelCase_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def lowercase__ ( self : int ) -> Optional[Any]: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() A__ : Dict =StableDiffusionInstructPixaPixPipeline.from_pretrained( """timbrooks/instruct-pix2pix""" , safety_checker=lowerCAmelCase_ , torch_dtype=torch.floataa ) A__ : Union[str, Any] =pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() A__ : List[str] =self.get_inputs() A__ : Dict =pipe(**lowerCAmelCase_ ) A__ : List[str] =torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def lowercase__ ( self : str ) -> Optional[Any]: '''simple docstring''' A__ : Tuple =self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 A__ : int =inputs["""image"""].resize((5_04, 5_04) ) A__ : Optional[int] ="""timbrooks/instruct-pix2pix""" A__ : List[Any] =StableDiffusionInstructPixaPixPipeline.from_pretrained( lowerCAmelCase_ , safety_checker=lowerCAmelCase_ , ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe.enable_attention_slicing() A__ : Dict =pipe(**lowerCAmelCase_ ) A__ : Dict =output.images[0] A__ : int =image[2_55:2_58, 3_83:3_86, -1] assert image.shape == (5_04, 5_04, 3) A__ : Dict =np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
136
1
'''simple docstring''' import math def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase ): """simple docstring""" if ( not isinstance(lowerCAmelCase , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("""power_factor must be a valid float value between -1 and 1.""" ) return apparent_power * power_factor def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase ): """simple docstring""" if ( not isinstance(lowerCAmelCase , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("""power_factor must be a valid float value between -1 and 1.""" ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
70
import argparse import copy def _a ( lowerCamelCase: List[Any] ) -> List[str]: '''simple docstring''' __A = {} with open(lowerCamelCase ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: __A = [] _list.append([line.split()[1], line.split()[2]] ) __A = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: __A = [] _list.append([line.split()[0], line.split()[2]] ) __A = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def _a ( lowerCamelCase: Any , lowerCamelCase: Optional[Any] ) -> Dict: '''simple docstring''' with open(lowerCamelCase ) as f: __A = f.read(1 ) __A = start_node __A = [] __A = start_node __A = 0 while visiting not in first_solution: __A = 1_00_00 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(lowerCamelCase ) and k[0] not in first_solution: __A = k[1] __A = k[0] first_solution.append(lowerCamelCase ) __A = distance_of_first_solution + int(lowerCamelCase ) __A = best_node first_solution.append(lowerCamelCase ) __A = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 __A = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_00_00 ) return first_solution, distance_of_first_solution def _a ( lowerCamelCase: List[str] , lowerCamelCase: Any ) -> Any: '''simple docstring''' __A = [] for n in solution[1:-1]: __A = solution.index(lowerCamelCase ) for kn in solution[1:-1]: __A = solution.index(lowerCamelCase ) if n == kn: continue __A = copy.deepcopy(lowerCamelCase ) __A = kn __A = n __A = 0 for k in _tmp[:-1]: __A = _tmp[_tmp.index(lowerCamelCase ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: __A = distance + int(i[1] ) _tmp.append(lowerCamelCase ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) __A = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda lowerCamelCase : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def _a ( lowerCamelCase: Optional[int] , lowerCamelCase: Dict , lowerCamelCase: Any , lowerCamelCase: Optional[int] , lowerCamelCase: Union[str, Any] ) -> Any: '''simple docstring''' __A = 1 __A = first_solution __A = [] __A = distance_of_first_solution __A = solution while count <= iters: __A = find_neighborhood(lowerCamelCase , lowerCamelCase ) __A = 0 __A = neighborhood[index_of_best_solution] __A = len(lowerCamelCase ) - 1 __A = False while not found: __A = 0 while i < len(lowerCamelCase ): if best_solution[i] != solution[i]: __A = best_solution[i] __A = solution[i] break __A = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) __A = True __A = best_solution[:-1] __A = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: __A = cost __A = solution else: __A = index_of_best_solution + 1 __A = neighborhood[index_of_best_solution] if len(lowerCamelCase ) >= size: tabu_list.pop(0 ) __A = count + 1 return best_solution_ever, best_cost def _a ( lowerCamelCase: List[str]=None ) -> str: '''simple docstring''' __A = generate_neighbours(args.File ) __A , __A = generate_first_solution( args.File , lowerCamelCase ) __A , __A = tabu_search( lowerCamelCase , lowerCamelCase , lowerCamelCase , args.Iterations , args.Size , ) print(F"""Best solution: {best_sol}, with total distance: {best_cost}.""" ) if __name__ == "__main__": snake_case__ : Tuple = argparse.ArgumentParser(description='Tabu Search') parser.add_argument( '-f', '--File', type=str, help='Path to the file containing the data', required=True, ) parser.add_argument( '-i', '--Iterations', type=int, help='How many iterations the algorithm should perform', required=True, ) parser.add_argument( '-s', '--Size', type=int, help='Size of the tabu list', required=True ) # Pass the arguments to main method main(parser.parse_args())
117
0
'''simple docstring''' def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" if not numbers: return 0 if not isinstance(lowerCAmelCase , (list, tuple) ) or not all( isinstance(lowerCAmelCase , lowerCAmelCase ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) _lowerCAmelCase = _lowerCAmelCase = _lowerCAmelCase = numbers[0] for i in range(1 , len(lowerCAmelCase ) ): # update the maximum and minimum subarray products _lowerCAmelCase = numbers[i] if number < 0: _lowerCAmelCase , _lowerCAmelCase = min_till_now, max_till_now _lowerCAmelCase = max(lowerCAmelCase , max_till_now * number ) _lowerCAmelCase = min(lowerCAmelCase , min_till_now * number ) # update the maximum product found till now _lowerCAmelCase = max(lowerCAmelCase , lowerCAmelCase ) return max_prod
220
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class UpperCAmelCase ( unittest.TestCase ): def lowercase__ ( self : int ) -> Union[str, Any]: _lowerCAmelCase = inspect.getfile(accelerate.test_utils ) _lowerCAmelCase = 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 _lowerCAmelCase = test_metrics @require_cpu def lowercase__ ( self : Optional[Any] ) -> Optional[Any]: debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def lowercase__ ( self : Tuple ) -> Tuple: debug_launcher(self.test_metrics.main ) @require_single_gpu def lowercase__ ( self : Union[str, Any] ) -> str: self.test_metrics.main() @require_multi_gpu def lowercase__ ( self : str ) -> List[str]: print(f"Found {torch.cuda.device_count()} devices." ) _lowerCAmelCase = ["""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() )
220
1
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() lowerCamelCase : Optional[int] = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( lowercase : Dict , lowercase : List[str] , lowercase : List[Any] ): '''simple docstring''' lowerCamelCase_ = UniSpeechSatForSequenceClassification.from_pretrained(lowercase , config=lowercase ) lowerCamelCase_ = downstream_dict['projector.weight'] lowerCamelCase_ = downstream_dict['projector.bias'] lowerCamelCase_ = downstream_dict['model.post_net.linear.weight'] lowerCamelCase_ = downstream_dict['model.post_net.linear.bias'] return model def _SCREAMING_SNAKE_CASE ( lowercase : Any , lowercase : List[Any] , lowercase : Optional[int] ): '''simple docstring''' lowerCamelCase_ = UniSpeechSatForAudioFrameClassification.from_pretrained(lowercase , config=lowercase ) lowerCamelCase_ = downstream_dict['model.linear.weight'] lowerCamelCase_ = downstream_dict['model.linear.bias'] return model def _SCREAMING_SNAKE_CASE ( lowercase : Dict , lowercase : List[str] , lowercase : Optional[Any] ): '''simple docstring''' lowerCamelCase_ = UniSpeechSatForXVector.from_pretrained(lowercase , config=lowercase ) lowerCamelCase_ = downstream_dict['connector.weight'] lowerCamelCase_ = downstream_dict['connector.bias'] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): lowerCamelCase_ = downstream_dict[ f"""model.framelevel_feature_extractor.module.{i}.kernel.weight""" ] lowerCamelCase_ = downstream_dict[f"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""] lowerCamelCase_ = downstream_dict['model.utterancelevel_feature_extractor.linear1.weight'] lowerCamelCase_ = downstream_dict['model.utterancelevel_feature_extractor.linear1.bias'] lowerCamelCase_ = downstream_dict['model.utterancelevel_feature_extractor.linear2.weight'] lowerCamelCase_ = downstream_dict['model.utterancelevel_feature_extractor.linear2.bias'] lowerCamelCase_ = downstream_dict['objective.W'] return model @torch.no_grad() def _SCREAMING_SNAKE_CASE ( lowercase : Optional[Any] , lowercase : Tuple , lowercase : List[Any] , lowercase : Optional[int] ): '''simple docstring''' lowerCamelCase_ = torch.load(lowercase , map_location='cpu' ) lowerCamelCase_ = checkpoint['Downstream'] lowerCamelCase_ = UniSpeechSatConfig.from_pretrained(lowercase ) lowerCamelCase_ = WavaVecaFeatureExtractor.from_pretrained( lowercase , return_attention_mask=lowercase , do_normalize=lowercase ) lowerCamelCase_ = hf_config.architectures[0] if arch.endswith('ForSequenceClassification' ): lowerCamelCase_ = convert_classification(lowercase , lowercase , lowercase ) elif arch.endswith('ForAudioFrameClassification' ): lowerCamelCase_ = convert_diarization(lowercase , lowercase , lowercase ) elif arch.endswith('ForXVector' ): lowerCamelCase_ = convert_xvector(lowercase , lowercase , lowercase ) else: raise NotImplementedError(f"""S3PRL weights conversion is not supported for {arch}""" ) if hf_config.use_weighted_layer_sum: lowerCamelCase_ = checkpoint['Featurizer']['weights'] hf_feature_extractor.save_pretrained(lowercase ) hf_model.save_pretrained(lowercase ) if __name__ == "__main__": lowerCamelCase : Tuple = argparse.ArgumentParser() parser.add_argument( "--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model." ) parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.") parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.") lowerCamelCase : Union[str, Any] = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
204
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Union[str, Any] = { "configuration_convbert": ["CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvBertConfig", "ConvBertOnnxConfig"], "tokenization_convbert": ["ConvBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = ["ConvBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ "CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "ConvBertForMaskedLM", "ConvBertForMultipleChoice", "ConvBertForQuestionAnswering", "ConvBertForSequenceClassification", "ConvBertForTokenClassification", "ConvBertLayer", "ConvBertModel", "ConvBertPreTrainedModel", "load_tf_weights_in_convbert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Tuple = [ "TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFConvBertForMaskedLM", "TFConvBertForMultipleChoice", "TFConvBertForQuestionAnswering", "TFConvBertForSequenceClassification", "TFConvBertForTokenClassification", "TFConvBertLayer", "TFConvBertModel", "TFConvBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
204
1
"""simple docstring""" from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class __magic_name__ : def __init__( self : Optional[Any] , snake_case__ : Optional[Any] , ): '''simple docstring''' lowercase :Tuple = parent lowercase :List[Any] = 1_3 lowercase :List[str] = 7 lowercase :Dict = 3_0 lowercase :Dict = self.seq_length + self.mem_len lowercase :int = 1_5 lowercase :Any = True lowercase :List[str] = True lowercase :Tuple = 9_9 lowercase :Union[str, Any] = [1_0, 5_0, 8_0] lowercase :Any = 3_2 lowercase :Optional[Any] = 3_2 lowercase :List[Any] = 4 lowercase :Optional[int] = 8 lowercase :Union[str, Any] = 1_2_8 lowercase :Dict = 2 lowercase :Optional[int] = 2 lowercase :Any = None lowercase :Tuple = 1 lowercase :int = 0 lowercase :Optional[Any] = 3 lowercase :Dict = self.vocab_size - 1 lowercase :Dict = 0.01 def __snake_case ( self : Dict ): '''simple docstring''' lowercase :Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase :Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase :List[Any] = None if self.use_labels: lowercase :Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase :Optional[int] = TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def __snake_case ( self : Union[str, Any] ): '''simple docstring''' random.seed(self.seed ) tf.random.set_seed(self.seed ) def __snake_case ( self : int , snake_case__ : Optional[int] , snake_case__ : Tuple , snake_case__ : Optional[Any] , snake_case__ : Optional[Any] ): '''simple docstring''' lowercase :Optional[Any] = TFTransfoXLModel(lowercase_ ) lowercase , lowercase :int = model(lowercase_ ).to_tuple() lowercase :int = {'''input_ids''': input_ids_a, '''mems''': mems_a} lowercase , lowercase :Any = model(lowercase_ ).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def __snake_case ( self : Dict , snake_case__ : str , snake_case__ : str , snake_case__ : Dict , snake_case__ : List[Any] ): '''simple docstring''' lowercase :str = TFTransfoXLLMHeadModel(lowercase_ ) lowercase , lowercase :Union[str, Any] = model(lowercase_ ).to_tuple() lowercase :str = {'''input_ids''': input_ids_a, '''labels''': lm_labels} lowercase , lowercase :Tuple = model(lowercase_ ).to_tuple() lowercase , lowercase :Union[str, Any] = model([input_ids_a, mems_a] ).to_tuple() lowercase :Optional[int] = {'''input_ids''': input_ids_a, '''mems''': mems_a, '''labels''': lm_labels} lowercase , lowercase :Tuple = model(lowercase_ ).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def __snake_case ( self : Optional[Any] , snake_case__ : List[Any] , snake_case__ : List[Any] , snake_case__ : Optional[Any] , snake_case__ : Dict ): '''simple docstring''' lowercase :List[str] = TFTransfoXLForSequenceClassification(lowercase_ ) lowercase :Dict = model(lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __snake_case ( self : Dict ): '''simple docstring''' lowercase :List[str] = self.prepare_config_and_inputs() ((lowercase) , (lowercase) , (lowercase) , (lowercase)) :str = config_and_inputs lowercase :Any = {'''input_ids''': input_ids_a} return config, inputs_dict @require_tf class __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): __A : Union[str, Any] = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) __A : Optional[Any] = () if is_tf_available() else () __A : Dict = ( { "feature-extraction": TFTransfoXLModel, "text-classification": TFTransfoXLForSequenceClassification, "text-generation": TFTransfoXLLMHeadModel, "zero-shot": TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented __A : Dict = False __A : Dict = False __A : Any = False __A : Dict = False def __snake_case ( self : List[Any] , snake_case__ : Dict , snake_case__ : Tuple , snake_case__ : Dict , snake_case__ : Any , snake_case__ : List[str] ): '''simple docstring''' if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def __snake_case ( self : Optional[Any] ): '''simple docstring''' lowercase :List[str] = TFTransfoXLModelTester(self ) lowercase :Union[str, Any] = ConfigTester(self , config_class=lowercase_ , d_embed=3_7 ) def __snake_case ( self : Dict ): '''simple docstring''' self.config_tester.run_common_tests() def __snake_case ( self : Union[str, Any] ): '''simple docstring''' self.model_tester.set_seed() lowercase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*lowercase_ ) def __snake_case ( self : Optional[Any] ): '''simple docstring''' self.model_tester.set_seed() lowercase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*lowercase_ ) def __snake_case ( self : List[str] ): '''simple docstring''' lowercase :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*lowercase_ ) def __snake_case ( self : Dict ): '''simple docstring''' lowercase , lowercase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() lowercase :int = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: lowercase :Tuple = model_class(lowercase_ ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: lowercase :List[Any] = model.get_output_embeddings() assert isinstance(lowercase_ , tf.keras.layers.Layer ) lowercase :int = model.get_bias() assert name is None else: lowercase :Dict = model.get_output_embeddings() assert x is None lowercase :List[Any] = model.get_bias() assert name is None def __snake_case ( self : Optional[int] ): '''simple docstring''' pass @slow def __snake_case ( self : List[str] ): '''simple docstring''' for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase :Union[str, Any] = TFTransfoXLModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) @unittest.skip(reason='''This model doesn\'t play well with fit() due to not returning a single loss.''' ) def __snake_case ( self : Union[str, Any] ): '''simple docstring''' pass @require_tf class __magic_name__ ( unittest.TestCase ): @unittest.skip('''Skip test until #12651 is resolved.''' ) @slow def __snake_case ( self : Optional[Any] ): '''simple docstring''' lowercase :str = TFTransfoXLLMHeadModel.from_pretrained('''transfo-xl-wt103''' ) # fmt: off lowercase :Dict = tf.convert_to_tensor([[3_3,1_2_9_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_2,1_7_0_6,1_7,2_0_0_9_8,5,3_2_1_5,2_1,3_7,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,6_2_2_4,8_3_1,1_6_0_0_2,2,8,6_0_3,7_8_9_6_7,2_9_5_4_6,2_3,8_0_3,2_0,2_5,4_1_6,5,8,2_3_2,4,2_7_7,6,1_8_5_5,4_6_0_1,3,2_9_5_4_6,5_4,8,3_6_0_9,5,5_7_2_1_1,4_9,4,1,2_7_7,1_8,8,1_7_5_5,1_5_6_9_1,3,3_4_1,2_5,4_1_6,6_9_3,4_2_5_7_3,7_1,1_7,4_0_1,9_4,3_1,1_7_9_1_9,2,2_9_5_4_6,7_8_7_3,1_8,1,4_3_5,2_3,1_1_0_1_1,7_5_5,5,5_1_6_7,3,7_9_8_3,9_8,8_4,2,2_9_5_4_6,3_2_6_7,8,3_6_0_9,4,1,4_8_6_5,1_0_7_5,2,6_0_8_7,7_1,6,3_4_6,8,5_8_5_4,3,2_9_5_4_6,8_2_4,1_4_0_0,1_8_6_8,2,1_9,1_6_0,2,3_1_1,8,5_4_9_6,2,2_0_9_2_0,1_7,2_5,1_5_0_9_7,3,2_4,2_4,0]] , dtype=tf.intaa ) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off lowercase :str = [3_3,1_2_9_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_2,1_7_0_6,1_7,2_0_0_9_8,5,3_2_1_5,2_1,3_7,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,6_2_2_4,8_3_1,1_6_0_0_2,2,8,6_0_3,7_8_9_6_7,2_9_5_4_6,2_3,8_0_3,2_0,2_5,4_1_6,5,8,2_3_2,4,2_7_7,6,1_8_5_5,4_6_0_1,3,2_9_5_4_6,5_4,8,3_6_0_9,5,5_7_2_1_1,4_9,4,1,2_7_7,1_8,8,1_7_5_5,1_5_6_9_1,3,3_4_1,2_5,4_1_6,6_9_3,4_2_5_7_3,7_1,1_7,4_0_1,9_4,3_1,1_7_9_1_9,2,2_9_5_4_6,7_8_7_3,1_8,1,4_3_5,2_3,1_1_0_1_1,7_5_5,5,5_1_6_7,3,7_9_8_3,9_8,8_4,2,2_9_5_4_6,3_2_6_7,8,3_6_0_9,4,1,4_8_6_5,1_0_7_5,2,6_0_8_7,7_1,6,3_4_6,8,5_8_5_4,3,2_9_5_4_6,8_2_4,1_4_0_0,1_8_6_8,2,1_9,1_6_0,2,3_1_1,8,5_4_9_6,2,2_0_9_2_0,1_7,2_5,1_5_0_9_7,3,2_4,2_4,0,3_3,1,1_8_5_7,2,1,1_0_0_9,4,1_1_0_9,1_1_7_3_9,4_7_6_2,3_5_8,5,2_5,2_4_5,2_8,1_1_1_0,3,1_3,1_0_4_1,4,2_4,6_0_3,4_9_0,2,7_1_4_7_7,2_0_0_9_8,1_0_4_4_4_7,2,2_0_9_6_1,1,2_6_0_4,4,1,3_2_9,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> lowercase :Optional[int] = model.generate(lowercase_ , max_length=2_0_0 , do_sample=lowercase_ ) self.assertListEqual(output_ids[0].numpy().tolist() , lowercase_ )
369
"""simple docstring""" # coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # 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. # this script dumps information about the environment import os import sys import transformers UpperCAmelCase = '''3''' print('''Python version:''', sys.version) print('''transformers version:''', transformers.__version__) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) print('''NCCL version:''', torch.cuda.nccl.version()) except ImportError: print('''Torch version:''', None) try: import deepspeed print('''DeepSpeed version:''', deepspeed.__version__) except ImportError: print('''DeepSpeed version:''', None) try: import tensorflow as tf print('''TensorFlow version:''', tf.__version__) print('''TF GPUs available:''', bool(tf.config.list_physical_devices('''GPU'''))) print('''Number of TF GPUs available:''', len(tf.config.list_physical_devices('''GPU'''))) except ImportError: print('''TensorFlow version:''', None)
172
0
"""simple docstring""" from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS lowercase_ = logging.get_logger(__name__) lowercase_ = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, "constant": get_constant_schedule, "constant_w_warmup": get_constant_schedule_with_warmup, } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , _a=None , *_a , **_a ): super().__init__(*_a , **_a ) if config is None: assert isinstance(self.model , _a ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" f''' {self.model.__class__}''' ) __a = self.model.config else: __a = config __a = data_args __a = self.config.tgt_vocab_size if isinstance(self.config , _a ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( f'''The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for''' ''' padding..''' ) if self.args.label_smoothing == 0: __a = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss __a = label_smoothed_nll_loss def __UpperCAmelCase ( self , _a ): if self.optimizer is None: __a = ['''bias''', '''LayerNorm.weight'''] __a = [ { '''params''': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], '''weight_decay''': self.args.weight_decay, }, { '''params''': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], '''weight_decay''': 0.0, }, ] __a = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: __a = Adafactor __a = {'''scale_parameter''': False, '''relative_step''': False} else: __a = AdamW __a = { '''betas''': (self.args.adam_betaa, self.args.adam_betaa), '''eps''': self.args.adam_epsilon, } __a = self.args.learning_rate if self.sharded_ddp: __a = OSS( params=_a , optim=_a , **_a , ) else: __a = optimizer_cls(_a , **_a ) if self.lr_scheduler is None: __a = self._get_lr_scheduler(_a ) else: # ignoring --lr_scheduler logger.warning('''scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.''' ) def __UpperCAmelCase ( self , _a ): __a = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": __a = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": __a = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: __a = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=_a ) return scheduler def __UpperCAmelCase ( self ): if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def __UpperCAmelCase ( self , _a , _a , _a ): if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token __a = model(**_a , use_cache=_a )[0] __a = self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models __a , __a = model(**_a , labels=_a , use_cache=_a )[:2] else: # compute label smoothed loss __a = model(**_a , use_cache=_a )[0] __a = torch.nn.functional.log_softmax(_a , dim=-1 ) __a , __a = self.loss_fn(_a , _a , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def __UpperCAmelCase ( self , _a , _a ): __a = inputs.pop('''labels''' ) __a , __a = self._compute_loss(_a , _a , _a ) return loss def __UpperCAmelCase ( self , _a , _a , _a , _a = None , ): __a = self._prepare_inputs(_a ) __a = { '''max_length''': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, '''num_beams''': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: __a = self.model.generate( inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , **_a , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: __a = self._pad_tensors_to_max_len(_a , gen_kwargs['''max_length'''] ) __a = inputs.pop('''labels''' ) with torch.no_grad(): # compute loss on predict data __a , __a = self._compute_loss(_a , _a , _a ) __a = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) __a = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: __a = self._pad_tensors_to_max_len(_a , gen_kwargs['''max_length'''] ) return (loss, logits, labels) def __UpperCAmelCase ( self , _a , _a ): # If PAD token is not defined at least EOS token has to be defined __a = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( '''Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be''' f''' padded to `max_length`={max_length}''' ) __a = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) __a = tensor return padded_tensor
45
def _lowerCAmelCase (_lowerCAmelCase): UpperCamelCase_ = len(_lowerCAmelCase) UpperCamelCase_ = len(matrix[0]) UpperCamelCase_ = min(_lowerCAmelCase , _lowerCAmelCase) for row in range(_lowerCAmelCase): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , _lowerCAmelCase): UpperCamelCase_ = matrix[col][row] / matrix[row][row] for i in range(_lowerCAmelCase , _lowerCAmelCase): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows UpperCamelCase_ = True for i in range(row + 1 , _lowerCAmelCase): if matrix[i][row] != 0: UpperCamelCase_ , UpperCamelCase_ = matrix[i], matrix[row] UpperCamelCase_ = False break if reduce: rank -= 1 for i in range(_lowerCAmelCase): UpperCamelCase_ = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
128
0
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : List[str] = (DPMSolverSinglestepScheduler,) __snake_case : Union[str, Any] = (("num_inference_steps", 25),) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ,**lowerCamelCase__ : Optional[int] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = { """num_train_timesteps""": 1000, """beta_start""": 0.0001, """beta_end""": 0.02, """beta_schedule""": """linear""", """solver_order""": 2, """prediction_type""": """epsilon""", """thresholding""": False, """sample_max_value""": 1.0, """algorithm_type""": """dpmsolver++""", """solver_type""": """midpoint""", """lambda_min_clipped""": -float("""inf""" ), """variance_type""": None, } config.update(**lowerCamelCase__ ) return config def SCREAMING_SNAKE_CASE__ ( self : Tuple ,lowerCamelCase__ : int=0 ,**lowerCamelCase__ : List[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE = kwargs.pop("""num_inference_steps""" ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.dummy_sample SCREAMING_SNAKE_CASE = 0.1 * sample SCREAMING_SNAKE_CASE = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE = self.get_scheduler_config(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = scheduler_class(**lowerCamelCase__ ) scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = scheduler_class.from_pretrained(lowerCamelCase__ ) new_scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE = dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = sample, sample for t in range(lowerCamelCase__ ,time_step + scheduler.config.solver_order + 1 ): SCREAMING_SNAKE_CASE = scheduler.step(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,**lowerCamelCase__ ).prev_sample SCREAMING_SNAKE_CASE = new_scheduler.step(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,**lowerCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> int: '''simple docstring''' pass def SCREAMING_SNAKE_CASE__ ( self : Tuple ,lowerCamelCase__ : List[Any]=0 ,**lowerCamelCase__ : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE = kwargs.pop("""num_inference_steps""" ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.dummy_sample SCREAMING_SNAKE_CASE = 0.1 * sample SCREAMING_SNAKE_CASE = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE = self.get_scheduler_config() SCREAMING_SNAKE_CASE = scheduler_class(**lowerCamelCase__ ) scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = scheduler_class.from_pretrained(lowerCamelCase__ ) # copy over dummy past residuals new_scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE = dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE = scheduler.step(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,**lowerCamelCase__ ).prev_sample SCREAMING_SNAKE_CASE = new_scheduler.step(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,**lowerCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def SCREAMING_SNAKE_CASE__ ( self : List[Any] ,lowerCamelCase__ : Dict=None ,**lowerCamelCase__ : int ) -> List[str]: '''simple docstring''' if scheduler is None: SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = scheduler_class(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = scheduler_class(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = 10 SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter scheduler.set_timesteps(lowerCamelCase__ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = scheduler.step(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ).prev_sample return sample def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter scheduler.set_timesteps(lowerCamelCase__ ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = scheduler.step(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ).prev_sample SCREAMING_SNAKE_CASE = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_mean.item() - 0.2574 ) < 1e-3 def SCREAMING_SNAKE_CASE__ ( self : int ) -> int: '''simple docstring''' for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) SCREAMING_SNAKE_CASE = self.full_loop(scheduler=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_mean.item() - 0.2791 ) < 1e-3 SCREAMING_SNAKE_CASE = DEISMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE = UniPCMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE = DPMSolverSinglestepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE = self.full_loop(scheduler=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_mean.item() - 0.2791 ) < 1e-3 def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> int: '''simple docstring''' self.check_over_configs(thresholding=lowerCamelCase__ ) for order in [1, 2, 3]: for solver_type in ["midpoint", "heun"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=lowerCamelCase__ ,prediction_type=lowerCamelCase__ ,sample_max_value=lowerCamelCase__ ,algorithm_type="""dpmsolver++""" ,solver_order=lowerCamelCase__ ,solver_type=lowerCamelCase__ ,) def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> str: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Any: '''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=lowerCamelCase__ ,solver_type=lowerCamelCase__ ,prediction_type=lowerCamelCase__ ,algorithm_type=lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = self.full_loop( solver_order=lowerCamelCase__ ,solver_type=lowerCamelCase__ ,prediction_type=lowerCamelCase__ ,algorithm_type=lowerCamelCase__ ,) assert not torch.isnan(lowerCamelCase__ ).any(), "Samples have nan numbers" def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' self.check_over_configs(lower_order_final=lowerCamelCase__ ) self.check_over_configs(lower_order_final=lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> int: '''simple docstring''' self.check_over_configs(lambda_min_clipped=-float("""inf""" ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> str: '''simple docstring''' self.check_over_configs(variance_type=lowerCamelCase__ ) self.check_over_configs(variance_type="""learned_range""" ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=lowerCamelCase__ ,time_step=0 ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.full_loop() SCREAMING_SNAKE_CASE = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_mean.item() - 0.2791 ) < 1e-3 def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = self.full_loop(use_karras_sigmas=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_mean.item() - 0.2248 ) < 1e-3 def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.full_loop(prediction_type="""v_prediction""" ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_mean.item() - 0.1453 ) < 1e-3 def SCREAMING_SNAKE_CASE__ ( self : Any ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = self.full_loop(prediction_type="""v_prediction""" ,use_karras_sigmas=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_mean.item() - 0.0649 ) < 1e-3 def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config(thresholding=lowerCamelCase__ ,dynamic_thresholding_ratio=0 ) SCREAMING_SNAKE_CASE = scheduler_class(**lowerCamelCase__ ) SCREAMING_SNAKE_CASE = 10 SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter.half() scheduler.set_timesteps(lowerCamelCase__ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = scheduler.step(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ).prev_sample assert sample.dtype == torch.floataa
193
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE_ = { """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""MvpTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""MvpTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """MVP_PRETRAINED_MODEL_ARCHIVE_LIST""", """MvpForCausalLM""", """MvpForConditionalGeneration""", """MvpForQuestionAnswering""", """MvpForSequenceClassification""", """MvpModel""", """MvpPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
193
1
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__ = logging.get_logger(__name__) lowerCamelCase__ = { """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 ( lowerCamelCase__ ): __lowerCamelCase : List[Any] ='perceiver' def __init__( self : Dict , __lowercase : List[Any]=256 , __lowercase : List[Any]=1280 , __lowercase : Tuple=768 , __lowercase : str=1 , __lowercase : List[str]=26 , __lowercase : Any=8 , __lowercase : Dict=8 , __lowercase : Optional[Any]=None , __lowercase : str=None , __lowercase : Optional[int]="kv" , __lowercase : Dict=1 , __lowercase : Optional[int]=1 , __lowercase : List[str]="gelu" , __lowercase : List[str]=0.1 , __lowercase : Union[str, Any]=0.02 , __lowercase : Tuple=1E-12 , __lowercase : Optional[Any]=True , __lowercase : List[str]=262 , __lowercase : List[Any]=2048 , __lowercase : str=56 , __lowercase : str=[368, 496] , __lowercase : Dict=16 , __lowercase : Union[str, Any]=1920 , __lowercase : Tuple=16 , __lowercase : List[str]=[1, 16, 224, 224] , **__lowercase : str , ): '''simple docstring''' super().__init__(**__lowercase ) __a = num_latents __a = d_latents __a = d_model __a = num_blocks __a = num_self_attends_per_block __a = num_self_attention_heads __a = num_cross_attention_heads __a = qk_channels __a = v_channels __a = cross_attention_shape_for_attention __a = self_attention_widening_factor __a = cross_attention_widening_factor __a = hidden_act __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = use_query_residual # masked language modeling attributes __a = vocab_size __a = max_position_embeddings # image classification attributes __a = image_size # flow attributes __a = train_size # multimodal autoencoding attributes __a = num_frames __a = audio_samples_per_frame __a = samples_per_patch __a = output_shape class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): @property def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' if self.task == "multiple-choice": __a = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __a = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""inputs""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] ) @property def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return 1E-4 def UpperCamelCase_ ( self : Any , __lowercase : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __lowercase : int = -1 , __lowercase : int = -1 , __lowercase : int = -1 , __lowercase : bool = False , __lowercase : Optional[TensorType] = None , __lowercase : int = 3 , __lowercase : int = 40 , __lowercase : int = 40 , ): '''simple docstring''' # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__lowercase , __lowercase ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __a = compute_effective_axis_dimension( __lowercase , 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 __a = preprocessor.num_special_tokens_to_add(__lowercase ) __a = compute_effective_axis_dimension( __lowercase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__lowercase ) # Generate dummy inputs according to compute batch and sequence __a = [""" """.join(["""a"""] ) * seq_length] * batch_size __a = dict(preprocessor(__lowercase , return_tensors=__lowercase ) ) __a = inputs.pop("""input_ids""" ) return inputs elif isinstance(__lowercase , __lowercase ) 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 __a = compute_effective_axis_dimension(__lowercase , fixed_dimension=OnnxConfig.default_fixed_batch ) __a = self._generate_dummy_images(__lowercase , __lowercase , __lowercase , __lowercase ) __a = dict(preprocessor(images=__lowercase , return_tensors=__lowercase ) ) __a = inputs.pop("""pixel_values""" ) return inputs else: raise ValueError( """Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.""" )
302
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : List[Any] ='autoformer' __lowerCamelCase : str ={ 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : List[Any] , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : str = "student_t" , __lowercase : str = "nll" , __lowercase : int = 1 , __lowercase : List[int] = [1, 2, 3, 4, 5, 6, 7] , __lowercase : bool = True , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : int = 0 , __lowercase : Optional[List[int]] = None , __lowercase : Optional[List[int]] = None , __lowercase : int = 64 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 2 , __lowercase : int = 32 , __lowercase : int = 32 , __lowercase : str = "gelu" , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : float = 0.1 , __lowercase : int = 100 , __lowercase : float = 0.02 , __lowercase : bool = True , __lowercase : List[Any]=True , __lowercase : int = 10 , __lowercase : int = 25 , __lowercase : int = 3 , **__lowercase : Optional[int] , ): '''simple docstring''' # time series specific configuration __a = prediction_length __a = context_length if context_length is not None else prediction_length __a = distribution_output __a = loss __a = input_size __a = num_time_features __a = lags_sequence __a = scaling __a = num_dynamic_real_features __a = num_static_real_features __a = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) __a = cardinality else: __a = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(__lowercase ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) __a = embedding_dimension else: __a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __a = num_parallel_samples # Transformer architecture configuration __a = input_size * len(self.lags_sequence ) + self._number_of_features __a = d_model __a = encoder_attention_heads __a = decoder_attention_heads __a = encoder_ffn_dim __a = decoder_ffn_dim __a = encoder_layers __a = decoder_layers __a = dropout __a = attention_dropout __a = activation_dropout __a = encoder_layerdrop __a = decoder_layerdrop __a = activation_function __a = init_std __a = use_cache # Autoformer __a = label_length __a = moving_average __a = autocorrelation_factor super().__init__(is_encoder_decoder=__lowercase , **__lowercase ) @property def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
302
1
'''simple docstring''' def lowerCamelCase__ ( A : int , A : int ): '''simple docstring''' return int(input_a == input_a == 0 ) def lowerCamelCase__ ( ): '''simple docstring''' print('''Truth Table of NOR Gate:''' ) print('''| Input 1 | Input 2 | Output |''' ) print(f"""| 0 | 0 | {nor_gate(0 , 0 )} |""" ) print(f"""| 0 | 1 | {nor_gate(0 , 1 )} |""" ) print(f"""| 1 | 0 | {nor_gate(1 , 0 )} |""" ) print(f"""| 1 | 1 | {nor_gate(1 , 1 )} |""" ) if __name__ == "__main__": import doctest doctest.testmod() main()
91
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase__( lowerCAmelCase ): __magic_name__ : List[Any] = ["image_processor", "tokenizer"] __magic_name__ : Tuple = "ViTImageProcessor" __magic_name__ : int = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : List[str] , lowerCAmelCase : Tuple=None , lowerCAmelCase : List[str]=None , **lowerCAmelCase : Optional[int] )-> Tuple: """simple docstring""" 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.''' , lowerCAmelCase , ) 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__(lowerCAmelCase , lowerCAmelCase ) def __call__( self : int , lowerCAmelCase : Dict=None , lowerCAmelCase : Optional[int]=None , lowerCAmelCase : Union[str, Any]=None , lowerCAmelCase : int=None , **lowerCAmelCase : Tuple )-> Optional[int]: """simple docstring""" if text is None and visual_prompt is None and images is None: raise ValueError('''You have to specify either text, visual prompt or images.''' ) if text is not None and visual_prompt is not None: raise ValueError('''You have to specify exactly one type of prompt. Either text or visual prompt.''' ) if text is not None: UpperCAmelCase = self.tokenizer(lowerCAmelCase , return_tensors=lowerCAmelCase , **lowerCAmelCase ) if visual_prompt is not None: UpperCAmelCase = self.image_processor(lowerCAmelCase , return_tensors=lowerCAmelCase , **lowerCAmelCase ) if images is not None: UpperCAmelCase = self.image_processor(lowerCAmelCase , return_tensors=lowerCAmelCase , **lowerCAmelCase ) if visual_prompt is not None and images is not None: UpperCAmelCase = { '''pixel_values''': image_features.pixel_values, '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: UpperCAmelCase = { '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**lowerCAmelCase ) , tensor_type=lowerCAmelCase ) def a__( self : Optional[int] , *lowerCAmelCase : List[str] , **lowerCAmelCase : Dict )-> Tuple: """simple docstring""" return self.tokenizer.batch_decode(*lowerCAmelCase , **lowerCAmelCase ) def a__( self : List[Any] , *lowerCAmelCase : str , **lowerCAmelCase : List[Any] )-> Optional[Any]: """simple docstring""" return self.tokenizer.decode(*lowerCAmelCase , **lowerCAmelCase ) @property def a__( self : Any )-> Optional[int]: """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 a__( self : str )-> List[Any]: """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , lowerCAmelCase , ) return self.image_processor
91
1
"""simple docstring""" def UpperCamelCase ( UpperCAmelCase ) ->int: """simple docstring""" if not numbers: return 0 if not isinstance(UpperCAmelCase , (list, tuple) ) or not all( isinstance(UpperCAmelCase , UpperCAmelCase ) for number in numbers ): raise ValueError("numbers must be an iterable of integers" ) a_ = a_ = a_ = numbers[0] for i in range(1 , len(UpperCAmelCase ) ): # update the maximum and minimum subarray products a_ = numbers[i] if number < 0: a_ , a_ = min_till_now, max_till_now a_ = max(UpperCAmelCase , max_till_now * number ) a_ = min(UpperCAmelCase , min_till_now * number ) # update the maximum product found till now a_ = max(UpperCAmelCase , UpperCAmelCase ) return max_prod
243
"""simple docstring""" def UpperCamelCase ( UpperCAmelCase ) ->list[int]: """simple docstring""" if length <= 0 or not isinstance(UpperCAmelCase , UpperCAmelCase ): raise ValueError("Length must be a positive integer." ) return [n * (2 * n - 1) for n in range(UpperCAmelCase )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
243
1
'''simple docstring''' import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) __A ='\\n Text data.\n Second line of data.' __A ='file' @pytest.fixture(scope="""session""" ) def _UpperCamelCase ( UpperCamelCase__ ): UpperCAmelCase__ : str = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") UpperCAmelCase__ : Tuple = bytes(lowerCamelCase__ , """utf-8""" ) with zstd.open(lowerCamelCase__ , """wb""" ) as f: f.write(lowerCamelCase__ ) return path @pytest.fixture def _UpperCamelCase ( UpperCamelCase__ ): with open(os.path.join(tmpfs.local_root_dir , lowerCamelCase__ ) , """w""" ) as f: f.write(lowerCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Dict = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} UpperCAmelCase__ : Optional[int] = input_paths[compression_format] UpperCAmelCase__ : str = tmp_path / """cache""" UpperCAmelCase__ : Optional[Any] = DownloadConfig(cache_dir=lowerCamelCase__ , extract_compressed_file=lowerCamelCase__ ) UpperCAmelCase__ : Any = cached_path(lowerCamelCase__ , download_config=lowerCamelCase__ ) with open(lowerCamelCase__ ) as f: UpperCAmelCase__ : Any = f.read() with open(lowerCamelCase__ ) as f: UpperCAmelCase__ : List[str] = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Union[str, Any] = """custom_cache""" UpperCAmelCase__ : Dict = """custom_extracted_dir""" UpperCAmelCase__ : List[str] = tmp_path / """custom_extracted_path""" if default_extracted: UpperCAmelCase__ : int = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , lowerCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(lowerCamelCase__ ) ) UpperCAmelCase__ : Any = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) UpperCAmelCase__ : Dict = xz_file UpperCAmelCase__ : Any = ( DownloadConfig(extract_compressed_file=lowerCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=lowerCamelCase__ ) ) UpperCAmelCase__ : int = cached_path(lowerCamelCase__ , download_config=lowerCamelCase__ ) assert Path(lowerCamelCase__ ).parent.parts[-2:] == expected def _UpperCamelCase ( UpperCamelCase__ ): # absolute path UpperCAmelCase__ : str = str(Path(lowerCamelCase__ ).resolve() ) assert cached_path(lowerCamelCase__ ) == text_file # relative path UpperCAmelCase__ : Union[str, Any] = str(Path(lowerCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(lowerCamelCase__ ) == text_file def _UpperCamelCase ( UpperCamelCase__ ): # absolute path UpperCAmelCase__ : Tuple = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(lowerCamelCase__ ): cached_path(lowerCamelCase__ ) # relative path UpperCAmelCase__ : Optional[int] = """./__missing_file__.txt""" with pytest.raises(lowerCamelCase__ ): cached_path(lowerCamelCase__ ) def _UpperCamelCase ( UpperCamelCase__ ): UpperCAmelCase__ : Tuple = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(lowerCamelCase__ ) as f: UpperCAmelCase__ : Dict = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , lowerCamelCase__ ) def _UpperCamelCase ( ): with pytest.raises(lowerCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , lowerCamelCase__ ) def _UpperCamelCase ( UpperCamelCase__ ): UpperCAmelCase__ : int = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(lowerCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=lowerCamelCase__ ) with pytest.raises(lowerCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , lowerCamelCase__ ) def _UpperCamelCase ( UpperCamelCase__ ): UpperCAmelCase__ : Optional[int] = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(lowerCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=lowerCamelCase__ ) with pytest.raises(lowerCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , lowerCamelCase__ ) def _UpperCamelCase ( UpperCamelCase__ ): UpperCAmelCase__ : Any = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(lowerCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=lowerCamelCase__ ) with pytest.raises(lowerCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
353
'''simple docstring''' import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __A =logging.getLogger(__name__) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = False , ): UpperCAmelCase__ : str = bnb_quantization_config.load_in_abit UpperCAmelCase__ : str = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( """You have a version of `bitsandbytes` that is not compatible with 8bit quantization,""" """ make sure you have the latest version of `bitsandbytes` installed.""" ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( """You have a version of `bitsandbytes` that is not compatible with 4bit quantization,""" """make sure you have the latest version of `bitsandbytes` installed.""" ) UpperCAmelCase__ : List[Any] = [] # custom device map if isinstance(UpperCamelCase__ , UpperCamelCase__ ) and len(device_map.keys() ) > 1: UpperCAmelCase__ : Dict = [key for key, value in device_map.items() if value in ["""disk""", """cpu"""]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: UpperCAmelCase__ : Any = get_keys_to_not_convert(UpperCamelCase__ ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(UpperCamelCase__ ) UpperCAmelCase__ : Tuple = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: UpperCAmelCase__ : List[Any] = [] UpperCAmelCase__ : int = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(UpperCamelCase__ ) # compatibility with peft UpperCAmelCase__ : Optional[int] = load_in_abit UpperCAmelCase__ : List[Any] = load_in_abit UpperCAmelCase__ : Dict = get_parameter_device(UpperCamelCase__ ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( """It is not recommended to quantize a loaded model. """ """The model should be instantiated under the `init_empty_weights` context manager.""" ) UpperCAmelCase__ : Optional[int] = replace_with_bnb_layers(UpperCamelCase__ , UpperCamelCase__ , modules_to_not_convert=UpperCamelCase__ ) # convert param to the right dtype UpperCAmelCase__ : str = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: UpperCAmelCase__ : List[str] = name.replace(""".weight""" , """""" ).replace(""".bias""" , """""" ) UpperCAmelCase__ : int = getattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(UpperCamelCase__ ): param.to(UpperCamelCase__ ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info( f'''The model device type is {model_device.type}. However, cuda is needed for quantization.''' """We move the model to cuda.""" ) return model elif weights_location is None: raise RuntimeError( f'''`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ''' ) else: with init_empty_weights(): UpperCAmelCase__ : Tuple = replace_with_bnb_layers( UpperCamelCase__ , UpperCamelCase__ , modules_to_not_convert=UpperCamelCase__ ) UpperCAmelCase__ : Any = get_quantized_model_device_map( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , max_memory=UpperCamelCase__ , no_split_module_classes=UpperCamelCase__ , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): UpperCAmelCase__ : Dict = True UpperCAmelCase__ : Any = any(x in list(device_map.values() ) for x in ["""cpu""", """disk"""] ) load_checkpoint_in_model( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , dtype=bnb_quantization_config.torch_dtype , offload_folder=UpperCamelCase__ , offload_state_dict=UpperCamelCase__ , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(UpperCamelCase__ , device_map=UpperCamelCase__ , offload_dir=UpperCamelCase__ ) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None ): if device_map is None: if torch.cuda.is_available(): UpperCAmelCase__ : Any = {"""""": torch.cuda.current_device()} else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`.""" ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( """If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """ """'sequential'.""" ) UpperCAmelCase__ : List[Any] = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) UpperCAmelCase__ : Optional[Any] = {} UpperCAmelCase__ : Union[str, Any] = special_dtypes UpperCAmelCase__ : Optional[int] = no_split_module_classes UpperCAmelCase__ : Optional[Any] = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": UpperCAmelCase__ : Optional[int] = get_balanced_memory( UpperCamelCase__ , low_zero=(device_map == """balanced_low_0""") , max_memory=UpperCamelCase__ , **UpperCamelCase__ , ) UpperCAmelCase__ : str = max_memory UpperCAmelCase__ : Any = infer_auto_device_map(UpperCamelCase__ , **UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # check if don't have any quantized module on the cpu UpperCAmelCase__ : Optional[int] = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules UpperCAmelCase__ : List[Any] = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( """ Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. """ ) else: logger.info( """Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit""" ) del device_map_without_some_modules return device_map def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=None ): if modules_to_not_convert is None: UpperCAmelCase__ : Any = [] UpperCAmelCase__ , UpperCAmelCase__ : List[str] = _replace_with_bnb_layers( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=None , ): UpperCAmelCase__ : List[str] = False for name, module in model.named_children(): if current_key_name is None: UpperCAmelCase__ : Dict = [] current_key_name.append(UpperCamelCase__ ) if isinstance(UpperCamelCase__ , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` UpperCAmelCase__ : List[str] = """.""".join(UpperCamelCase__ ) UpperCAmelCase__ : List[Any] = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: UpperCAmelCase__ : Union[str, Any] = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: UpperCAmelCase__ : Optional[Any] = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=UpperCamelCase__ , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: UpperCAmelCase__ : Dict = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("""load_in_8bit and load_in_4bit can't be both False""" ) UpperCAmelCase__ : int = module.weight.data if module.bias is not None: UpperCAmelCase__ : Dict = module.bias.data bnb_module.requires_grad_(UpperCamelCase__ ) setattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase__ : Union[str, Any] = True if len(list(module.children() ) ) > 0: UpperCAmelCase__ , UpperCAmelCase__ : str = _replace_with_bnb_layers( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase__ : Any = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _UpperCamelCase ( UpperCamelCase__ ): # Create a copy of the model with init_empty_weights(): UpperCAmelCase__ : Optional[int] = deepcopy(UpperCamelCase__ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` UpperCAmelCase__ : Any = find_tied_parameters(UpperCamelCase__ ) # For compatibility with Accelerate < 0.18 if isinstance(UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Optional[Any] = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: UpperCAmelCase__ : str = sum(UpperCamelCase__ , [] ) UpperCAmelCase__ : int = len(UpperCamelCase__ ) > 0 # Check if it is a base model UpperCAmelCase__ : int = False if hasattr(UpperCamelCase__ , """base_model_prefix""" ): UpperCAmelCase__ : Tuple = not hasattr(UpperCamelCase__ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head UpperCAmelCase__ : Optional[Any] = list(model.named_children() ) UpperCAmelCase__ : int = [list_modules[-1][0]] # add last module together with tied weights UpperCAmelCase__ : Optional[int] = set(UpperCamelCase__ ) - set(UpperCamelCase__ ) UpperCAmelCase__ : Any = list(set(UpperCamelCase__ ) ) + list(UpperCamelCase__ ) # remove ".weight" from the keys UpperCAmelCase__ : int = [""".weight""", """.bias"""] UpperCAmelCase__ : str = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: UpperCAmelCase__ : List[Any] = name.replace(UpperCamelCase__ , """""" ) filtered_module_names.append(UpperCamelCase__ ) return filtered_module_names def _UpperCamelCase ( UpperCamelCase__ ): for m in model.modules(): if isinstance(UpperCamelCase__ , bnb.nn.Linearabit ): return True return False def _UpperCamelCase ( UpperCamelCase__ ): return next(parameter.parameters() ).device def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(UpperCamelCase__ , UpperCamelCase__ , 0 , dtype=UpperCamelCase__ , value=UpperCamelCase__ ) UpperCAmelCase__ : Any = param_name UpperCAmelCase__ : Dict = model if "." in tensor_name: UpperCAmelCase__ : List[Any] = tensor_name.split(""".""" ) for split in splits[:-1]: UpperCAmelCase__ : Optional[Any] = getattr(UpperCamelCase__ , UpperCamelCase__ ) if new_module is None: raise ValueError(f'''{module} has no attribute {split}.''' ) UpperCAmelCase__ : List[str] = new_module UpperCAmelCase__ : Dict = splits[-1] # offload weights UpperCAmelCase__ : Any = False offload_weight(module._parameters[tensor_name] , UpperCamelCase__ , UpperCamelCase__ , index=UpperCamelCase__ ) if hasattr(module._parameters[tensor_name] , """SCB""" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("""weight""" , """SCB""" ) , UpperCamelCase__ , index=UpperCamelCase__ , ) else: offload_weight(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , index=UpperCamelCase__ ) offload_weight(UpperCamelCase__ , param_name.replace("""weight""" , """SCB""" ) , UpperCamelCase__ , index=UpperCamelCase__ ) set_module_tensor_to_device(UpperCamelCase__ , UpperCamelCase__ , """meta""" , dtype=UpperCamelCase__ , value=torch.empty(*param.size() ) )
283
0
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib lowerCamelCase__ = get_logger() lowerCamelCase__ = None class A__ ( TensorFormatter[Mapping, 'jax.Array', Mapping] ): def __init__( self : List[str] , a : Tuple=None , a : str=None , **a : int ): '''simple docstring''' super().__init__(features=a ) import jax from jaxlib.xla_client import Device if isinstance(a , a ): raise ValueError( f'''Expected {device} to be a `str` not {type(a )}, as `jaxlib.xla_extension.Device` ''' 'is not serializable neither with `pickle` nor with `dill`. Instead you can surround ' 'the device with `str()` to get its string identifier that will be internally mapped ' 'to the actual `jaxlib.xla_extension.Device`.' ) lowerCAmelCase__ : Optional[int] = device if isinstance(a , a ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: lowerCAmelCase__ : Union[str, Any] = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( f'''Device with string identifier {self.device} not listed among the available ''' f'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ''' f'''device: {str(jax.devices()[0] )}.''' ) lowerCAmelCase__ : Optional[Any] = str(jax.devices()[0] ) lowerCAmelCase__ : Tuple = jnp_array_kwargs @staticmethod def _lowerCamelCase ( ): '''simple docstring''' import jax return {str(a ): device for device in jax.devices()} def _lowerCamelCase ( self : Tuple , a : int ): '''simple docstring''' import jax import jax.numpy as jnp if isinstance(a , a ) and column: if all( isinstance(a , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(a , axis=0 ) return column def _lowerCamelCase ( self : int , a : Tuple ): '''simple docstring''' import jax import jax.numpy as jnp if isinstance(a , (str, bytes, type(a )) ): return value elif isinstance(a , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() lowerCAmelCase__ : int = {} if isinstance(a , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: lowerCAmelCase__ : Dict = {'dtype': jnp.intaa} else: lowerCAmelCase__ : Any = {'dtype': jnp.intaa} elif isinstance(a , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): lowerCAmelCase__ : int = {'dtype': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(a , PIL.Image.Image ): lowerCAmelCase__ : Tuple = np.asarray(a ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: lowerCAmelCase__ : Union[str, Any] = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(a , **{**default_dtype, **self.jnp_array_kwargs} ) def _lowerCamelCase ( self : Tuple , a : str ): '''simple docstring''' import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(a , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(a , '__array__' ) and not isinstance(a , jax.Array ): lowerCAmelCase__ : List[str] = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(a , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(a ) for substruct in data_struct] ) elif isinstance(a , (list, tuple) ): return self._consolidate([self.recursive_tensorize(a ) for substruct in data_struct] ) return self._tensorize(a ) def _lowerCamelCase ( self : int , a : dict ): '''simple docstring''' return map_nested(self._recursive_tensorize , a , map_list=a ) def _lowerCamelCase ( self : Dict , a : pa.Table ): '''simple docstring''' lowerCAmelCase__ : Dict = self.numpy_arrow_extractor().extract_row(a ) lowerCAmelCase__ : Union[str, Any] = self.python_features_decoder.decode_row(a ) return self.recursive_tensorize(a ) def _lowerCamelCase ( self : int , a : pa.Table ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = self.numpy_arrow_extractor().extract_column(a ) lowerCAmelCase__ : Tuple = self.python_features_decoder.decode_column(a , pa_table.column_names[0] ) lowerCAmelCase__ : int = self.recursive_tensorize(a ) lowerCAmelCase__ : List[str] = self._consolidate(a ) return column def _lowerCamelCase ( self : int , a : pa.Table ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = self.numpy_arrow_extractor().extract_batch(a ) lowerCAmelCase__ : Tuple = self.python_features_decoder.decode_batch(a ) lowerCAmelCase__ : Optional[Any] = self.recursive_tensorize(a ) for column_name in batch: lowerCAmelCase__ : Dict = self._consolidate(batch[column_name] ) return batch
212
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """EleutherAI/gpt-j-6B""": """https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json""", # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class A__ ( __magic_name__ ): lowercase = 'gptj' lowercase = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Optional[Any] , a : Dict=50_400 , a : Union[str, Any]=2_048 , a : List[str]=4_096 , a : Any=28 , a : Optional[Any]=16 , a : Optional[Any]=64 , a : int=None , a : Any="gelu_new" , a : Union[str, Any]=0.0 , a : List[Any]=0.0 , a : List[Any]=0.0 , a : Optional[Any]=1E-5 , a : Optional[int]=0.0_2 , a : int=True , a : str=50_256 , a : str=50_256 , a : Any=False , **a : Dict , ): '''simple docstring''' lowerCAmelCase__ : List[Any] = vocab_size lowerCAmelCase__ : List[Any] = n_positions lowerCAmelCase__ : str = n_embd lowerCAmelCase__ : str = n_layer lowerCAmelCase__ : str = n_head lowerCAmelCase__ : Dict = n_inner lowerCAmelCase__ : Union[str, Any] = rotary_dim lowerCAmelCase__ : Optional[int] = activation_function lowerCAmelCase__ : Any = resid_pdrop lowerCAmelCase__ : int = embd_pdrop lowerCAmelCase__ : int = attn_pdrop lowerCAmelCase__ : List[Any] = layer_norm_epsilon lowerCAmelCase__ : str = initializer_range lowerCAmelCase__ : Dict = use_cache lowerCAmelCase__ : str = bos_token_id lowerCAmelCase__ : int = eos_token_id super().__init__( bos_token_id=a , eos_token_id=a , tie_word_embeddings=a , **a ) class A__ ( __magic_name__ ): def __init__( self : str , a : PretrainedConfig , a : str = "default" , a : List[PatchingSpec] = None , a : bool = False , ): '''simple docstring''' super().__init__(a , task=a , patching_specs=a , use_past=a ) if not getattr(self._config , 'pad_token_id' , a ): # TODO: how to do that better? lowerCAmelCase__ : int = 0 @property def _lowerCamelCase ( self : Tuple ): '''simple docstring''' lowerCAmelCase__ : Dict = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(a , direction='inputs' ) lowerCAmelCase__ : Optional[Any] = {0: 'batch', 1: 'past_sequence + sequence'} else: lowerCAmelCase__ : Tuple = {0: 'batch', 1: 'sequence'} return common_inputs @property def _lowerCamelCase ( self : Union[str, Any] ): '''simple docstring''' return self._config.n_layer @property def _lowerCamelCase ( self : Optional[Any] ): '''simple docstring''' return self._config.n_head def _lowerCamelCase ( self : Tuple , a : PreTrainedTokenizer , a : int = -1 , a : int = -1 , a : bool = False , a : Optional[TensorType] = None , ): '''simple docstring''' lowerCAmelCase__ : Tuple = super(a , self ).generate_dummy_inputs( a , batch_size=a , seq_length=a , is_pair=a , framework=a ) # We need to order the input in the way they appears in the forward() lowerCAmelCase__ : Optional[int] = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch lowerCAmelCase__ , lowerCAmelCase__ : int = common_inputs['input_ids'].shape # Not using the same length for past_key_values lowerCAmelCase__ : Optional[int] = seqlen + 2 lowerCAmelCase__ : Tuple = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) lowerCAmelCase__ : Tuple = [ (torch.zeros(a ), torch.zeros(a )) for _ in range(self.num_layers ) ] lowerCAmelCase__ : Any = common_inputs['attention_mask'] if self.use_past: lowerCAmelCase__ : List[str] = ordered_inputs['attention_mask'].dtype lowerCAmelCase__ : Optional[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(a , a , dtype=a )] , dim=1 ) return ordered_inputs @property def _lowerCamelCase ( self : int ): '''simple docstring''' return 13
212
1
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version _UpperCAmelCase = get_logger(__name__) class snake_case_ : A_ = 'dummy_data' A_ = 'datasets' A_ = False def __init__( self : Tuple , _snake_case : str , _snake_case : str , _snake_case : Union[Version, str] , _snake_case : Optional[str] = None , _snake_case : bool = False , _snake_case : bool = True , _snake_case : Optional[List[Callable]] = None , )->str: '''simple docstring''' __lowerCAmelCase : int = 0 __lowerCAmelCase : Optional[Any] = dataset_name __lowerCAmelCase : Optional[int] = cache_dir __lowerCAmelCase : List[str] = use_local_dummy_data __lowerCAmelCase : Tuple = config # download_callbacks take a single url as input __lowerCAmelCase : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root __lowerCAmelCase : Union[str, Any] = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general __lowerCAmelCase : str = str(_snake_case ) # to be downloaded __lowerCAmelCase : List[Any] = None __lowerCAmelCase : str = None @property def UpperCAmelCase__ ( self : List[str] )->Any: '''simple docstring''' if self._dummy_file is None: __lowerCAmelCase : List[Any] = self.download_dummy_data() return self._dummy_file @property def UpperCAmelCase__ ( self : int )->str: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("""dummy""" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("""dummy""" , self.version_name ) @property def UpperCAmelCase__ ( self : Any )->Optional[int]: '''simple docstring''' return os.path.join(self.dummy_data_folder , """dummy_data.zip""" ) def UpperCAmelCase__ ( self : Optional[Any] )->List[str]: '''simple docstring''' __lowerCAmelCase : Union[str, Any] = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) __lowerCAmelCase : Optional[int] = cached_path( _snake_case , cache_dir=self.cache_dir , extract_compressed_file=_snake_case , force_extract=_snake_case ) return os.path.join(_snake_case , self.dummy_file_name ) @property def UpperCAmelCase__ ( self : Optional[Any] )->Any: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def UpperCAmelCase__ ( self : Optional[Any] )->int: '''simple docstring''' if self._bucket_url is None: __lowerCAmelCase : Any = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , """/""" ) ) return self._bucket_url @property def UpperCAmelCase__ ( self : str )->Optional[Any]: '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , """/""" ).split("""/""" )[:-1] ) def UpperCAmelCase__ ( self : List[str] , _snake_case : List[Any] , *_snake_case : Tuple )->Any: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested __lowerCAmelCase : List[str] = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned __lowerCAmelCase : str = self.dummy_file_name # special case when data_url is a dict if isinstance(_snake_case , _snake_case ): return self.create_dummy_data_dict(_snake_case , _snake_case ) elif isinstance(_snake_case , (list, tuple) ): return self.create_dummy_data_list(_snake_case , _snake_case ) else: return self.create_dummy_data_single(_snake_case , _snake_case ) def UpperCAmelCase__ ( self : Tuple , _snake_case : Optional[int] , *_snake_case : Optional[int] )->Optional[int]: '''simple docstring''' return self.download_and_extract(_snake_case ) def UpperCAmelCase__ ( self : Dict , _snake_case : Dict , _snake_case : Optional[int] )->Union[str, Any]: '''simple docstring''' return self.download_and_extract(_snake_case ) def UpperCAmelCase__ ( self : str , _snake_case : List[Any] , *_snake_case : Optional[Any] , **_snake_case : int )->Tuple: '''simple docstring''' return path def UpperCAmelCase__ ( self : Dict )->int: '''simple docstring''' return {} def UpperCAmelCase__ ( self : Tuple , _snake_case : str , _snake_case : Optional[int] )->Tuple: '''simple docstring''' __lowerCAmelCase : Dict = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(_snake_case , _snake_case ): for single_url in single_urls: download_callback(_snake_case ) else: __lowerCAmelCase : List[str] = single_urls download_callback(_snake_case ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(_snake_case , _snake_case ): __lowerCAmelCase : Optional[int] = [os.path.join(_snake_case , urllib.parse.quote_plus(Path(_snake_case ).name ) ) for x in single_urls] else: __lowerCAmelCase : List[Any] = single_urls __lowerCAmelCase : List[str] = os.path.join(_snake_case , urllib.parse.quote_plus(Path(_snake_case ).name ) ) __lowerCAmelCase : Any = value # make sure that values are unique if all(isinstance(_snake_case , _snake_case ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique __lowerCAmelCase : Union[str, Any] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def UpperCAmelCase__ ( self : Optional[int] , _snake_case : List[Any] , _snake_case : Any )->Dict: '''simple docstring''' __lowerCAmelCase : Tuple = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one __lowerCAmelCase : Optional[Any] = all(bool(re.findall("""[0-9]{3,}-of-[0-9]{3,}""" , _snake_case ) ) for url in data_url ) __lowerCAmelCase : Any = all( url.startswith("""https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed""" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): __lowerCAmelCase : List[Any] = [data_url[0]] * len(_snake_case ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(_snake_case ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __lowerCAmelCase : str = os.path.join(_snake_case , urllib.parse.quote_plus(single_url.split("""/""" )[-1] ) ) dummy_data_list.append(_snake_case ) return dummy_data_list def UpperCAmelCase__ ( self : str , _snake_case : int , _snake_case : Tuple )->Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(_snake_case ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __lowerCAmelCase : List[Any] = os.path.join(_snake_case , urllib.parse.quote_plus(data_url.split("""/""" )[-1] ) ) if os.path.exists(_snake_case ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def UpperCAmelCase__ ( self : List[str] )->Tuple: '''simple docstring''' pass def UpperCAmelCase__ ( self : str )->str: '''simple docstring''' pass def UpperCAmelCase__ ( self : Optional[int] , _snake_case : int )->Optional[Any]: '''simple docstring''' def _iter_archive_members(_snake_case : Optional[Any] ): # this preserves the order of the members inside the ZIP archive __lowerCAmelCase : List[Any] = Path(self.dummy_file ).parent __lowerCAmelCase : Optional[Any] = path.relative_to(_snake_case ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: __lowerCAmelCase : Union[str, Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(_snake_case ) __lowerCAmelCase : Any = Path(_snake_case ) __lowerCAmelCase : str = _iter_archive_members(_snake_case ) if self.use_local_dummy_data else path.rglob("""*""" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((""".""", """__""") ): yield file_path.relative_to(_snake_case ).as_posix(), file_path.open("""rb""" ) def UpperCAmelCase__ ( self : Tuple , _snake_case : Union[str, Any] )->List[str]: '''simple docstring''' if not isinstance(_snake_case , _snake_case ): __lowerCAmelCase : Tuple = [paths] for path in paths: if os.path.isfile(_snake_case ): if os.path.basename(_snake_case ).startswith((""".""", """__""") ): return yield path else: for dirpath, dirnames, filenames in os.walk(_snake_case ): if os.path.basename(_snake_case ).startswith((""".""", """__""") ): continue dirnames.sort() for filename in sorted(_snake_case ): if filename.startswith((""".""", """__""") ): continue yield os.path.join(_snake_case , _snake_case )
232
import random def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :list , SCREAMING_SNAKE_CASE :Dict ) -> tuple: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : List[str] = [], [], [] for element in data: if element < pivot: less.append(SCREAMING_SNAKE_CASE ) elif element > pivot: greater.append(SCREAMING_SNAKE_CASE ) else: equal.append(SCREAMING_SNAKE_CASE ) return less, equal, greater def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :list , SCREAMING_SNAKE_CASE :int ) -> Dict: # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(SCREAMING_SNAKE_CASE ) or index < 0: return None __lowerCAmelCase : Union[str, Any] = items[random.randint(0 , len(SCREAMING_SNAKE_CASE ) - 1 )] __lowerCAmelCase : int = 0 __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Tuple = _partition(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = len(SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = len(SCREAMING_SNAKE_CASE ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # must be in larger else: return quick_select(SCREAMING_SNAKE_CASE , index - (m + count) )
232
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: A_ : Optional[int] = None A_ : Optional[int] = logging.get_logger(__name__) A_ : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} A_ : List[str] = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } A_ : Union[str, Any] = { 'google/fnet-base': 512, 'google/fnet-large': 512, } A_ : Optional[Any] = '▁' class _a (__magic_name__ ): '''simple docstring''' UpperCAmelCase__: str = VOCAB_FILES_NAMES UpperCAmelCase__: str = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__: int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__: Tuple = ['''input_ids''', '''token_type_ids'''] UpperCAmelCase__: Dict = FNetTokenizer def __init__( self , A__=None , A__=None , A__=False , A__=True , A__=True , A__="<unk>" , A__="[SEP]" , A__="<pad>" , A__="[CLS]" , A__="[MASK]" , **A__ , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. A__ : Union[str, Any] = ( AddedToken(A__ , lstrip=A__ , rstrip=A__ , normalized=A__ ) if isinstance(A__ , A__ ) else mask_token ) super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , **A__ , ) A__ : int = do_lower_case A__ : Any = remove_space A__ : Optional[int] = keep_accents A__ : Union[str, Any] = vocab_file A__ : str = False if not self.vocab_file else True def __A ( self , A__ , A__ = None ): A__ : Any = [self.sep_token_id] A__ : Any = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __A ( self , A__ , A__ = None ): A__ : List[Any] = [self.sep_token_id] A__ : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , A__ , A__ = None ): if not os.path.isdir(A__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return A__ : Tuple = os.path.join( A__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ): copyfile(self.vocab_file , A__ ) return (out_vocab_file,)
192
import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch A_ : List[Any] = logging.get_logger(__name__) class _a : '''simple docstring''' def __init__( self , A__ = None , A__ = None , A__=None , A__=None ): if not conversation_id: A__ : List[Any] = uuid.uuida() if past_user_inputs is None: A__ : Dict = [] if generated_responses is None: A__ : int = [] A__ : uuid.UUID = conversation_id A__ : List[str] = past_user_inputs A__ : List[str] = generated_responses A__ : Optional[str] = text def __eq__( self , A__ ): if not isinstance(A__ , A__ ): return False if self.uuid == other.uuid: return True return ( self.new_user_input == other.new_user_input and self.past_user_inputs == other.past_user_inputs and self.generated_responses == other.generated_responses ) def __A ( self , A__ , A__ = False ): if self.new_user_input: if overwrite: logger.warning( F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" was overwritten """ F"""with: \"{text}\".""" ) A__ : str = text else: logger.warning( F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" new input """ F"""ignored: \"{text}\". Set `overwrite` to True to overwrite unprocessed user input""" ) else: A__ : Tuple = text def __A ( self ): if self.new_user_input: self.past_user_inputs.append(self.new_user_input ) A__ : Tuple = None def __A ( self , A__ ): self.generated_responses.append(A__ ) def __A ( self ): for user_input, generated_response in zip(self.past_user_inputs , self.generated_responses ): yield True, user_input yield False, generated_response if self.new_user_input: yield True, self.new_user_input def __repr__( self ): A__ : Optional[Any] = F"""Conversation id: {self.uuid} \n""" for is_user, text in self.iter_texts(): A__ : str = """user""" if is_user else """bot""" output += F"""{name} >> {text} \n""" return output @add_end_docstrings( __magic_name__ , r''' min_length_for_response (`int`, *optional*, defaults to 32): The minimum length (in number of tokens) for a response. minimum_tokens (`int`, *optional*, defaults to 10): The minimum length of tokens to leave for a response. ''' , ) class _a (__magic_name__ ): '''simple docstring''' def __init__( self , *A__ , **A__ ): super().__init__(*A__ , **A__ ) if self.tokenizer.pad_token_id is None: A__ : Tuple = self.tokenizer.eos_token def __A ( self , A__=None , A__=None , A__=None , **A__ ): A__ : Tuple = {} A__ : List[str] = {} A__ : Union[str, Any] = {} if min_length_for_response is not None: A__ : str = min_length_for_response if minimum_tokens is not None: A__ : List[str] = minimum_tokens if "max_length" in generate_kwargs: A__ : List[Any] = generate_kwargs["""max_length"""] # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length) if clean_up_tokenization_spaces is not None: A__ : Optional[int] = clean_up_tokenization_spaces if generate_kwargs: forward_params.update(A__ ) return preprocess_params, forward_params, postprocess_params def __call__( self , A__ , A__=0 , **A__ ): A__ : Optional[Any] = super().__call__(A__ , num_workers=A__ , **A__ ) if isinstance(A__ , A__ ) and len(A__ ) == 1: return outputs[0] return outputs def __A ( self , A__ , A__=32 ): if not isinstance(A__ , A__ ): raise ValueError("""ConversationalPipeline, expects Conversation as inputs""" ) if conversation.new_user_input is None: raise ValueError( F"""Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. """ """Add user inputs with the conversation's `add_user_input` method""" ) if hasattr(self.tokenizer , """_build_conversation_input_ids""" ): A__ : List[str] = self.tokenizer._build_conversation_input_ids(A__ ) else: # If the tokenizer cannot handle conversations, we default to only the old version A__ : Tuple = self._legacy_parse_and_tokenize(A__ ) if self.framework == "pt": A__ : List[str] = torch.LongTensor([input_ids] ) elif self.framework == "tf": A__ : Optional[Any] = tf.constant([input_ids] ) return {"input_ids": input_ids, "conversation": conversation} def __A ( self , A__ , A__=10 , **A__ ): A__ : List[Any] = generate_kwargs.get("""max_length""" , self.model.config.max_length ) A__ : Optional[int] = model_inputs["""input_ids"""].shape[1] if max_length - minimum_tokens < n: logger.warning(F"""Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})""" ) A__ : Dict = max_length - minimum_tokens A__ : Optional[int] = model_inputs["""input_ids"""][:, -trim:] if "attention_mask" in model_inputs: A__ : str = model_inputs["""attention_mask"""][:, -trim:] A__ : List[str] = model_inputs.pop("""conversation""" ) A__ : Dict = max_length A__ : str = self.model.generate(**A__ , **A__ ) if self.model.config.is_encoder_decoder: A__ : Union[str, Any] = 1 else: A__ : Optional[Any] = n return {"output_ids": output_ids[:, start_position:], "conversation": conversation} def __A ( self , A__ , A__=True ): A__ : Dict = model_outputs["""output_ids"""] A__ : str = self.tokenizer.decode( output_ids[0] , skip_special_tokens=A__ , clean_up_tokenization_spaces=A__ , ) A__ : Optional[int] = model_outputs["""conversation"""] conversation.mark_processed() conversation.append_response(A__ ) return conversation def __A ( self , A__ ): A__ : str = self.tokenizer.eos_token_id A__ : Tuple = [] for is_user, text in conversation.iter_texts(): if eos_token_id is not None: input_ids.extend(self.tokenizer.encode(A__ , add_special_tokens=A__ ) + [eos_token_id] ) else: input_ids.extend(self.tokenizer.encode(A__ , add_special_tokens=A__ ) ) if len(A__ ) > self.tokenizer.model_max_length: A__ : str = input_ids[-self.tokenizer.model_max_length :] return input_ids
192
1
"""simple docstring""" from __future__ import annotations def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : list[int] , _UpperCAmelCase : list[int] , _UpperCAmelCase : list[int] , _UpperCAmelCase : list[list[str]] , _UpperCAmelCase : int , ): lowerCAmelCase = len(_UpperCAmelCase ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append(['. ' * i + 'Q ' + '. ' * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(_UpperCAmelCase ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , _UpperCAmelCase , _UpperCAmelCase , ) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : int ): lowerCAmelCase = [] depth_first_search([] , [] , [] , _UpperCAmelCase , _UpperCAmelCase ) # Print all the boards for board in boards: for column in board: print(_UpperCAmelCase ) print('' ) print(len(_UpperCAmelCase ) , 'solutions were found.' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
309
"""simple docstring""" from __future__ import annotations def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : str , _UpperCAmelCase : list[str] | None = None ): lowerCAmelCase = word_bank or [] # create a table lowerCAmelCase = len(_UpperCAmelCase ) + 1 lowerCAmelCase = [] for _ in range(_UpperCAmelCase ): table.append([] ) # seed value lowerCAmelCase = [[]] # because empty string has empty combination # iterate through the indices for i in range(_UpperCAmelCase ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(_UpperCAmelCase )] == word: lowerCAmelCase = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(_UpperCAmelCase )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(_UpperCAmelCase )]: combination.reverse() return table[len(_UpperCAmelCase )] if __name__ == "__main__": print(all_construct('''jwajalapa''', ['''jwa''', '''j''', '''w''', '''a''', '''la''', '''lapa'''])) print(all_construct('''rajamati''', ['''s''', '''raj''', '''amat''', '''raja''', '''ma''', '''i''', '''t'''])) print( all_construct( '''hexagonosaurus''', ['''h''', '''ex''', '''hex''', '''ag''', '''ago''', '''ru''', '''auru''', '''rus''', '''go''', '''no''', '''o''', '''s'''], ) )
309
1
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/config.json', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/config.json', } class a_ ( lowerCamelCase ): lowercase = """xlnet""" lowercase = ["""mems"""] lowercase = { """n_token""": """vocab_size""", # Backward compatibility """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , _SCREAMING_SNAKE_CASE=32000 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=24 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="bi" , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1e-12 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=-1 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="last" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="tanh" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=2 , **_SCREAMING_SNAKE_CASE , ) -> Tuple: """simple docstring""" UpperCamelCase = vocab_size UpperCamelCase = d_model UpperCamelCase = n_layer UpperCamelCase = n_head if d_model % n_head != 0: raise ValueError(F"'d_model % n_head' ({d_model % n_head}) should be equal to 0" ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( F"`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})" ) UpperCamelCase = d_model // n_head UpperCamelCase = ff_activation UpperCamelCase = d_inner UpperCamelCase = untie_r UpperCamelCase = attn_type UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps UpperCamelCase = dropout UpperCamelCase = mem_len UpperCamelCase = reuse_len UpperCamelCase = bi_data UpperCamelCase = clamp_len UpperCamelCase = same_length UpperCamelCase = summary_type UpperCamelCase = summary_use_proj UpperCamelCase = summary_activation UpperCamelCase = summary_last_dropout UpperCamelCase = start_n_top UpperCamelCase = end_n_top UpperCamelCase = bos_token_id UpperCamelCase = pad_token_id UpperCamelCase = eos_token_id if "use_cache" in kwargs: warnings.warn( """The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`""" """ instead.""" , _SCREAMING_SNAKE_CASE , ) UpperCamelCase = kwargs["""use_cache"""] UpperCamelCase = use_mems_eval UpperCamelCase = use_mems_train super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def A__ ( self ) -> Optional[Any]: """simple docstring""" logger.info(F"The model {self.model_type} is one of the few models that has no sequence length limit." ) return -1 @max_position_embeddings.setter def A__ ( self , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" raise NotImplementedError( F"The model {self.model_type} is one of the few models that has no sequence length limit." )
321
'''simple docstring''' import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem SCREAMING_SNAKE_CASE__ = importlib.util.find_spec('s3fs') is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 SCREAMING_SNAKE_CASE__ = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(f'A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def lowercase__ ( __UpperCamelCase )-> str: if "://" in dataset_path: UpperCamelCase = dataset_path.split("""://""" )[1] return dataset_path def lowercase__ ( __UpperCamelCase )-> bool: if fs is not None and fs.protocol != "file": return True else: return False def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> int: UpperCamelCase = not is_remote_filesystem(__UpperCamelCase ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(__UpperCamelCase ) , fs._strip_protocol(__UpperCamelCase ) ) else: fs.mv(__UpperCamelCase , __UpperCamelCase , recursive=__UpperCamelCase ) def lowercase__ ( )-> None: if hasattr(fsspec.asyn , """reset_lock""" ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: UpperCamelCase = None UpperCamelCase = None UpperCamelCase = threading.Lock()
321
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if not numbers: return 0 if not isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) or not all( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for number in numbers ): raise ValueError('numbers must be an iterable of integers' ) __lowerCamelCase : Optional[int] = numbers[0] for i in range(1 , len(SCREAMING_SNAKE_CASE__ ) ): # update the maximum and minimum subarray products __lowerCamelCase : Optional[Any] = numbers[i] if number < 0: __lowerCamelCase , __lowerCamelCase : Union[str, Any] = min_till_now, max_till_now __lowerCamelCase : Optional[Any] = max(SCREAMING_SNAKE_CASE__ , max_till_now * number ) __lowerCamelCase : Optional[Any] = min(SCREAMING_SNAKE_CASE__ , min_till_now * number ) # update the maximum product found till now __lowerCamelCase : int = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return max_prod
194
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = len(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): __lowerCamelCase : Dict = True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1 ): __lowerCamelCase : Union[str, Any] = False for i in range(1 , arr_len + 1 ): for j in range(1 , required_sum + 1 ): if arr[i - 1] > j: __lowerCamelCase : Tuple = subset[i - 1][j] if arr[i - 1] <= j: __lowerCamelCase : List[Any] = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
194
1
"""simple docstring""" from collections import defaultdict from pathlib import Path import pandas as pd from rouge_cli import calculate_rouge_path from utils import calculate_rouge lowercase__ : Tuple = [ "Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of the" " final seconds on board Flight 9525. The Germanwings co-pilot says he had a \"previous episode of severe" " depression\" German airline confirms it knew of Andreas Lubitz's depression years before he took control.", "The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal" " accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC's" " founding Rome Statute in January. Israel and the United States opposed the Palestinians' efforts to join the" " body.", "Amnesty International releases its annual report on the death penalty. The report catalogs the use of" " state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the" " world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital" " punishment.", ] lowercase__ : str = [ "Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports ." " Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz" " had informed his Lufthansa training school of an episode of severe depression, airline says .", "Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June ." " Israel and the United States opposed the move, which could open the door to war crimes investigations against" " Israelis .", "Amnesty's annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to" " death . Organization claims that governments around the world are using the threat of terrorism to advance" " executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death" " sentences up by 28% .", ] def __lowercase ( ): snake_case_ : List[str] = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , bootstrap_aggregation=__lowerCAmelCase , rouge_keys=['''rouge2''', '''rougeL'''] ) assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) snake_case_ : Optional[int] = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , bootstrap_aggregation=__lowerCAmelCase , rouge_keys=['''rouge2'''] ) assert ( pd.DataFrame(no_aggregation['''rouge2'''] ).fmeasure.mean() == pd.DataFrame(no_aggregation_just_ra['''rouge2'''] ).fmeasure.mean() ) def __lowercase ( ): snake_case_ : Any = '''rougeLsum''' snake_case_ : Any = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase , rouge_keys=[k] )[k] snake_case_ : Dict = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase , rouge_keys=[k] )[k] assert score > score_no_sep def __lowercase ( ): snake_case_ : Dict = ['''rouge1''', '''rouge2''', '''rougeL'''] snake_case_ : Tuple = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase , rouge_keys=__lowerCAmelCase ) snake_case_ : Dict = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase , rouge_keys=__lowerCAmelCase ) assert score_sep == score_no_sep def __lowercase ( ): snake_case_ : Any = [ '''Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.''', '''Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .''', ] snake_case_ : List[Any] = [ '''Margot Frank, died in 1945, a month earlier than previously thought.''', '''Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of''' ''' the final seconds on board Flight 9525.''', ] assert calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase ) == calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , newline_sep=__lowerCAmelCase ) def __lowercase ( ): snake_case_ : str = [ '''" "a person who has such a video needs to immediately give it to the investigators," prosecutor says .<n> "it is a very disturbing scene," editor-in-chief of bild online tells "erin burnett: outfront" ''' ] snake_case_ : str = [ ''' Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports . Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says .''' ] snake_case_ : List[Any] = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , rouge_keys=['''rougeLsum'''] , newline_sep=__lowerCAmelCase )['''rougeLsum'''] snake_case_ : Optional[Any] = calculate_rouge(__lowerCAmelCase , __lowerCAmelCase , rouge_keys=['''rougeLsum'''] )['''rougeLsum'''] assert new_score > prev_score def __lowercase ( ): snake_case_ : Optional[int] = Path('''examples/seq2seq/test_data/wmt_en_ro''' ) snake_case_ : int = calculate_rouge_path(data_dir.joinpath('''test.source''' ) , data_dir.joinpath('''test.target''' ) ) assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) snake_case_ : Union[str, Any] = calculate_rouge_path( data_dir.joinpath('''test.source''' ) , data_dir.joinpath('''test.target''' ) , bootstrap_aggregation=__lowerCAmelCase ) assert isinstance(__lowerCAmelCase , __lowerCAmelCase )
264
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=lowerCAmelCase_ ) class __lowerCAmelCase ( lowerCAmelCase_ ): """simple docstring""" A__ : str = field(default='''audio-classification''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) A__ : ClassVar[Features] = Features({'''audio''': Audio()} ) A__ : ClassVar[Features] = Features({'''labels''': ClassLabel} ) A__ : str = "audio" A__ : str = "labels" def snake_case_ ( self : List[Any] , _snake_case : List[str] ): if self.label_column not in features: raise ValueError(F'Column {self.label_column} is not present in features.' ) if not isinstance(features[self.label_column] , _snake_case ): raise ValueError(F'Column {self.label_column} is not a ClassLabel.' ) __lowercase : Optional[Any] = copy.deepcopy(self ) __lowercase : Optional[int] = self.label_schema.copy() __lowercase : Tuple = features[self.label_column] __lowercase : Optional[Any] = label_schema return task_template @property def snake_case_ ( self : Optional[Any] ): return { self.audio_column: "audio", self.label_column: "labels", }
156
0
from math import pi def lowerCamelCase_ ( UpperCamelCase__ : List[Any], UpperCamelCase__ : Optional[int] ): '''simple docstring''' return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(9_0, 1_0))
370
from __future__ import annotations class __lowercase : '''simple docstring''' def __init__( self : List[Any] , _a : int ): UpperCamelCase__ = data UpperCamelCase__ = None UpperCamelCase__ = None def lowerCamelCase_ ( UpperCamelCase__ : Node | None ): # In Order traversal of the tree '''simple docstring''' if tree: display(tree.left ) print(tree.data ) display(tree.right ) def lowerCamelCase_ ( UpperCamelCase__ : Node | None ): '''simple docstring''' return 1 + max(depth_of_tree(tree.left ), depth_of_tree(tree.right ) ) if tree else 0 def lowerCamelCase_ ( UpperCamelCase__ : Node ): '''simple docstring''' if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def lowerCamelCase_ ( ): # Main function for testing. '''simple docstring''' UpperCamelCase__ = Node(1 ) UpperCamelCase__ = Node(2 ) UpperCamelCase__ = Node(3 ) UpperCamelCase__ = Node(4 ) UpperCamelCase__ = Node(5 ) UpperCamelCase__ = Node(6 ) UpperCamelCase__ = Node(7 ) UpperCamelCase__ = Node(8 ) UpperCamelCase__ = Node(9 ) print(is_full_binary_tree(UpperCamelCase__ ) ) print(depth_of_tree(UpperCamelCase__ ) ) print('''Tree is: ''' ) display(UpperCamelCase__ ) if __name__ == "__main__": main()
35
0
"""simple docstring""" def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : int = 10**12 ): '''simple docstring''' lowerCAmelCase = 1 lowerCAmelCase = 0 lowerCAmelCase = 1 lowerCAmelCase = 1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f'{solution() = }')
46
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : List[Any] = logging.get_logger(__name__) __UpperCamelCase : str = { "microsoft/unispeech-large-1500h-cv": ( "https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json" ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class __magic_name__ ( __lowerCAmelCase): A: Optional[int] = "unispeech" def __init__( self : Union[str, Any] , lowerCamelCase__ : Tuple=32 , lowerCamelCase__ : Dict=768 , lowerCamelCase__ : Dict=12 , lowerCamelCase__ : List[Any]=12 , lowerCamelCase__ : List[Any]=3072 , lowerCamelCase__ : Tuple="gelu" , lowerCamelCase__ : Dict=0.1 , lowerCamelCase__ : Dict=0.1 , lowerCamelCase__ : Optional[int]=0.1 , lowerCamelCase__ : List[Any]=0.0 , lowerCamelCase__ : Optional[int]=0.0 , lowerCamelCase__ : Tuple=0.1 , lowerCamelCase__ : int=0.1 , lowerCamelCase__ : Union[str, Any]=0.02 , lowerCamelCase__ : Dict=1E-5 , lowerCamelCase__ : Any="group" , lowerCamelCase__ : Any="gelu" , lowerCamelCase__ : Union[str, Any]=(512, 512, 512, 512, 512, 512, 512) , lowerCamelCase__ : Any=(5, 2, 2, 2, 2, 2, 2) , lowerCamelCase__ : Dict=(10, 3, 3, 3, 3, 2, 2) , lowerCamelCase__ : Optional[int]=False , lowerCamelCase__ : Dict=128 , lowerCamelCase__ : Tuple=16 , lowerCamelCase__ : Tuple=False , lowerCamelCase__ : Optional[Any]=True , lowerCamelCase__ : Optional[int]=0.05 , lowerCamelCase__ : List[str]=10 , lowerCamelCase__ : List[Any]=2 , lowerCamelCase__ : Optional[Any]=0.0 , lowerCamelCase__ : Optional[int]=10 , lowerCamelCase__ : Dict=0 , lowerCamelCase__ : Union[str, Any]=320 , lowerCamelCase__ : int=2 , lowerCamelCase__ : Union[str, Any]=0.1 , lowerCamelCase__ : List[str]=100 , lowerCamelCase__ : str=256 , lowerCamelCase__ : Union[str, Any]=256 , lowerCamelCase__ : List[str]=0.1 , lowerCamelCase__ : Tuple="mean" , lowerCamelCase__ : Tuple=False , lowerCamelCase__ : List[Any]=False , lowerCamelCase__ : Optional[int]=256 , lowerCamelCase__ : int=80 , lowerCamelCase__ : str=0 , lowerCamelCase__ : str=1 , lowerCamelCase__ : int=2 , lowerCamelCase__ : str=0.5 , **lowerCamelCase__ : List[Any] , ) -> int: '''simple docstring''' super().__init__(**lowerCamelCase__ , pad_token_id=lowerCamelCase__ , bos_token_id=lowerCamelCase__ , eos_token_id=lowerCamelCase__ ) UpperCamelCase__ : int = hidden_size UpperCamelCase__ : int = feat_extract_norm UpperCamelCase__ : Union[str, Any] = feat_extract_activation UpperCamelCase__ : Tuple = list(lowerCamelCase__ ) UpperCamelCase__ : Optional[Any] = list(lowerCamelCase__ ) UpperCamelCase__ : Any = list(lowerCamelCase__ ) UpperCamelCase__ : Optional[int] = conv_bias UpperCamelCase__ : Dict = num_conv_pos_embeddings UpperCamelCase__ : Dict = num_conv_pos_embedding_groups UpperCamelCase__ : Any = len(self.conv_dim ) UpperCamelCase__ : List[str] = num_hidden_layers UpperCamelCase__ : Union[str, Any] = intermediate_size UpperCamelCase__ : Tuple = hidden_act UpperCamelCase__ : Optional[Any] = num_attention_heads UpperCamelCase__ : Optional[Any] = hidden_dropout UpperCamelCase__ : str = attention_dropout UpperCamelCase__ : Optional[Any] = activation_dropout UpperCamelCase__ : Optional[int] = feat_proj_dropout UpperCamelCase__ : Any = final_dropout UpperCamelCase__ : List[Any] = layerdrop UpperCamelCase__ : Optional[int] = layer_norm_eps UpperCamelCase__ : List[str] = initializer_range UpperCamelCase__ : Dict = num_ctc_classes UpperCamelCase__ : Dict = vocab_size UpperCamelCase__ : Dict = do_stable_layer_norm UpperCamelCase__ : Optional[Any] = use_weighted_layer_sum UpperCamelCase__ : List[Any] = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' F" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`," F" `len(config.conv_kernel) = {len(self.conv_kernel )}`." ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCamelCase__ : List[Any] = apply_spec_augment UpperCamelCase__ : Dict = mask_time_prob UpperCamelCase__ : List[str] = mask_time_length UpperCamelCase__ : Optional[int] = mask_time_min_masks UpperCamelCase__ : List[str] = mask_feature_prob UpperCamelCase__ : Union[str, Any] = mask_feature_length UpperCamelCase__ : List[Any] = mask_feature_min_masks # parameters for pretraining with codevector quantized representations UpperCamelCase__ : Tuple = num_codevectors_per_group UpperCamelCase__ : str = num_codevector_groups UpperCamelCase__ : Tuple = contrastive_logits_temperature UpperCamelCase__ : Optional[Any] = feat_quantizer_dropout UpperCamelCase__ : Optional[Any] = num_negatives UpperCamelCase__ : Optional[Any] = codevector_dim UpperCamelCase__ : int = proj_codevector_dim UpperCamelCase__ : Tuple = diversity_loss_weight # ctc loss UpperCamelCase__ : str = ctc_loss_reduction UpperCamelCase__ : List[str] = ctc_zero_infinity # pretraining loss UpperCamelCase__ : Dict = replace_prob @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
146
0
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class _SCREAMING_SNAKE_CASE : __SCREAMING_SNAKE_CASE :int __SCREAMING_SNAKE_CASE :int class _SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] , a__ : int ): __magic_name__ = [[] for _ in range(a__ )] __magic_name__ = size def __getitem__( self : Optional[int] , a__ : int ): return iter(self._graph[vertex] ) @property def snake_case__ ( self : Dict ): return self._size def snake_case__ ( self : Dict , a__ : int , a__ : int , a__ : int ): if weight not in (0, 1): raise ValueError('''Edge weight must be either 0 or 1.''' ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError('''Vertex indexes must be in [0; size).''' ) self._graph[from_vertex].append(Edge(a__ , a__ ) ) def snake_case__ ( self : Any , a__ : int , a__ : int ): __magic_name__ = deque([start_vertex] ) __magic_name__ = [None] * self.size __magic_name__ = 0 while queue: __magic_name__ = queue.popleft() __magic_name__ = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: __magic_name__ = current_distance + edge.weight __magic_name__ = distances[edge.destination_vertex] if ( isinstance(a__ , a__ ) and new_distance >= dest_vertex_distance ): continue __magic_name__ = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError('''No path from start_vertex to finish_vertex.''' ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
98
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _SCREAMING_SNAKE_CASE ( __a ,__a ,__a ,unittest.TestCase ): __SCREAMING_SNAKE_CASE :Union[str, Any] = StableDiffusionInpaintPipeline __SCREAMING_SNAKE_CASE :Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS __SCREAMING_SNAKE_CASE :Tuple = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __SCREAMING_SNAKE_CASE :str = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __SCREAMING_SNAKE_CASE :Optional[Any] = frozenset([] ) def snake_case__ ( self : Union[str, Any] ): torch.manual_seed(0 ) __magic_name__ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a__ , ) __magic_name__ = PNDMScheduler(skip_prk_steps=a__ ) torch.manual_seed(0 ) __magic_name__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __magic_name__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='''gelu''' , projection_dim=512 , ) __magic_name__ = CLIPTextModel(a__ ) __magic_name__ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) __magic_name__ = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def snake_case__ ( self : Any , a__ : Optional[int] , a__ : List[Any]=0 ): # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched __magic_name__ = floats_tensor((1, 3, 32, 32) , rng=random.Random(a__ ) ).to(a__ ) __magic_name__ = image.cpu().permute(0 , 2 , 3 , 1 )[0] __magic_name__ = Image.fromarray(np.uinta(a__ ) ).convert('''RGB''' ).resize((64, 64) ) __magic_name__ = Image.fromarray(np.uinta(image + 4 ) ).convert('''RGB''' ).resize((64, 64) ) if str(a__ ).startswith('''mps''' ): __magic_name__ = torch.manual_seed(a__ ) else: __magic_name__ = torch.Generator(device=a__ ).manual_seed(a__ ) __magic_name__ = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': init_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def snake_case__ ( self : Union[str, Any] ): __magic_name__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator __magic_name__ = self.get_dummy_components() __magic_name__ = StableDiffusionInpaintPipeline(**a__ ) __magic_name__ = sd_pipe.to(a__ ) sd_pipe.set_progress_bar_config(disable=a__ ) __magic_name__ = self.get_dummy_inputs(a__ ) __magic_name__ = sd_pipe(**a__ ).images __magic_name__ = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __magic_name__ = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case__ ( self : List[Any] ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def snake_case__ ( self : int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case__ ( self : Tuple ): __magic_name__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) __magic_name__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) __magic_name__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench.npy''' ) __magic_name__ = '''stabilityai/stable-diffusion-2-inpainting''' __magic_name__ = StableDiffusionInpaintPipeline.from_pretrained(a__ , safety_checker=a__ ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() __magic_name__ = '''Face of a yellow cat, high resolution, sitting on a park bench''' __magic_name__ = torch.manual_seed(0 ) __magic_name__ = pipe( prompt=a__ , image=a__ , mask_image=a__ , generator=a__ , output_type='''np''' , ) __magic_name__ = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def snake_case__ ( self : List[str] ): __magic_name__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) __magic_name__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) __magic_name__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench_fp16.npy''' ) __magic_name__ = '''stabilityai/stable-diffusion-2-inpainting''' __magic_name__ = StableDiffusionInpaintPipeline.from_pretrained( a__ , torch_dtype=torch.floataa , safety_checker=a__ , ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing() __magic_name__ = '''Face of a yellow cat, high resolution, sitting on a park bench''' __magic_name__ = torch.manual_seed(0 ) __magic_name__ = pipe( prompt=a__ , image=a__ , mask_image=a__ , generator=a__ , output_type='''np''' , ) __magic_name__ = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def snake_case__ ( self : List[Any] ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __magic_name__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) __magic_name__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) __magic_name__ = '''stabilityai/stable-diffusion-2-inpainting''' __magic_name__ = PNDMScheduler.from_pretrained(a__ , subfolder='''scheduler''' ) __magic_name__ = StableDiffusionInpaintPipeline.from_pretrained( a__ , safety_checker=a__ , scheduler=a__ , torch_dtype=torch.floataa , ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __magic_name__ = '''Face of a yellow cat, high resolution, sitting on a park bench''' __magic_name__ = torch.manual_seed(0 ) __magic_name__ = pipe( prompt=a__ , image=a__ , mask_image=a__ , generator=a__ , num_inference_steps=2 , output_type='''np''' , ) __magic_name__ = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
98
1
import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py __UpperCAmelCase = '\\n@INPROCEEDINGS{Papineni02bleu:a,\n author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n booktitle = {},\n year = {2002},\n pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n title = "{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation",\n author = "Lin, Chin-Yew and\n Och, Franz Josef",\n booktitle = "{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics",\n month = "aug 23{--}aug 27",\n year = "2004",\n address = "Geneva, Switzerland",\n publisher = "COLING",\n url = "https://www.aclweb.org/anthology/C04-1072",\n pages = "501--507",\n}\n' __UpperCAmelCase = '\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine\'s output and that of a human: "the closer a machine translation is to a professional human translation,\nthe better it is" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation\'s overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU\'s output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n' __UpperCAmelCase = '\nComputes BLEU score of translated segments against one or more references.\nArgs:\n predictions: list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n max_order: Maximum n-gram order to use when computing BLEU score.\n smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n \'bleu\': bleu score,\n \'precisions\': geometric mean of n-gram precisions,\n \'brevity_penalty\': brevity penalty,\n \'length_ratio\': ratio of lengths,\n \'translation_length\': translation_length,\n \'reference_length\': reference_length\nExamples:\n\n >>> predictions = [\n ... ["hello", "there", "general", "kenobi"], # tokenized prediction of the first sample\n ... ["foo", "bar", "foobar"] # tokenized prediction of the second sample\n ... ]\n >>> references = [\n ... [["hello", "there", "general", "kenobi"], ["hello", "there", "!"]], # tokenized references for the first sample (2 references)\n ... [["foo", "bar", "foobar"]] # tokenized references for the second sample (1 reference)\n ... ]\n >>> bleu = datasets.load_metric("bleu")\n >>> results = bleu.compute(predictions=predictions, references=references)\n >>> print(results["bleu"])\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase (datasets.Metric ): '''simple docstring''' def __UpperCAmelCase ( self ) -> Tuple: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' , id='token' ) , id='sequence' ), 'references': datasets.Sequence( datasets.Sequence(datasets.Value('string' , id='token' ) , id='sequence' ) , id='references' ), } ) , codebase_urls=['https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py'] , reference_urls=[ 'https://en.wikipedia.org/wiki/BLEU', 'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213', ] , ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=4 , _UpperCamelCase=False ) -> Union[str, Any]: UpperCAmelCase_ : List[str] = compute_bleu( reference_corpus=_UpperCamelCase , translation_corpus=_UpperCamelCase , max_order=_UpperCamelCase , smooth=_UpperCamelCase ) ((UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_)) : Tuple = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
29
'''simple docstring''' import math from numpy import inf from scipy.integrate import quad def __a(SCREAMING_SNAKE_CASE_ : float ): '''simple docstring''' if num <= 0: raise ValueError("math domain error" ) return quad(SCREAMING_SNAKE_CASE_ , 0 , SCREAMING_SNAKE_CASE_ , args=(SCREAMING_SNAKE_CASE_) )[0] def __a(SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ): '''simple docstring''' return math.pow(SCREAMING_SNAKE_CASE_ , z - 1 ) * math.exp(-x ) if __name__ == "__main__": from doctest import testmod testmod()
158
0
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def UpperCamelCase_( snake_case__: Dict , snake_case__: Optional[int] ) -> Union[str, Any]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer UpperCAmelCase__ = flax_key_tuple[:-1] + ('weight',) UpperCAmelCase__ = torch.permute(snake_case__ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(snake_case__ ): # linear layer UpperCAmelCase__ = flax_key_tuple[:-1] + ('weight',) UpperCAmelCase__ = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: UpperCAmelCase__ = flax_key_tuple[:-1] + ('weight',) return flax_key_tuple, flax_tensor def UpperCamelCase_( snake_case__: str , snake_case__: Dict , snake_case__: Union[str, Any] ) -> str: if "metadata" in layer: UpperCAmelCase__ = layer.split('metadata' ) UpperCAmelCase__ = ''.join(split_layer[0] )[:-1] UpperCAmelCase__ = [tuple(('metadata' + split_layer[1]).split('/' ) )] elif "kvstore" in layer: UpperCAmelCase__ = layer.split('kvstore' ) UpperCAmelCase__ = ''.join(split_layer[0] )[:-1] UpperCAmelCase__ = [tuple(('kvstore' + split_layer[1]).split('/' ) )] else: UpperCAmelCase__ = layer.split('/' ) UpperCAmelCase__ = '/'.join(split_layer[:-1] ) UpperCAmelCase__ = (split_layer[-1],) if "kvstore/path" in layer: UpperCAmelCase__ = f"{switch_checkpoint_path}/{checkpoint_info[layer]}" elif "kvstore/driver" in layer: UpperCAmelCase__ = 'file' else: UpperCAmelCase__ = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def UpperCamelCase_( snake_case__: Optional[int] , snake_case__: Tuple ) -> Union[str, Any]: UpperCAmelCase__ = rename_keys(snake_case__ ) UpperCAmelCase__ = {} for k, v in current_block.items(): UpperCAmelCase__ = v UpperCAmelCase__ = new_current_block torch.save(snake_case__ , snake_case__ ) def UpperCamelCase_( snake_case__: Dict , snake_case__: Optional[int] , snake_case__: int , snake_case__: Dict , snake_case__: str = WEIGHTS_NAME ) -> List[Any]: UpperCAmelCase__ = convert_file_size_to_int(snake_case__ ) UpperCAmelCase__ = [] UpperCAmelCase__ = {} UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 os.makedirs(snake_case__ , exist_ok=snake_case__ ) with gfile.GFile(switch_checkpoint_path + '/checkpoint' , 'rb' ) as fp: UpperCAmelCase__ = serialization.msgpack_restore(fp.read() )['optimizer']['target'] UpperCAmelCase__ = flatten_dict(snake_case__ , sep='/' ) UpperCAmelCase__ = {} for layer in checkpoint_info.keys(): UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = get_key_and_tensorstore_dict( snake_case__ , snake_case__ , snake_case__ ) if curr_real_layer_name in all_layers: UpperCAmelCase__ = content else: UpperCAmelCase__ = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file UpperCAmelCase__ = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() UpperCAmelCase__ = torch.tensor(snake_case__ ) UpperCAmelCase__ = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts UpperCAmelCase__ , UpperCAmelCase__ = rename_base_flax_keys(tuple(key.split('/' ) ) , snake_case__ ) UpperCAmelCase__ = '/'.join(snake_case__ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: UpperCAmelCase__ = os.path.join( snake_case__ , weights_name.replace('.bin' , f"-{len(snake_case__ )+1:05d}-of-???.bin" ) ) rename_and_save_block(snake_case__ , snake_case__ ) sharded_state_dicts.append(current_block.keys() ) del current_block UpperCAmelCase__ = {} UpperCAmelCase__ = 0 UpperCAmelCase__ = raw_weights.to(getattr(snake_case__ , snake_case__ ) ) current_block_size += weight_size total_size += weight_size # Add the last block UpperCAmelCase__ = os.path.join(snake_case__ , weights_name.replace('.bin' , f"-{len(snake_case__ )+1:05d}-of-???.bin" ) ) rename_and_save_block(snake_case__ , snake_case__ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(snake_case__ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index UpperCAmelCase__ = {} UpperCAmelCase__ = {} for idx, shard in enumerate(snake_case__ ): UpperCAmelCase__ = weights_name.replace( '.bin' , f"-{idx+1:05d}-of-{len(snake_case__ ):05d}.bin" ) # len(sharded_state_dicts):05d} UpperCAmelCase__ = os.path.join(snake_case__ , weights_name.replace('.bin' , f"-{idx+1:05d}-of-???.bin" ) ) os.rename(snake_case__ , os.path.join(snake_case__ , snake_case__ ) ) UpperCAmelCase__ = shard for key in shard: UpperCAmelCase__ = shard_file # Add the metadata UpperCAmelCase__ = {'total_size': total_size} UpperCAmelCase__ = {'metadata': metadata, 'weight_map': weight_map} with open(os.path.join(snake_case__ , snake_case__ ) , 'w' , encoding='utf-8' ) as f: UpperCAmelCase__ = json.dumps(snake_case__ , indent=2 , sort_keys=snake_case__ ) + '\n' f.write(snake_case__ ) return metadata, index if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--switch_t5x_checkpoint_path''', default='''/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600''', type=str, required=False, help='''Path to a directory containing a folder per layer. Follows the original Google format.''', ) parser.add_argument('''--max_shard_size''', default='''10GB''', required=False, help='''Max shard size''') parser.add_argument('''--dtype''', default='''bfloat16''', type=str, required=False, help='''dtype of the saved model''') parser.add_argument( '''--pytorch_dump_folder_path''', default='''/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted''', type=str, required=False, help='''Path to the output pytorch model.''', ) _UpperCamelCase = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def UpperCamelCase_( ) -> Optional[Any]: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer UpperCAmelCase__ = SwitchTransformersConfig.from_pretrained('google/switch-base-8' ) config.save_pretrained('/home/arthur_huggingface_co/transformers/switch_converted' ) UpperCAmelCase__ = SwitchTransformersForConditionalGeneration.from_pretrained( '/home/arthur_huggingface_co/transformers/switch_converted' , device_map='auto' ) UpperCAmelCase__ = TaTokenizer.from_pretrained('t5-small' ) UpperCAmelCase__ = 'A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.' UpperCAmelCase__ = tokenizer(snake_case__ , return_tensors='pt' ).input_ids UpperCAmelCase__ = model.generate(snake_case__ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
335
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class lowercase : '''simple docstring''' def __init__(self ) -> str: """simple docstring""" UpperCAmelCase__ = '' UpperCAmelCase__ = '' UpperCAmelCase__ = [] UpperCAmelCase__ = 0 UpperCAmelCase__ = 256 UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 def UpperCamelCase__ (self , __a ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = cva.imread(__a , 0 ) UpperCAmelCase__ = copy.deepcopy(self.img ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = plt.hist(self.img.ravel() , 256 , [0, 256] , label='x' ) UpperCAmelCase__ = np.sum(__a ) for i in range(len(__a ) ): UpperCAmelCase__ = x[i] / self.k self.sk += prk UpperCAmelCase__ = (self.L - 1) * self.sk if self.rem != 0: UpperCAmelCase__ = int(last % last ) UpperCAmelCase__ = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__a ) UpperCAmelCase__ = int(np.ma.count(self.img ) / self.img[1].size ) UpperCAmelCase__ = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): UpperCAmelCase__ = self.img[j][i] if num != self.last_list[num]: UpperCAmelCase__ = self.last_list[num] cva.imwrite('output_data/output.jpg' , self.img ) def UpperCamelCase__ (self ) -> Optional[int]: """simple docstring""" plt.hist(self.img.ravel() , 256 , [0, 256] ) def UpperCamelCase__ (self ) -> Tuple: """simple docstring""" cva.imshow('Output-Image' , self.img ) cva.imshow('Input-Image' , self.original_image ) cva.waitKey(5000 ) cva.destroyAllWindows() if __name__ == "__main__": _UpperCamelCase = os.path.join(os.path.basename(__file__), '''image_data/input.jpg''') _UpperCamelCase = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
335
1
import unittest from knapsack import greedy_knapsack as kp class _A ( unittest.TestCase ): def _lowerCamelCase ( self : List[Any]): '''simple docstring''' __a = [10, 20, 30, 40, 50, 60] __a = [2, 4, 6, 8, 10, 12] __a = 100 self.assertEqual(kp.calc_profit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) , 210) def _lowerCamelCase ( self : Dict): '''simple docstring''' self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''') def _lowerCamelCase ( self : Any): '''simple docstring''' self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Weight can not be negative.''') def _lowerCamelCase ( self : Dict): '''simple docstring''' self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Profit can not be negative.''') def _lowerCamelCase ( self : List[str]): '''simple docstring''' self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''') def _lowerCamelCase ( self : Any): '''simple docstring''' self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , '''The length of profit and weight must be same.''') if __name__ == "__main__": unittest.main()
49
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available UpperCamelCase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
87
0
'''simple docstring''' import itertools import os import re UpperCamelCase_ = re.compile(R"([A-Z]+)([A-Z][a-z])") UpperCamelCase_ = re.compile(R"([a-z\d])([A-Z])") UpperCamelCase_ = re.compile(R"(?<!_)_(?!_)") UpperCamelCase_ = re.compile(R"(_{2,})") UpperCamelCase_ = R"^\w+(\.\w+)*$" UpperCamelCase_ = R"<>:/\|?*" def lowercase__( __UpperCamelCase: Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE : str = _uppercase_uppercase_re.sub(r'\1_\2' ,__UpperCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = _lowercase_uppercase_re.sub(r'\1_\2' ,__UpperCamelCase ) return name.lower() def lowercase__( __UpperCamelCase: Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = _single_underscore_re.split(__UpperCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = [_multiple_underscores_re.split(__UpperCamelCase ) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(__UpperCamelCase ) if n != '' ) def lowercase__( __UpperCamelCase: Union[str, Any] ): """simple docstring""" if os.path.basename(__UpperCamelCase ) != name: raise ValueError(f"Should be a dataset name, not a path: {name}" ) return camelcase_to_snakecase(__UpperCamelCase ) def lowercase__( __UpperCamelCase: Union[str, Any] ,__UpperCamelCase: Dict ): """simple docstring""" if os.path.basename(__UpperCamelCase ) != name: raise ValueError(f"Should be a dataset name, not a path: {name}" ) if not re.match(_split_re ,__UpperCamelCase ): raise ValueError(f"Split name should match '{_split_re}'' but got '{split}'." ) return f"{filename_prefix_for_name(__UpperCamelCase )}-{split}" def lowercase__( __UpperCamelCase: List[Any] ,__UpperCamelCase: Dict ,__UpperCamelCase: Tuple ,__UpperCamelCase: Optional[Any]=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = filename_prefix_for_split(__UpperCamelCase ,__UpperCamelCase ) if filetype_suffix: prefix += f".{filetype_suffix}" SCREAMING_SNAKE_CASE : str = os.path.join(__UpperCamelCase ,__UpperCamelCase ) return f"{filepath}*" def lowercase__( __UpperCamelCase: Union[str, Any] ,__UpperCamelCase: List[str] ,__UpperCamelCase: Optional[Any] ,__UpperCamelCase: List[Any]=None ,__UpperCamelCase: List[str]=None ): """simple docstring""" SCREAMING_SNAKE_CASE : str = filename_prefix_for_split(__UpperCamelCase ,__UpperCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(__UpperCamelCase ,__UpperCamelCase ) if shard_lengths: SCREAMING_SNAKE_CASE : Union[str, Any] = len(__UpperCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = [f"{prefix}-{shard_id:05d}-of-{num_shards:05d}" for shard_id in range(__UpperCamelCase )] if filetype_suffix: SCREAMING_SNAKE_CASE : Optional[int] = [filename + f".{filetype_suffix}" for filename in filenames] return filenames else: SCREAMING_SNAKE_CASE : int = prefix if filetype_suffix: filename += f".{filetype_suffix}" return [filename]
363
'''simple docstring''' import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class _a ( unittest.TestCase ): '''simple docstring''' def __init__( self, A, A=2, A=56, A=True, A=True, A=True, A=True, A=99, A=32, A=2, A=2, A=7, A="gelu_new", A=0.1, A=0.1, A=512, A=16, A=2, A=0.02, A=4, A="block_sparse", A=True, A=False, A=2, A=3, ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : List[str] = seq_length SCREAMING_SNAKE_CASE : Optional[Any] = is_training SCREAMING_SNAKE_CASE : Dict = use_attention_mask SCREAMING_SNAKE_CASE : List[Any] = use_token_type_ids SCREAMING_SNAKE_CASE : Optional[Any] = use_labels SCREAMING_SNAKE_CASE : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE : int = hidden_size SCREAMING_SNAKE_CASE : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = num_attention_heads SCREAMING_SNAKE_CASE : Dict = intermediate_size SCREAMING_SNAKE_CASE : Optional[int] = hidden_act SCREAMING_SNAKE_CASE : str = hidden_dropout_prob SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Any = max_position_embeddings SCREAMING_SNAKE_CASE : List[Any] = type_vocab_size SCREAMING_SNAKE_CASE : Any = type_sequence_label_size SCREAMING_SNAKE_CASE : List[Any] = initializer_range SCREAMING_SNAKE_CASE : Optional[Any] = num_choices SCREAMING_SNAKE_CASE : int = rescale_embeddings SCREAMING_SNAKE_CASE : Any = attention_type SCREAMING_SNAKE_CASE : str = use_bias SCREAMING_SNAKE_CASE : Tuple = block_size SCREAMING_SNAKE_CASE : List[Any] = num_random_blocks def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_attention_mask: SCREAMING_SNAKE_CASE : Dict = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size ) SCREAMING_SNAKE_CASE : List[str] = BigBirdConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=A, initializer_range=self.initializer_range, attention_type=self.attention_type, block_size=self.block_size, num_random_blocks=self.num_random_blocks, use_bias=self.use_bias, rescale_embeddings=self.rescale_embeddings, ) return config, input_ids, token_type_ids, attention_mask def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE : List[str] = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask, } return config, inputs_dict @require_flax class _a ( SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' A : str = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) A : List[Any] = False A : List[str] = False def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = FlaxBigBirdModelTester(self ) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def UpperCamelCase_ ( self ): '''simple docstring''' super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def UpperCamelCase_ ( self ): '''simple docstring''' super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def UpperCamelCase_ ( self ): '''simple docstring''' super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def UpperCamelCase_ ( self ): '''simple docstring''' super().test_hidden_states_output() @slow def UpperCamelCase_ ( self ): '''simple docstring''' for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[Any] = model_class_name.from_pretrained('google/bigbird-roberta-base' ) self.assertIsNotNone(A ) def UpperCamelCase_ ( self ): '''simple docstring''' if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE : Any = self._prepare_for_class(A, A ) SCREAMING_SNAKE_CASE : List[str] = model_class(A ) @jax.jit def model_jitted(A, A=None, **A ): return model(input_ids=A, attention_mask=A, **A ) with self.subTest('JIT Enabled' ): SCREAMING_SNAKE_CASE : List[str] = model_jitted(**A ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): SCREAMING_SNAKE_CASE : Optional[Any] = model_jitted(**A ).to_tuple() self.assertEqual(len(A ), len(A ) ) for jitted_output, output in zip(A, A ): self.assertEqual(jitted_output.shape, output.shape ) def UpperCamelCase_ ( self, A, A, A, A=1E-5, A="outputs", A=None ): '''simple docstring''' if name.startswith('outputs.attentions' ): return else: super().check_pt_flax_outputs(A, A, A, A, A, A )
246
0
'''simple docstring''' import unittest import numpy as np from datasets import load_dataset 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 BeitImageProcessor class UpperCAmelCase_ (unittest.TestCase ): """simple docstring""" 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_=4_00 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE_=False , ) -> List[str]: __lowerCamelCase : str = size if size is not None else {"height": 20, "width": 20} __lowerCamelCase : Optional[int] = crop_size if crop_size is not None else {"height": 18, "width": 18} __lowerCamelCase : Any = parent __lowerCamelCase : Union[str, Any] = batch_size __lowerCamelCase : Tuple = num_channels __lowerCamelCase : Dict = image_size __lowerCamelCase : Dict = min_resolution __lowerCamelCase : List[Any] = max_resolution __lowerCamelCase : Optional[int] = do_resize __lowerCamelCase : Optional[Any] = size __lowerCamelCase : Any = do_center_crop __lowerCamelCase : Optional[Any] = crop_size __lowerCamelCase : Dict = do_normalize __lowerCamelCase : Tuple = image_mean __lowerCamelCase : int = image_std __lowerCamelCase : Optional[Any] = do_reduce_labels def lowercase_ ( self ) -> Dict: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def UpperCAmelCase__ ( ) -> str: __lowerCamelCase : str = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) __lowerCamelCase : Any = Image.open(dataset[0]['file'] ) __lowerCamelCase : Union[str, Any] = Image.open(dataset[1]['file'] ) return image, map def UpperCAmelCase__ ( ) -> Any: __lowerCamelCase : Any = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) __lowerCamelCase : List[Any] = Image.open(ds[0]['file'] ) __lowerCamelCase : Tuple = Image.open(ds[1]['file'] ) __lowerCamelCase : List[str] = Image.open(ds[2]['file'] ) __lowerCamelCase : Optional[int] = Image.open(ds[3]['file'] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class UpperCAmelCase_ (_lowercase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Union[str, Any] = BeitImageProcessor if is_vision_available() else None def lowercase_ ( self ) -> Tuple: __lowerCamelCase : int = BeitImageProcessingTester(self ) @property def lowercase_ ( self ) -> Tuple: return self.image_processor_tester.prepare_image_processor_dict() def lowercase_ ( self ) -> Union[str, Any]: __lowerCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , 'do_resize' ) ) self.assertTrue(hasattr(__lowerCamelCase , 'size' ) ) self.assertTrue(hasattr(__lowerCamelCase , 'do_center_crop' ) ) self.assertTrue(hasattr(__lowerCamelCase , 'center_crop' ) ) self.assertTrue(hasattr(__lowerCamelCase , 'do_normalize' ) ) self.assertTrue(hasattr(__lowerCamelCase , 'image_mean' ) ) self.assertTrue(hasattr(__lowerCamelCase , 'image_std' ) ) def lowercase_ ( self ) -> Optional[Any]: __lowerCamelCase : Any = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 20, 'width': 20} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) self.assertEqual(image_processor.do_reduce_labels , __lowerCamelCase ) __lowerCamelCase : Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=__lowerCamelCase ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) self.assertEqual(image_processor.do_reduce_labels , __lowerCamelCase ) def lowercase_ ( self ) -> int: pass def lowercase_ ( self ) -> str: # Initialize image_processing __lowerCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input __lowerCamelCase : 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __lowerCamelCase : List[Any] = 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 lowercase_ ( self ) -> Any: # Initialize image_processing __lowerCamelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase : List[str] = 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 __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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __lowerCamelCase : Optional[Any] = 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 lowercase_ ( self ) -> Optional[Any]: # Initialize image_processing __lowerCamelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase : str = 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 __lowerCamelCase : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __lowerCamelCase : Tuple = 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 lowercase_ ( self ) -> Optional[Any]: # Initialize image_processing __lowerCamelCase : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) __lowerCamelCase : Optional[int] = [] for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input __lowerCamelCase : Dict = image_processing(image_inputs[0] , maps[0] , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 2_55 ) # Test batched __lowerCamelCase : Tuple = image_processing(__lowerCamelCase , __lowerCamelCase , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].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'], ) , ) self.assertEqual( encoding['labels'].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 2_55 ) # Test not batched input (PIL images) __lowerCamelCase : Optional[int] = prepare_semantic_single_inputs() __lowerCamelCase : Any = image_processing(__lowerCamelCase , __lowerCamelCase , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 2_55 ) # Test batched input (PIL images) __lowerCamelCase : Union[str, Any] = prepare_semantic_batch_inputs() __lowerCamelCase : Dict = image_processing(__lowerCamelCase , __lowerCamelCase , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 2, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 2_55 ) def lowercase_ ( self ) -> Union[str, Any]: # Initialize image_processing __lowerCamelCase : Dict = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 __lowerCamelCase : Optional[int] = prepare_semantic_single_inputs() __lowerCamelCase : Dict = image_processing(__lowerCamelCase , __lowerCamelCase , return_tensors='pt' ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 1_50 ) __lowerCamelCase : int = True __lowerCamelCase : List[str] = image_processing(__lowerCamelCase , __lowerCamelCase , return_tensors='pt' ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 2_55 )
185
def _UpperCamelCase ( snake_case__ ) -> bool: if not isinstance(snake_case__, snake_case__ ): raise ValueError("check_bouncy() accepts only integer arguments" ) __UpperCAmelCase : Optional[int] = str(snake_case__ ) __UpperCAmelCase : Any = "".join(sorted(snake_case__ ) ) return sorted_str_n != str_n and sorted_str_n[::-1] != str_n def _UpperCamelCase ( snake_case__ = 99 ) -> int: if not 0 < percent < 100: raise ValueError("solution() only accepts values from 0 to 100" ) __UpperCAmelCase : List[str] = 0 __UpperCAmelCase : int = 1 while True: if check_bouncy(snake_case__ ): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(F'{solution(99)}')
157
0
import numpy as np def a__ ( _SCREAMING_SNAKE_CASE : np.array ) -> np.array: """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
356
'''simple docstring''' from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder _lowerCamelCase = datasets.utils.logging.get_logger(__name__) class _snake_case (folder_based_builder.FolderBasedBuilderConfig): __A : bool =None __A : bool =None class _snake_case (folder_based_builder.FolderBasedBuilder): __A : Union[str, Any] =datasets.Audio() __A : Optional[int] ="audio" __A : Any =AudioFolderConfig __A : List[str] # definition at the bottom of the script __A : Optional[int] =AudioClassification(audio_column="audio" , label_column="label") _lowerCamelCase = [ """.aiff""", """.au""", """.avr""", """.caf""", """.flac""", """.htk""", """.svx""", """.mat4""", """.mat5""", """.mpc2k""", """.ogg""", """.paf""", """.pvf""", """.raw""", """.rf64""", """.sd2""", """.sds""", """.ircam""", """.voc""", """.w64""", """.wav""", """.nist""", """.wavex""", """.wve""", """.xi""", """.mp3""", """.opus""", ] _lowerCamelCase = AUDIO_EXTENSIONS
67
0
"""simple docstring""" import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class __snake_case ( _lowercase): snake_case__ : List[Any] = "MCTCTFeatureExtractor" snake_case__ : Optional[int] = "AutoTokenizer" def __init__( self : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" super().__init__(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Optional[Any] = self.feature_extractor _lowerCamelCase : Optional[Any] = False def __call__( self : Optional[int] , *__lowerCAmelCase : Dict , **__lowerCAmelCase : str ): """simple docstring""" if self._in_target_context_manager: return self.current_processor(*__lowerCAmelCase , **__lowerCAmelCase ) if "raw_speech" in kwargs: warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' ) _lowerCamelCase : str = kwargs.pop('''raw_speech''' ) else: _lowerCamelCase : str = kwargs.pop('''audio''' , __lowerCAmelCase ) _lowerCamelCase : Dict = kwargs.pop('''sampling_rate''' , __lowerCAmelCase ) _lowerCamelCase : List[str] = kwargs.pop('''text''' , __lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: _lowerCamelCase : Optional[Any] = args[0] _lowerCamelCase : str = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if audio is not None: _lowerCamelCase : str = self.feature_extractor(__lowerCAmelCase , *__lowerCAmelCase , sampling_rate=__lowerCAmelCase , **__lowerCAmelCase ) if text is not None: _lowerCamelCase : Union[str, Any] = self.tokenizer(__lowerCAmelCase , **__lowerCAmelCase ) if text is None: return inputs elif audio is None: return encodings else: _lowerCamelCase : Dict = encodings['''input_ids'''] return inputs def SCREAMING_SNAKE_CASE ( self : Dict , *__lowerCAmelCase : List[Any] , **__lowerCAmelCase : int ): """simple docstring""" return self.tokenizer.batch_decode(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , *__lowerCAmelCase : Union[str, Any] , **__lowerCAmelCase : Optional[int] ): """simple docstring""" if self._in_target_context_manager: return self.current_processor.pad(*__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Tuple = kwargs.pop('''input_features''' , __lowerCAmelCase ) _lowerCamelCase : int = kwargs.pop('''labels''' , __lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: _lowerCamelCase : List[str] = args[0] _lowerCamelCase : Optional[int] = args[1:] if input_features is not None: _lowerCamelCase : int = self.feature_extractor.pad(__lowerCAmelCase , *__lowerCAmelCase , **__lowerCAmelCase ) if labels is not None: _lowerCamelCase : Tuple = self.tokenizer.pad(__lowerCAmelCase , **__lowerCAmelCase ) if labels is None: return input_features elif input_features is None: return labels else: _lowerCamelCase : Any = labels['''input_ids'''] return input_features def SCREAMING_SNAKE_CASE ( self : List[Any] , *__lowerCAmelCase : Any , **__lowerCAmelCase : Union[str, Any] ): """simple docstring""" return self.tokenizer.decode(*__lowerCAmelCase , **__lowerCAmelCase ) @contextmanager def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" warnings.warn( '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ''' '''labels by using the argument `text` of the regular `__call__` method (either in the same call as ''' '''your audio inputs, or in a separate call.''' ) _lowerCamelCase : Tuple = True _lowerCamelCase : str = self.tokenizer yield _lowerCamelCase : Union[str, Any] = self.feature_extractor _lowerCamelCase : Optional[Any] = False
72
def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Any = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase :List[str] = True for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase :List[Any] = True if a[i].islower(): UpperCamelCase :List[Any] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
259
0
import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) a__ : Tuple = logging.getLogger(__name__) def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = git.Repo(search_parent_directories=a__ ) SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(a__ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), } with open(os.path.join(a__ , '''git_log.json''' ) , '''w''' ) as f: json.dump(a__ , a__ , indent=4 ) def UpperCAmelCase_( a__ ): """simple docstring""" if params.n_gpu <= 0: SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : Optional[int] = -1 SCREAMING_SNAKE_CASE : Optional[Any] = True SCREAMING_SNAKE_CASE : Optional[Any] = False return assert torch.cuda.is_available() logger.info('''Initializing GPUs''' ) if params.n_gpu > 1: assert params.local_rank != -1 SCREAMING_SNAKE_CASE : Tuple = int(os.environ['''WORLD_SIZE'''] ) SCREAMING_SNAKE_CASE : Optional[int] = int(os.environ['''N_GPU_NODE'''] ) SCREAMING_SNAKE_CASE : List[Any] = int(os.environ['''RANK'''] ) # number of nodes / node ID SCREAMING_SNAKE_CASE : List[Any] = params.world_size // params.n_gpu_per_node SCREAMING_SNAKE_CASE : Optional[int] = params.global_rank // params.n_gpu_per_node SCREAMING_SNAKE_CASE : Optional[Any] = True assert params.n_nodes == int(os.environ['''N_NODES'''] ) assert params.node_id == int(os.environ['''NODE_RANK'''] ) # local job (single GPU) else: assert params.local_rank == -1 SCREAMING_SNAKE_CASE : List[str] = 1 SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : Any = 1 SCREAMING_SNAKE_CASE : List[str] = 1 SCREAMING_SNAKE_CASE : Dict = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode SCREAMING_SNAKE_CASE : str = params.node_id == 0 and params.local_rank == 0 SCREAMING_SNAKE_CASE : Union[str, Any] = params.n_nodes > 1 # summary SCREAMING_SNAKE_CASE : Optional[Any] = F"""--- Global rank: {params.global_rank} - """ logger.info(PREFIX + '''Number of nodes: %i''' % params.n_nodes ) logger.info(PREFIX + '''Node ID : %i''' % params.node_id ) logger.info(PREFIX + '''Local rank : %i''' % params.local_rank ) logger.info(PREFIX + '''World size : %i''' % params.world_size ) logger.info(PREFIX + '''GPUs per node : %i''' % params.n_gpu_per_node ) logger.info(PREFIX + '''Master : %s''' % str(params.is_master ) ) logger.info(PREFIX + '''Multi-node : %s''' % str(params.multi_node ) ) logger.info(PREFIX + '''Multi-GPU : %s''' % str(params.multi_gpu ) ) logger.info(PREFIX + '''Hostname : %s''' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('''Initializing PyTorch distributed''' ) torch.distributed.init_process_group( init_method='''env://''' , backend='''nccl''' , ) def UpperCAmelCase_( a__ ): """simple docstring""" np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
19
from sklearn.metrics import matthews_corrcoef import datasets a__ : Optional[Any] = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' a__ : str = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' a__ : Union[str, Any] = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self ) ->Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html''' ] , ) def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None ) ->List[str]: return { "matthews_correlation": float(matthews_corrcoef(_lowerCamelCase , _lowerCamelCase , sample_weight=_lowerCamelCase ) ), }
19
1
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig __A : Any = logging.get_logger(__name__) # General docstring __A : int = '''RegNetConfig''' # Base docstring __A : Dict = '''facebook/regnet-y-040''' __A : Union[str, Any] = [1, 1_088, 7, 7] # Image classification docstring __A : List[str] = '''facebook/regnet-y-040''' __A : Optional[Any] = '''tabby, tabby cat''' __A : int = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class _UpperCAmelCase ( tf.keras.layers.Layer ): def __init__( self : Tuple , A : int , A : int = 3 , A : int = 1 , A : int = 1 , A : Optional[str] = "relu" , **A : str , ) -> Dict: super().__init__(**A ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb lowercase_ : int = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) lowercase_ : Any = tf.keras.layers.ConvaD( filters=A , kernel_size=A , strides=A , padding='''VALID''' , groups=A , use_bias=A , name='''convolution''' , ) lowercase_ : Tuple = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) lowercase_ : Union[str, Any] = ACTaFN[activation] if activation is not None else tf.identity def A ( self : Union[str, Any] , A : List[Any] ) -> Any: lowercase_ : Union[str, Any] = self.convolution(self.padding(A ) ) lowercase_ : Tuple = self.normalization(A ) lowercase_ : List[str] = self.activation(A ) return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , A : RegNetConfig , **A : Dict ) -> Optional[Any]: super().__init__(**A ) lowercase_ : Any = config.num_channels lowercase_ : List[str] = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='''embedder''' , ) def A ( self : Optional[int] , A : Dict ) -> Optional[Any]: lowercase_ : Dict = shape_list(A )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) lowercase_ : List[str] = tf.transpose(A , perm=(0, 2, 3, 1) ) lowercase_ : Union[str, Any] = self.embedder(A ) return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): def __init__( self : Tuple , A : int , A : int = 2 , **A : Optional[Any] ) -> Tuple: super().__init__(**A ) lowercase_ : Tuple = tf.keras.layers.ConvaD( filters=A , kernel_size=1 , strides=A , use_bias=A , name='''convolution''' ) lowercase_ : Tuple = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) def A ( self : Optional[Any] , A : tf.Tensor , A : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(A ) , training=A ) class _UpperCAmelCase ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , A : int , A : int , **A : Union[str, Any] ) -> Optional[Any]: super().__init__(**A ) lowercase_ : Optional[Any] = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A , name='''pooler''' ) lowercase_ : Dict = [ tf.keras.layers.ConvaD(filters=A , kernel_size=1 , activation='''relu''' , name='''attention.0''' ), tf.keras.layers.ConvaD(filters=A , kernel_size=1 , activation='''sigmoid''' , name='''attention.2''' ), ] def A ( self : Tuple , A : Union[str, Any] ) -> List[Any]: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] lowercase_ : Dict = self.pooler(A ) for layer_module in self.attention: lowercase_ : List[Any] = layer_module(A ) lowercase_ : List[str] = hidden_state * pooled return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): def __init__( self : List[Any] , A : RegNetConfig , A : int , A : int , A : int = 1 , **A : Optional[Any] ) -> Dict: super().__init__(**A ) lowercase_ : str = in_channels != out_channels or stride != 1 lowercase_ : List[str] = max(1 , out_channels // config.groups_width ) lowercase_ : Dict = ( TFRegNetShortCut(A , stride=A , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. lowercase_ : Optional[Any] = [ TFRegNetConvLayer(A , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( A , stride=A , groups=A , activation=config.hidden_act , name='''layer.1''' ), TFRegNetConvLayer(A , kernel_size=1 , activation=A , name='''layer.2''' ), ] lowercase_ : Union[str, Any] = ACTaFN[config.hidden_act] def A ( self : Tuple , A : List[Any] ) -> Any: lowercase_ : str = hidden_state for layer_module in self.layers: lowercase_ : Union[str, Any] = layer_module(A ) lowercase_ : List[Any] = self.shortcut(A ) hidden_state += residual lowercase_ : Tuple = self.activation(A ) return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): def __init__( self : List[str] , A : RegNetConfig , A : int , A : int , A : int = 1 , **A : List[Any] ) -> str: super().__init__(**A ) lowercase_ : List[str] = in_channels != out_channels or stride != 1 lowercase_ : List[Any] = max(1 , out_channels // config.groups_width ) lowercase_ : Union[str, Any] = ( TFRegNetShortCut(A , stride=A , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) lowercase_ : Optional[int] = [ TFRegNetConvLayer(A , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( A , stride=A , groups=A , activation=config.hidden_act , name='''layer.1''' ), TFRegNetSELayer(A , reduced_channels=int(round(in_channels / 4 ) ) , name='''layer.2''' ), TFRegNetConvLayer(A , kernel_size=1 , activation=A , name='''layer.3''' ), ] lowercase_ : int = ACTaFN[config.hidden_act] def A ( self : int , A : Any ) -> Tuple: lowercase_ : Optional[int] = hidden_state for layer_module in self.layers: lowercase_ : Optional[Any] = layer_module(A ) lowercase_ : Optional[Any] = self.shortcut(A ) hidden_state += residual lowercase_ : Optional[Any] = self.activation(A ) return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): def __init__( self : List[str] , A : RegNetConfig , A : int , A : int , A : int = 2 , A : int = 2 , **A : Optional[int] ) -> Tuple: super().__init__(**A ) lowercase_ : Dict = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer lowercase_ : Any = [ # downsampling is done in the first layer with stride of 2 layer(A , A , A , stride=A , name='''layers.0''' ), *[layer(A , A , A , name=F'''layers.{i+1}''' ) for i in range(depth - 1 )], ] def A ( self : List[Any] , A : Dict ) -> Any: for layer_module in self.layers: lowercase_ : Dict = layer_module(A ) return hidden_state class _UpperCAmelCase ( tf.keras.layers.Layer ): def __init__( self : int , A : RegNetConfig , **A : str ) -> List[str]: super().__init__(**A ) lowercase_ : Union[str, Any] = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( A , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='''stages.0''' , ) ) lowercase_ : Tuple = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(A , config.depths[1:] ) ): self.stages.append(TFRegNetStage(A , A , A , depth=A , name=F'''stages.{i+1}''' ) ) def A ( self : Dict , A : tf.Tensor , A : bool = False , A : bool = True ) -> TFBaseModelOutputWithNoAttention: lowercase_ : Dict = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowercase_ : Dict = hidden_states + (hidden_state,) lowercase_ : int = stage_module(A ) if output_hidden_states: lowercase_ : Tuple = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=A , hidden_states=A ) @keras_serializable class _UpperCAmelCase ( tf.keras.layers.Layer ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = RegNetConfig def __init__( self : Dict , A : int , **A : Dict ) -> Optional[Any]: super().__init__(**A ) lowercase_ : Optional[Any] = config lowercase_ : Any = TFRegNetEmbeddings(A , name='''embedder''' ) lowercase_ : str = TFRegNetEncoder(A , name='''encoder''' ) lowercase_ : Dict = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A , name='''pooler''' ) @unpack_inputs def A ( self : Union[str, Any] , A : tf.Tensor , A : Optional[bool] = None , A : Optional[bool] = None , A : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: lowercase_ : str = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowercase_ : Dict = return_dict if return_dict is not None else self.config.use_return_dict lowercase_ : Optional[int] = self.embedder(A , training=A ) lowercase_ : int = self.encoder( A , output_hidden_states=A , return_dict=A , training=A ) lowercase_ : Union[str, Any] = encoder_outputs[0] lowercase_ : Optional[int] = self.pooler(A ) # Change to NCHW output format have uniformity in the modules lowercase_ : List[Any] = tf.transpose(A , perm=(0, 3, 1, 2) ) lowercase_ : Union[str, Any] = tf.transpose(A , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: lowercase_ : Any = tuple([tf.transpose(A , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=A , pooler_output=A , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class _UpperCAmelCase ( _A ): SCREAMING_SNAKE_CASE_ : Optional[Any] = RegNetConfig SCREAMING_SNAKE_CASE_ : List[Any] = "regnet" SCREAMING_SNAKE_CASE_ : str = "pixel_values" @property def A ( self : Tuple ) -> List[Any]: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) , dtype=tf.floataa )} __A : Optional[Any] = R''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): 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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' __A : int = R''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , _A , ) class _UpperCAmelCase ( _A ): def __init__( self : Tuple , A : RegNetConfig , *A : Union[str, Any] , **A : List[str] ) -> Optional[Any]: super().__init__(A , *A , **A ) lowercase_ : Any = TFRegNetMainLayer(A , name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=A , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def A ( self : Tuple , A : tf.Tensor , A : Optional[bool] = None , A : Optional[bool] = None , A : Dict=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: lowercase_ : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowercase_ : Dict = return_dict if return_dict is not None else self.config.use_return_dict lowercase_ : List[str] = self.regnet( pixel_values=A , output_hidden_states=A , return_dict=A , training=A , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , _A , ) class _UpperCAmelCase ( _A , _A ): def __init__( self : Union[str, Any] , A : RegNetConfig , *A : Optional[Any] , **A : Union[str, Any] ) -> int: super().__init__(A , *A , **A ) lowercase_ : Optional[Any] = config.num_labels lowercase_ : List[str] = TFRegNetMainLayer(A , name='''regnet''' ) # classification head lowercase_ : Optional[int] = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def A ( self : Optional[Any] , A : tf.Tensor = None , A : tf.Tensor = None , A : bool = None , A : bool = None , A : Union[str, Any]=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: lowercase_ : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowercase_ : List[str] = return_dict if return_dict is not None else self.config.use_return_dict lowercase_ : Any = self.regnet( A , output_hidden_states=A , return_dict=A , training=A ) lowercase_ : List[Any] = outputs.pooler_output if return_dict else outputs[1] lowercase_ : Any = self.classifier[0](A ) lowercase_ : Dict = self.classifier[1](A ) lowercase_ : Union[str, Any] = None if labels is None else self.hf_compute_loss(labels=A , logits=A ) if not return_dict: lowercase_ : Any = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=A , logits=A , hidden_states=outputs.hidden_states )
33
'''simple docstring''' from __future__ import annotations import math a_ = '2020.9.26' a_ = 'xcodz-dot, cclaus, dhruvmanila' def _a( UpperCamelCase__ : float, UpperCamelCase__ : float, UpperCamelCase__ : float, UpperCamelCase__ : float, UpperCamelCase__ : float ): '''simple docstring''' if not all(isinstance(UpperCamelCase__, (float, int) ) for val in locals().values() ): SCREAMING_SNAKE_CASE__ : int =f"Input values must either be float or int: {list(locals().values() )}" raise TypeError(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict =((x * distance) / (z + distance)) * scale SCREAMING_SNAKE_CASE__ : Tuple =((y * distance) / (z + distance)) * scale return projected_x, projected_y def _a( UpperCamelCase__ : float, UpperCamelCase__ : float, UpperCamelCase__ : float, UpperCamelCase__ : str, UpperCamelCase__ : float ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ): raise TypeError('''Axis must be a str''' ) SCREAMING_SNAKE_CASE__ : List[Any] =locals() del input_variables["axis"] if not all(isinstance(UpperCamelCase__, (float, int) ) for val in input_variables.values() ): SCREAMING_SNAKE_CASE__ : List[str] =( '''Input values except axis must either be float or int: ''' f"{list(input_variables.values() )}" ) raise TypeError(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple =(angle % 3_6_0) / 4_5_0 * 1_8_0 / math.pi if axis == "z": SCREAMING_SNAKE_CASE__ : str =x * math.cos(UpperCamelCase__ ) - y * math.sin(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Tuple =y * math.cos(UpperCamelCase__ ) + x * math.sin(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : str =z elif axis == "x": SCREAMING_SNAKE_CASE__ : Dict =y * math.cos(UpperCamelCase__ ) - z * math.sin(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] =z * math.cos(UpperCamelCase__ ) + y * math.sin(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =x elif axis == "y": SCREAMING_SNAKE_CASE__ : Tuple =x * math.cos(UpperCamelCase__ ) - z * math.sin(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] =z * math.cos(UpperCamelCase__ ) + x * math.sin(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[Any] =y else: raise ValueError('''not a valid axis, choose one of \'x\', \'y\', \'z\'''' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(F'''{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }''') print(F'''{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }''')
152
0
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={"vocab_file": "vocab.json", "merges_file": "merges.txt"} __UpperCAmelCase ={ "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } __UpperCAmelCase ={ "allenai/longformer-base-4096": 4_0_9_6, "allenai/longformer-large-4096": 4_0_9_6, "allenai/longformer-large-4096-finetuned-triviaqa": 4_0_9_6, "allenai/longformer-base-4096-extra.pos.embd.only": 4_0_9_6, "allenai/longformer-large-4096-extra.pos.embd.only": 4_0_9_6, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def __lowerCAmelCase ( ) -> Optional[int]: __lowerCamelCase = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __lowerCamelCase = bs[:] __lowerCamelCase = 0 for b in range(2**8 ): if b not in bs: bs.append(UpperCamelCase__ ) cs.append(2**8 + n ) n += 1 __lowerCamelCase = [chr(UpperCamelCase__ ) for n in cs] return dict(zip(UpperCamelCase__ , UpperCamelCase__ ) ) def __lowerCAmelCase ( UpperCamelCase__ ) -> List[str]: __lowerCamelCase = set() __lowerCamelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowerCamelCase = char return pairs class a__ ( UpperCAmelCase__ ): lowerCamelCase : Dict =VOCAB_FILES_NAMES lowerCamelCase : Optional[Any] =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : Union[str, Any] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : List[Any] =["input_ids", "attention_mask"] def __init__( self : str , a : List[str] , a : Any , a : Optional[int]="replace" , a : List[Any]="<s>" , a : List[str]="</s>" , a : Dict="</s>" , a : str="<s>" , a : Union[str, Any]="<unk>" , a : Any="<pad>" , a : Union[str, Any]="<mask>" , a : Dict=False , **a : int , ): """simple docstring""" __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else bos_token __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else eos_token __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else sep_token __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else cls_token __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else unk_token __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else mask_token super().__init__( errors=a , bos_token=a , eos_token=a , unk_token=a , sep_token=a , cls_token=a , pad_token=a , mask_token=a , add_prefix_space=a , **a , ) with open(a , encoding='''utf-8''' ) as vocab_handle: __lowerCamelCase = json.load(a ) __lowerCamelCase = {v: k for k, v in self.encoder.items()} __lowerCamelCase = errors # how to handle errors in decoding __lowerCamelCase = bytes_to_unicode() __lowerCamelCase = {v: k for k, v in self.byte_encoder.items()} with open(a , encoding='''utf-8''' ) as merges_handle: __lowerCamelCase = merges_handle.read().split('''\n''' )[1:-1] __lowerCamelCase = [tuple(merge.split() ) for merge in bpe_merges] __lowerCamelCase = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase = {} __lowerCamelCase = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __lowerCamelCase = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" return len(self.encoder ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : int ): """simple docstring""" if token in self.cache: return self.cache[token] __lowerCamelCase = tuple(a ) __lowerCamelCase = get_pairs(a ) if not pairs: return token while True: __lowerCamelCase = min(a , key=lambda a : self.bpe_ranks.get(a , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __lowerCamelCase , __lowerCamelCase = bigram __lowerCamelCase = [] __lowerCamelCase = 0 while i < len(a ): try: __lowerCamelCase = word.index(a , a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __lowerCamelCase = j if word[i] == first and i < len(a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __lowerCamelCase = tuple(a ) __lowerCamelCase = new_word if len(a ) == 1: break else: __lowerCamelCase = get_pairs(a ) __lowerCamelCase = ''' '''.join(a ) __lowerCamelCase = word return word def SCREAMING_SNAKE_CASE__ ( self : str , a : Optional[Any] ): """simple docstring""" __lowerCamelCase = [] for token in re.findall(self.pat , a ): __lowerCamelCase = ''''''.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(a ).split(''' ''' ) ) return bpe_tokens def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , a : Tuple ): """simple docstring""" return self.encoder.get(a , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE__ ( self : Any , a : Tuple ): """simple docstring""" return self.decoder.get(a ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = ''''''.join(a ) __lowerCamelCase = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def SCREAMING_SNAKE_CASE__ ( self : List[str] , a : str , a : Optional[str] = None ): """simple docstring""" if not os.path.isdir(a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase = os.path.join( a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __lowerCamelCase = os.path.join( a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(a , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=a , ensure_ascii=a ) + '''\n''' ) __lowerCamelCase = 0 with open(a , '''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 a : 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!''' ) __lowerCamelCase = token_index writer.write(''' '''.join(a ) + '''\n''' ) index += 1 return vocab_file, merge_file def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] __lowerCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self : Dict , a : List[int] , a : Optional[List[int]] = None , a : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a , token_ids_a=a , already_has_special_tokens=a ) if token_ids_a is None: return [1] + ([0] * len(a )) + [1] return [1] + ([0] * len(a )) + [1, 1] + ([0] * len(a )) + [1] def SCREAMING_SNAKE_CASE__ ( self : List[str] , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" __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 + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : Dict , a : Any=False , **a : Any ): """simple docstring""" __lowerCamelCase = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(a ) > 0 and not text[0].isspace()): __lowerCamelCase = ''' ''' + text return (text, kwargs)
237
'''simple docstring''' from bisect import bisect from itertools import accumulate def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> str: __lowerCamelCase = sorted(zip(UpperCamelCase__ , UpperCamelCase__ ) , key=lambda UpperCamelCase__ : x[0] / x[1] , reverse=UpperCamelCase__ ) __lowerCamelCase , __lowerCamelCase = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase = list(accumulate(UpperCamelCase__ ) ) __lowerCamelCase = bisect(UpperCamelCase__ , UpperCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
237
1
def lowerCAmelCase ( lowerCAmelCase_ )-> int: lowerCAmelCase_ : list[list[int]] = [[0 for _ in range(lowerCAmelCase_ )] for _ in range(m + 1 )] for i in range(m + 1 ): lowerCAmelCase_ : Optional[Any] = 1 for n in range(m + 1 ): for k in range(1 , lowerCAmelCase_ ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: _UpperCAmelCase : Any =int(input("""Enter a number: """).strip()) print(partition(n)) except ValueError: print("""Please enter a number.""") else: try: _UpperCAmelCase : Optional[Any] =int(sys.argv[1]) print(partition(n)) except ValueError: print("""Please pass a number.""")
262
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: _UpperCAmelCase : Tuple =None _UpperCAmelCase : int =logging.get_logger(__name__) _UpperCAmelCase : Dict ={"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} _UpperCAmelCase : Any ={ """vocab_file""": { """facebook/nllb-200-distilled-600M""": ( """https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model""" ), }, """tokenizer_file""": { """facebook/nllb-200-distilled-600M""": ( """https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json""" ), }, } _UpperCAmelCase : int ={ """facebook/nllb-large-en-ro""": 1024, """facebook/nllb-200-distilled-600M""": 1024, } # fmt: off _UpperCAmelCase : Any =["""ace_Arab""", """ace_Latn""", """acm_Arab""", """acq_Arab""", """aeb_Arab""", """afr_Latn""", """ajp_Arab""", """aka_Latn""", """amh_Ethi""", """apc_Arab""", """arb_Arab""", """ars_Arab""", """ary_Arab""", """arz_Arab""", """asm_Beng""", """ast_Latn""", """awa_Deva""", """ayr_Latn""", """azb_Arab""", """azj_Latn""", """bak_Cyrl""", """bam_Latn""", """ban_Latn""", """bel_Cyrl""", """bem_Latn""", """ben_Beng""", """bho_Deva""", """bjn_Arab""", """bjn_Latn""", """bod_Tibt""", """bos_Latn""", """bug_Latn""", """bul_Cyrl""", """cat_Latn""", """ceb_Latn""", """ces_Latn""", """cjk_Latn""", """ckb_Arab""", """crh_Latn""", """cym_Latn""", """dan_Latn""", """deu_Latn""", """dik_Latn""", """dyu_Latn""", """dzo_Tibt""", """ell_Grek""", """eng_Latn""", """epo_Latn""", """est_Latn""", """eus_Latn""", """ewe_Latn""", """fao_Latn""", """pes_Arab""", """fij_Latn""", """fin_Latn""", """fon_Latn""", """fra_Latn""", """fur_Latn""", """fuv_Latn""", """gla_Latn""", """gle_Latn""", """glg_Latn""", """grn_Latn""", """guj_Gujr""", """hat_Latn""", """hau_Latn""", """heb_Hebr""", """hin_Deva""", """hne_Deva""", """hrv_Latn""", """hun_Latn""", """hye_Armn""", """ibo_Latn""", """ilo_Latn""", """ind_Latn""", """isl_Latn""", """ita_Latn""", """jav_Latn""", """jpn_Jpan""", """kab_Latn""", """kac_Latn""", """kam_Latn""", """kan_Knda""", """kas_Arab""", """kas_Deva""", """kat_Geor""", """knc_Arab""", """knc_Latn""", """kaz_Cyrl""", """kbp_Latn""", """kea_Latn""", """khm_Khmr""", """kik_Latn""", """kin_Latn""", """kir_Cyrl""", """kmb_Latn""", """kon_Latn""", """kor_Hang""", """kmr_Latn""", """lao_Laoo""", """lvs_Latn""", """lij_Latn""", """lim_Latn""", """lin_Latn""", """lit_Latn""", """lmo_Latn""", """ltg_Latn""", """ltz_Latn""", """lua_Latn""", """lug_Latn""", """luo_Latn""", """lus_Latn""", """mag_Deva""", """mai_Deva""", """mal_Mlym""", """mar_Deva""", """min_Latn""", """mkd_Cyrl""", """plt_Latn""", """mlt_Latn""", """mni_Beng""", """khk_Cyrl""", """mos_Latn""", """mri_Latn""", """zsm_Latn""", """mya_Mymr""", """nld_Latn""", """nno_Latn""", """nob_Latn""", """npi_Deva""", """nso_Latn""", """nus_Latn""", """nya_Latn""", """oci_Latn""", """gaz_Latn""", """ory_Orya""", """pag_Latn""", """pan_Guru""", """pap_Latn""", """pol_Latn""", """por_Latn""", """prs_Arab""", """pbt_Arab""", """quy_Latn""", """ron_Latn""", """run_Latn""", """rus_Cyrl""", """sag_Latn""", """san_Deva""", """sat_Beng""", """scn_Latn""", """shn_Mymr""", """sin_Sinh""", """slk_Latn""", """slv_Latn""", """smo_Latn""", """sna_Latn""", """snd_Arab""", """som_Latn""", """sot_Latn""", """spa_Latn""", """als_Latn""", """srd_Latn""", """srp_Cyrl""", """ssw_Latn""", """sun_Latn""", """swe_Latn""", """swh_Latn""", """szl_Latn""", """tam_Taml""", """tat_Cyrl""", """tel_Telu""", """tgk_Cyrl""", """tgl_Latn""", """tha_Thai""", """tir_Ethi""", """taq_Latn""", """taq_Tfng""", """tpi_Latn""", """tsn_Latn""", """tso_Latn""", """tuk_Latn""", """tum_Latn""", """tur_Latn""", """twi_Latn""", """tzm_Tfng""", """uig_Arab""", """ukr_Cyrl""", """umb_Latn""", """urd_Arab""", """uzn_Latn""", """vec_Latn""", """vie_Latn""", """war_Latn""", """wol_Latn""", """xho_Latn""", """ydd_Hebr""", """yor_Latn""", """yue_Hant""", """zho_Hans""", """zho_Hant""", """zul_Latn"""] class snake_case__( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ : Dict = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ : Optional[Any] = ["""input_ids""", """attention_mask"""] SCREAMING_SNAKE_CASE__ : int = NllbTokenizer SCREAMING_SNAKE_CASE__ : List[int] = [] SCREAMING_SNAKE_CASE__ : List[int] = [] def __init__( self , __lowercase=None , __lowercase=None , __lowercase="<s>" , __lowercase="</s>" , __lowercase="</s>" , __lowercase="<s>" , __lowercase="<unk>" , __lowercase="<pad>" , __lowercase="<mask>" , __lowercase=None , __lowercase=None , __lowercase=None , __lowercase=False , **__lowercase , ) -> int: # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase_ : int = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token lowerCAmelCase_ : List[Any] = legacy_behaviour super().__init__( vocab_file=__lowercase , tokenizer_file=__lowercase , bos_token=__lowercase , eos_token=__lowercase , sep_token=__lowercase , cls_token=__lowercase , unk_token=__lowercase , pad_token=__lowercase , mask_token=__lowercase , src_lang=__lowercase , tgt_lang=__lowercase , additional_special_tokens=__lowercase , legacy_behaviour=__lowercase , **__lowercase , ) lowerCAmelCase_ : Any = vocab_file lowerCAmelCase_ : List[Any] = False if not self.vocab_file else True lowerCAmelCase_ : Optional[Any] = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) lowerCAmelCase_ : Optional[Any] = { lang_code: self.convert_tokens_to_ids(__lowercase ) for lang_code in FAIRSEQ_LANGUAGE_CODES } lowerCAmelCase_ : Any = src_lang if src_lang is not None else '''eng_Latn''' lowerCAmelCase_ : str = self.convert_tokens_to_ids(self._src_lang ) lowerCAmelCase_ : Optional[int] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def lowercase_ ( self ) -> str: return self._src_lang @src_lang.setter def lowercase_ ( self , __lowercase ) -> None: lowerCAmelCase_ : Any = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def lowercase_ ( self , __lowercase , __lowercase = None ) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def lowercase_ ( self , __lowercase , __lowercase = None ) -> List[int]: lowerCAmelCase_ : Optional[Any] = [self.sep_token_id] lowerCAmelCase_ : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowercase_ ( self , __lowercase , __lowercase , __lowercase , __lowercase , **__lowercase ) -> str: if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowerCAmelCase_ : List[str] = src_lang lowerCAmelCase_ : int = self(__lowercase , add_special_tokens=__lowercase , return_tensors=__lowercase , **__lowercase ) lowerCAmelCase_ : Dict = self.convert_tokens_to_ids(__lowercase ) lowerCAmelCase_ : List[Any] = tgt_lang_id return inputs def lowercase_ ( self , __lowercase , __lowercase = "eng_Latn" , __lowercase = None , __lowercase = "fra_Latn" , **__lowercase , ) -> BatchEncoding: lowerCAmelCase_ : List[str] = src_lang lowerCAmelCase_ : List[str] = tgt_lang return super().prepare_seqaseq_batch(__lowercase , __lowercase , **__lowercase ) def lowercase_ ( self ) -> List[Any]: return self.set_src_lang_special_tokens(self.src_lang ) def lowercase_ ( self ) -> str: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def lowercase_ ( self , __lowercase ) -> None: lowerCAmelCase_ : List[str] = self.convert_tokens_to_ids(__lowercase ) if self.legacy_behaviour: lowerCAmelCase_ : Any = [] lowerCAmelCase_ : List[str] = [self.eos_token_id, self.cur_lang_code] else: lowerCAmelCase_ : Optional[int] = [self.cur_lang_code] lowerCAmelCase_ : List[Any] = [self.eos_token_id] lowerCAmelCase_ : Any = self.convert_ids_to_tokens(self.prefix_tokens ) lowerCAmelCase_ : List[Any] = self.convert_ids_to_tokens(self.suffix_tokens ) lowerCAmelCase_ : Any = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def lowercase_ ( self , __lowercase ) -> None: lowerCAmelCase_ : Dict = self.convert_tokens_to_ids(__lowercase ) if self.legacy_behaviour: lowerCAmelCase_ : List[Any] = [] lowerCAmelCase_ : Any = [self.eos_token_id, self.cur_lang_code] else: lowerCAmelCase_ : Any = [self.cur_lang_code] lowerCAmelCase_ : Any = [self.eos_token_id] lowerCAmelCase_ : List[Any] = self.convert_ids_to_tokens(self.prefix_tokens ) lowerCAmelCase_ : Tuple = self.convert_ids_to_tokens(self.suffix_tokens ) lowerCAmelCase_ : Optional[Any] = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def lowercase_ ( self , __lowercase , __lowercase = None ) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(__lowercase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory.""" ) return lowerCAmelCase_ : Any = os.path.join( __lowercase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ): copyfile(self.vocab_file , __lowercase ) return (out_vocab_file,)
262
1
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, 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_vision_available, logging if is_vision_available(): import PIL lowercase : Union[str, Any] = logging.get_logger(__name__) class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' A : List[Any] = ['pixel_values'] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PIL.Image.BICUBIC , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> None: super().__init__(**_SCREAMING_SNAKE_CASE ) snake_case_ : Optional[Any] = size if size is not None else {"height": 256, "width": 256} snake_case_ : int = get_size_dict(_SCREAMING_SNAKE_CASE ) snake_case_ : Tuple = crop_size if crop_size is not None else {"height": 224, "width": 224} snake_case_ : Dict = get_size_dict(_SCREAMING_SNAKE_CASE , param_name="crop_size" ) snake_case_ : str = do_resize snake_case_ : Tuple = size snake_case_ : Tuple = resample snake_case_ : Dict = do_center_crop snake_case_ : Any = crop_size snake_case_ : int = do_rescale snake_case_ : Union[str, Any] = rescale_factor snake_case_ : Optional[int] = do_normalize snake_case_ : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN snake_case_ : Optional[Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PIL.Image.BICUBIC , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> np.ndarray: snake_case_ : List[Any] = get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''' ) return resize( _SCREAMING_SNAKE_CASE , size=(size["height"], size["width"]) , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> np.ndarray: snake_case_ : str = get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must have 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 _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> Optional[int]: return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> np.ndarray: return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , ) -> PIL.Image.Image: snake_case_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize snake_case_ : Tuple = resample if resample is not None else self.resample snake_case_ : Optional[int] = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case_ : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale snake_case_ : Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case_ : Tuple = do_normalize if do_normalize is not None else self.do_normalize snake_case_ : Union[str, Any] = image_mean if image_mean is not None else self.image_mean snake_case_ : Optional[int] = image_std if image_std is not None else self.image_std snake_case_ : Optional[Any] = size if size is not None else self.size snake_case_ : int = get_size_dict(_SCREAMING_SNAKE_CASE ) snake_case_ : str = crop_size if crop_size is not None else self.crop_size snake_case_ : Optional[Any] = get_size_dict(_SCREAMING_SNAKE_CASE , param_name="crop_size" ) snake_case_ : 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 or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. snake_case_ : Optional[int] = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: snake_case_ : Optional[Any] = [self.resize(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: snake_case_ : List[Any] = [self.center_crop(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: snake_case_ : Optional[int] = [self.rescale(image=_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: snake_case_ : List[str] = [self.normalize(image=_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE ) for image in images] snake_case_ : int = [to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] snake_case_ : List[str] = {"pixel_values": images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
36
def lowerCAmelCase__ ( _a : int = 50 ): snake_case_ : Union[str, Any] = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
36
1
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract lowercase : Dict = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( __A , __A , __A ) -> Union[str, Any]: return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE__ ( __A , __A , __A = None ) -> Any: _snake_case = tesseract_config if tesseract_config is not None else '' # apply OCR _snake_case = to_pil_image(__A ) _snake_case , _snake_case = pil_image.size _snake_case = pytesseract.image_to_data(__A , lang=__A , output_type='dict' , config=__A ) _snake_case , _snake_case , _snake_case , _snake_case , _snake_case = data['text'], data['left'], data['top'], data['width'], data['height'] # filter empty words and corresponding coordinates _snake_case = [idx for idx, word in enumerate(__A ) if not word.strip()] _snake_case = [word for idx, word in enumerate(__A ) if idx not in irrelevant_indices] _snake_case = [coord for idx, coord in enumerate(__A ) if idx not in irrelevant_indices] _snake_case = [coord for idx, coord in enumerate(__A ) if idx not in irrelevant_indices] _snake_case = [coord for idx, coord in enumerate(__A ) if idx not in irrelevant_indices] _snake_case = [coord for idx, coord in enumerate(__A ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _snake_case = [] for x, y, w, h in zip(__A , __A , __A , __A ): _snake_case = [x, y, x + w, y + h] actual_boxes.append(__A ) # finally, normalize the bounding boxes _snake_case = [] for box in actual_boxes: normalized_boxes.append(normalize_box(__A , __A , __A ) ) assert len(__A ) == len(__A ), "Not as many words as there are bounding boxes" return words, normalized_boxes class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = ["""pixel_values"""] def __init__( self , lowerCAmelCase_ = True , lowerCAmelCase_ = None , lowerCAmelCase_ = PILImageResampling.BILINEAR , lowerCAmelCase_ = True , lowerCAmelCase_ = None , lowerCAmelCase_ = "" , **lowerCAmelCase_ , ): """simple docstring""" super().__init__(**lowerCAmelCase_ ) _snake_case = size if size is not None else {'height': 2_24, 'width': 2_24} _snake_case = get_size_dict(lowerCAmelCase_ ) _snake_case = do_resize _snake_case = size _snake_case = resample _snake_case = apply_ocr _snake_case = ocr_lang _snake_case = tesseract_config def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = PILImageResampling.BILINEAR , lowerCAmelCase_ = None , **lowerCAmelCase_ , ): """simple docstring""" _snake_case = get_size_dict(lowerCAmelCase_ ) if "height" not in size or "width" not in size: raise ValueError(F'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) _snake_case = (size['height'], size['width']) return resize(lowerCAmelCase_ , size=lowerCAmelCase_ , resample=lowerCAmelCase_ , data_format=lowerCAmelCase_ , **lowerCAmelCase_ ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = ChannelDimension.FIRST , **lowerCAmelCase_ , ): """simple docstring""" _snake_case = do_resize if do_resize is not None else self.do_resize _snake_case = size if size is not None else self.size _snake_case = get_size_dict(lowerCAmelCase_ ) _snake_case = resample if resample is not None else self.resample _snake_case = apply_ocr if apply_ocr is not None else self.apply_ocr _snake_case = ocr_lang if ocr_lang is not None else self.ocr_lang _snake_case = tesseract_config if tesseract_config is not None else self.tesseract_config _snake_case = make_list_of_images(lowerCAmelCase_ ) if not valid_images(lowerCAmelCase_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) # All transformations expect numpy arrays. _snake_case = [to_numpy_array(lowerCAmelCase_ ) for image in images] if apply_ocr: requires_backends(self , 'pytesseract' ) _snake_case = [] _snake_case = [] for image in images: _snake_case , _snake_case = apply_tesseract(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) words_batch.append(lowerCAmelCase_ ) boxes_batch.append(lowerCAmelCase_ ) if do_resize: _snake_case = [self.resize(image=lowerCAmelCase_ , size=lowerCAmelCase_ , resample=lowerCAmelCase_ ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _snake_case = [flip_channel_order(lowerCAmelCase_ ) for image in images] _snake_case = [to_channel_dimension_format(lowerCAmelCase_ , lowerCAmelCase_ ) for image in images] _snake_case = BatchFeature(data={'pixel_values': images} , tensor_type=lowerCAmelCase_ ) if apply_ocr: _snake_case = words_batch _snake_case = boxes_batch return data
42
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __a = logging.get_logger(__name__) __a = { "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", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } __a = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: for attribute in key.split(""".""" ): snake_case__ : Dict = getattr(_lowerCAmelCase , _lowerCAmelCase ) if weight_type is not None: snake_case__ : List[Any] = getattr(_lowerCAmelCase , _lowerCAmelCase ).shape else: snake_case__ : Union[str, Any] = hf_pointer.shape assert hf_shape == value.shape, ( 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": snake_case__ : int = value elif weight_type == "weight_g": snake_case__ : List[str] = value elif weight_type == "weight_v": snake_case__ : List[str] = value elif weight_type == "bias": snake_case__ : Optional[Any] = value else: snake_case__ : str = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> Any: snake_case__ : Union[str, Any] = [] snake_case__ : Dict = fairseq_model.state_dict() snake_case__ : List[Any] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight snake_case__ : Optional[int] = None for name, value in fairseq_dict.items(): snake_case__ : List[Any] = False if "conv_layers" in name: load_conv_layer( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , hf_model.config.feat_extract_norm == """group""" , ) snake_case__ : Union[str, Any] = True elif name.split(""".""" )[0] == "proj": snake_case__ : Tuple = fairseq_model.proj snake_case__ : int = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: snake_case__ : Optional[Any] = True if "*" in mapped_key: snake_case__ : Optional[int] = name.split(_lowerCAmelCase )[0].split(""".""" )[-2] snake_case__ : Tuple = mapped_key.replace("""*""" , _lowerCAmelCase ) if "weight_g" in name: snake_case__ : str = """weight_g""" elif "weight_v" in name: snake_case__ : int = """weight_v""" elif "bias" in name: snake_case__ : Dict = """bias""" elif "weight" in name: snake_case__ : Union[str, Any] = """weight""" else: snake_case__ : Union[str, Any] = None set_recursively(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) continue if not is_used: unused_weights.append(_lowerCAmelCase ) logger.warning(f"Unused weights: {unused_weights}" ) return proj_weight def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Dict: snake_case__ : int = full_name.split("""conv_layers.""" )[-1] snake_case__ : Dict = name.split(""".""" ) snake_case__ : Any = int(items[0] ) snake_case__ : Optional[Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) snake_case__ : int = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) snake_case__ : str = 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: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) snake_case__ : Union[str, Any] = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) snake_case__ : int = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_lowerCAmelCase ) def __snake_case( _lowerCAmelCase ) -> List[str]: snake_case__ , snake_case__ : str = emb.weight.shape snake_case__ : List[str] = nn.Linear(_lowerCAmelCase , _lowerCAmelCase , bias=_lowerCAmelCase ) snake_case__ : List[str] = emb.weight.data return lin_layer def __snake_case( _lowerCAmelCase ) -> Optional[Any]: with open(_lowerCAmelCase , """r""" , encoding="""utf-8""" ) as f: snake_case__ : int = f.readlines() snake_case__ : List[Any] = [line.split(""" """ )[0] for line in lines] snake_case__ : Union[str, Any] = len(_lowerCAmelCase ) snake_case__ : Any = { """<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3, } vocab_dict.update(dict(zip(_lowerCAmelCase , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , ) -> int: snake_case__ : Optional[Any] = WavaVecaConfig.from_pretrained(_lowerCAmelCase ) snake_case__ : Optional[Any] = SpeechaTextaConfig.from_pretrained( _lowerCAmelCase , vocab_size=_lowerCAmelCase , decoder_layers=_lowerCAmelCase , do_stable_layer_norm=_lowerCAmelCase ) snake_case__ : Optional[Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_lowerCAmelCase , return_attention_mask=_lowerCAmelCase , ) snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) snake_case__ : Tuple = model[0].eval() # set weights for wav2vec2 encoder snake_case__ : Optional[Any] = WavaVecaModel(_lowerCAmelCase ) snake_case__ : Dict = recursively_load_weights_wavaveca(model.encoder , _lowerCAmelCase ) snake_case__ : Optional[Any] = SpeechaTextaForCausalLM(_lowerCAmelCase ) snake_case__ , snake_case__ : Tuple = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=_lowerCAmelCase ) # set output linear layer unexpected_keys.remove("""embed_out""" ) snake_case__ : Tuple = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"The following keys are missing when loading the decoder weights: {missing_keys}" ) logger.warning(f"The following keys are unexpected when loading the decoder weights: {unexpected_keys}" ) snake_case__ : List[Any] = SpeechEncoderDecoderModel(encoder=_lowerCAmelCase , decoder=_lowerCAmelCase ) snake_case__ : Tuple = False # add projection layer snake_case__ : Union[str, Any] = nn.Parameter(projection_layer.weight ) snake_case__ : int = nn.Parameter(projection_layer.bias ) snake_case__ : Tuple = create_vocab_dict(_lowerCAmelCase ) with open(os.path.join(_lowerCAmelCase , """vocab.json""" ) , """w""" ) as fp: json.dump(_lowerCAmelCase , _lowerCAmelCase ) snake_case__ : Tuple = SpeechaTextaTokenizer(os.path.join(_lowerCAmelCase , """vocab.json""" ) ) tokenizer.save_pretrained(_lowerCAmelCase ) snake_case__ : Optional[Any] = hf_wavavec.config.to_dict() snake_case__ : Tuple = tokenizer.pad_token_id snake_case__ : Optional[Any] = tokenizer.bos_token_id snake_case__ : int = tokenizer.eos_token_id snake_case__ : str = """speech_to_text_2""" snake_case__ : List[Any] = """wav2vec2""" snake_case__ : List[str] = SpeechEncoderDecoderConfig.from_dict(_lowerCAmelCase ) hf_wavavec.save_pretrained(_lowerCAmelCase ) feature_extractor.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": __a = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=1_0224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") __a = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
35
0
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
78
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { '''RWKV/rwkv-4-169m-pile''': '''https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-430m-pile''': '''https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-1b5-pile''': '''https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json''', '''RWKV/rwkv-4-3b-pile''': '''https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-7b-pile''': '''https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-14b-pile''': '''https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json''', '''RWKV/rwkv-raven-1b5''': '''https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json''', '''RWKV/rwkv-raven-3b''': '''https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json''', '''RWKV/rwkv-raven-7b''': '''https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json''', '''RWKV/rwkv-raven-14b''': '''https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json''', } class __snake_case ( lowerCamelCase__ ): __lowerCamelCase : str = """rwkv""" __lowerCamelCase : str = {"""max_position_embeddings""": """context_length"""} def __init__( self , snake_case__=5_0277 , snake_case__=1024 , snake_case__=4096 , snake_case__=32 , snake_case__=None , snake_case__=None , snake_case__=1e-5 , snake_case__=0 , snake_case__=0 , snake_case__=6 , snake_case__=False , snake_case__=True , **snake_case__ , ) -> List[str]: '''simple docstring''' UpperCAmelCase : int =vocab_size UpperCAmelCase : List[str] =context_length UpperCAmelCase : Any =hidden_size UpperCAmelCase : Tuple =num_hidden_layers UpperCAmelCase : str =attention_hidden_size if attention_hidden_size is not None else hidden_size UpperCAmelCase : List[Any] =intermediate_size if intermediate_size is not None else 4 * hidden_size UpperCAmelCase : Optional[int] =layer_norm_epsilon UpperCAmelCase : int =rescale_every UpperCAmelCase : Any =use_cache UpperCAmelCase : List[str] =bos_token_id UpperCAmelCase : Any =eos_token_id super().__init__( tie_word_embeddings=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ )
78
1
'''simple docstring''' import collections import os import re from pathlib import Path __lowerCamelCase = '''src/transformers''' # Matches is_xxx_available() __lowerCamelCase = re.compile(r'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} __lowerCamelCase = re.compile(r'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] __lowerCamelCase = re.compile(r'''\s+\"\S*\":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available __lowerCamelCase = re.compile(r'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") __lowerCamelCase = re.compile(r'''^\s*_import_structure\[\"\S*\"\]\.append\(\"(\S*)\"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] __lowerCamelCase = re.compile(r'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", __lowerCamelCase = re.compile(r'''^\s+\"([^\"]+)\",''') # Catches a line with objects between brackets only: ["foo", "bar"], __lowerCamelCase = re.compile(r'''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo __lowerCamelCase = re.compile(r'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: __lowerCamelCase = re.compile(r'''^\s*try:''') # Catches a line with else: __lowerCamelCase = re.compile(r'''^\s*else:''') def UpperCAmelCase__ ( UpperCAmelCase__ ) -> int: if _re_test_backend.search(a__ ) is None: return None A_ = [b[0] for b in _re_backend.findall(a__ )] backends.sort() return "_and_".join(a__ ) def UpperCAmelCase__ ( UpperCAmelCase__ ) -> Dict: with open(a__, """r""", encoding="""utf-8""", newline="""\n""" ) as f: A_ = f.readlines() A_ = 0 while line_index < len(a__ ) and not lines[line_index].startswith("""_import_structure = {""" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(a__ ): return None # First grab the objects without a specific backend in _import_structure A_ = [] while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None: A_ = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(a__ ): A_ = _re_one_line_import_struct.search(a__ ).groups()[0] A_ = re.findall(r"""\[([^\]]+)\]""", a__ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(""", """ )] ) line_index += 1 continue A_ = _re_import_struct_key_value.search(a__ ) if single_line_import_search is not None: A_ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(a__ ) > 0] objects.extend(a__ ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) line_index += 1 A_ = {"""none""": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("""if TYPE_CHECKING""" ): # If the line is an if not is_backend_available, we grab all objects associated. A_ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A_ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A_ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ): A_ = lines[line_index] if _re_import_struct_add_one.search(a__ ) is not None: objects.append(_re_import_struct_add_one.search(a__ ).groups()[0] ) elif _re_import_struct_add_many.search(a__ ) is not None: A_ = _re_import_struct_add_many.search(a__ ).groups()[0].split(""", """ ) A_ = [obj[1:-1] for obj in imports if len(a__ ) > 0] objects.extend(a__ ) elif _re_between_brackets.search(a__ ) is not None: A_ = _re_between_brackets.search(a__ ).groups()[0].split(""", """ ) A_ = [obj[1:-1] for obj in imports if len(a__ ) > 0] objects.extend(a__ ) elif _re_quote_object.search(a__ ) is not None: objects.append(_re_quote_object.search(a__ ).groups()[0] ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) elif line.startswith(""" """ * 12 + """\"""" ): objects.append(line[13:-3] ) line_index += 1 A_ = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A_ = [] while ( line_index < len(a__ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("""else""" ) ): A_ = lines[line_index] A_ = _re_import.search(a__ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 8 ): objects.append(line[8:-2] ) line_index += 1 A_ = {"""none""": objects} # Let's continue with backend-specific objects while line_index < len(a__ ): # If the line is an if is_backend_available, we grab all objects associated. A_ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A_ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A_ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ): A_ = lines[line_index] A_ = _re_import.search(a__ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 12 ): objects.append(line[12:-2] ) line_index += 1 A_ = objects else: line_index += 1 return import_dict_objects, type_hint_objects def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__ ) -> Dict: def find_duplicates(UpperCAmelCase__ ): return [k for k, v in collections.Counter(a__ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] A_ = [] for key in import_dict_objects.keys(): A_ = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'''Duplicate _import_structure definitions for: {duplicate_imports}''' ) A_ = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): A_ = """base imports""" if key == """none""" else F'''{key} backend''' errors.append(F'''Differences for {name}:''' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F''' {a} in TYPE_HINT but not in _import_structure.''' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F''' {a} in _import_structure but not in TYPE_HINT.''' ) return errors def UpperCAmelCase__ ( ) -> List[str]: A_ = [] for root, _, files in os.walk(a__ ): if "__init__.py" in files: A_ = os.path.join(a__, """__init__.py""" ) A_ = parse_init(a__ ) if objects is not None: A_ = analyze_results(*a__ ) if len(a__ ) > 0: A_ = F'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}''' failures.append("""\n""".join(a__ ) ) if len(a__ ) > 0: raise ValueError("""\n\n""".join(a__ ) ) def UpperCAmelCase__ ( ) -> Any: A_ = [] for path, directories, files in os.walk(a__ ): for folder in directories: # Ignore private modules if folder.startswith("""_""" ): directories.remove(a__ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(a__ ) / folder).glob("""*.py""" ) ) ) == 0: continue A_ = str((Path(a__ ) / folder).relative_to(a__ ) ) A_ = short_path.replace(os.path.sep, """.""" ) submodules.append(a__ ) for fname in files: if fname == "__init__.py": continue A_ = str((Path(a__ ) / fname).relative_to(a__ ) ) A_ = short_path.replace(""".py""", """""" ).replace(os.path.sep, """.""" ) if len(submodule.split(""".""" ) ) == 1: submodules.append(a__ ) return submodules __lowerCamelCase = [ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', '''models.esm.openfold_utils''', ] def UpperCAmelCase__ ( ) -> str: # This is to make sure the transformers module imported is the one in the repo. from transformers.utils import direct_transformers_import A_ = direct_transformers_import(a__ ) A_ = set(transformers._import_structure.keys() ) # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and # (potentiall re-) add them. with open(os.path.join(a__, """__init__.py""" ), """r""" ) as f: A_ = f.read() import_structure_keys.update(set(re.findall(r"""import_structure\[\"([^\"]*)\"\]""", a__ ) ) ) A_ = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in import_structure_keys ] if len(a__ ) > 0: A_ = """\n""".join(F'''- {module}''' for module in module_not_registered ) raise ValueError( """The following submodules are not properly registed in the main init of Transformers:\n""" F'''{list_of_modules}\n''' """Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" ) if __name__ == "__main__": check_all_inits() check_submodules()
162
"""simple docstring""" def lowercase ( a__ : Union[str, Any] ) -> Optional[Any]: _UpperCamelCase = len(a__ ) while cur > 1: # Find the maximum number in arr _UpperCamelCase = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi _UpperCamelCase = arr[mi::-1] + arr[mi + 1 : len(a__ )] # Reverse whole list _UpperCamelCase = arr[cur - 1 :: -1] + arr[cur : len(a__ )] cur -= 1 return arr if __name__ == "__main__": UpperCAmelCase = input("""Enter numbers separated by a comma:\n""").strip() UpperCAmelCase = [int(item) for item in user_input.split(""",""")] print(pancake_sort(unsorted))
256
0
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> int: return number | (1 << position) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> int: return number & ~(1 << position) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> int: return number ^ (1 << position) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> bool: return ((number >> position) & 1) == 1 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> int: return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
56
"""simple docstring""" import math from collections.abc import Iterator from itertools import takewhile def _lowercase ( __lowerCAmelCase ) -> 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(__lowerCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowercase ( ) -> Iterator[int]: SCREAMING_SNAKE_CASE__ : List[Any] = 2 while True: if is_prime(__lowerCAmelCase ): yield num num += 1 def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: return sum(takewhile(lambda __lowerCAmelCase : x < n , prime_generator() ) ) if __name__ == "__main__": print(f'{solution() = }')
56
1
import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase : Optional[Any] = random.Random() if is_torch_available(): import torch def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Union[str, Any]=1.0 , _lowerCamelCase : Any=None , _lowerCamelCase : Any=None) -> Optional[int]: '''simple docstring''' if rng is None: __UpperCamelCase : Tuple = global_rng __UpperCamelCase : Any = [] for batch_idx in range(shape[0]): values.append([]) for _ in range(shape[1]): values[-1].append(rng.random() * scale) return values class lowerCamelCase__ ( unittest.TestCase): '''simple docstring''' def __init__( self :Union[str, Any] , a :Dict , a :int=7 , a :Tuple=4_0_0 , a :Optional[int]=2_0_0_0 , a :Optional[Any]=1 , a :Optional[Any]=0.0 , a :Dict=1_6_0_0_0 , a :List[Any]=True , a :List[str]=True , ) -> Optional[int]: __UpperCamelCase : str = parent __UpperCamelCase : Optional[Any] = batch_size __UpperCamelCase : Optional[int] = min_seq_length __UpperCamelCase : List[str] = max_seq_length __UpperCamelCase : Optional[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __UpperCamelCase : List[Any] = feature_size __UpperCamelCase : Tuple = padding_value __UpperCamelCase : List[str] = sampling_rate __UpperCamelCase : Dict = return_attention_mask __UpperCamelCase : List[str] = do_normalize def _lowerCamelCase ( self :Dict ) -> Dict: return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _lowerCamelCase ( self :int , a :Optional[Any]=False , a :str=False ) -> Tuple: def _flatten(a :Dict ): return list(itertools.chain(*a ) ) if equal_length: __UpperCamelCase : Optional[int] = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __UpperCamelCase : List[str] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __UpperCamelCase : Any = [np.asarray(a ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCamelCase__ ( __lowercase , unittest.TestCase): '''simple docstring''' _A = ASTFeatureExtractor def _lowerCamelCase ( self :Union[str, Any] ) -> Any: __UpperCamelCase : str = ASTFeatureExtractionTester(self ) def _lowerCamelCase ( self :Any ) -> Union[str, Any]: # Tests that all call wrap to encode_plus and batch_encode_plus __UpperCamelCase : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __UpperCamelCase : Dict = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __UpperCamelCase : Optional[int] = [np.asarray(a ) for speech_input in speech_inputs] # Test not batched input __UpperCamelCase : Tuple = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values __UpperCamelCase : int = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(a , a , atol=1E-3 ) ) # Test batched __UpperCamelCase : List[str] = feat_extract(a , padding=a , return_tensors="np" ).input_values __UpperCamelCase : Optional[Any] = feat_extract(a , padding=a , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(a , a ): self.assertTrue(np.allclose(a , a , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __UpperCamelCase : Optional[Any] = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] __UpperCamelCase : int = np.asarray(a ) __UpperCamelCase : Union[str, Any] = feat_extract(a , return_tensors="np" ).input_values __UpperCamelCase : Any = feat_extract(a , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(a , a ): self.assertTrue(np.allclose(a , a , atol=1E-3 ) ) @require_torch def _lowerCamelCase ( self :Optional[int] ) -> List[str]: import torch __UpperCamelCase : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __UpperCamelCase : Any = np.random.rand(1_0_0 ).astype(np.floataa ) __UpperCamelCase : List[Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __UpperCamelCase : List[str] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __UpperCamelCase : List[str] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def _lowerCamelCase ( self :int , a :Optional[int] ) -> Any: from datasets import load_dataset __UpperCamelCase : Union[str, Any] = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech __UpperCamelCase : str = ds.sort("id" ).select(range(a ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] @require_torch def _lowerCamelCase ( self :Dict ) -> Dict: # fmt: off __UpperCamelCase : Dict = torch.tensor( [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776, -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133, -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936, -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869] ) # fmt: on __UpperCamelCase : Optional[int] = self._load_datasamples(1 ) __UpperCamelCase : int = ASTFeatureExtractor() __UpperCamelCase : Optional[Any] = feature_extractor(a , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 1_0_2_4, 1_2_8) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , a , atol=1E-4 ) )
232
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 lowerCamelCase__ : '''simple docstring''' def __init__( self :List[Any] , a :Dict , a :Any=3 , a :Any=3_2 , a :Optional[Any]=3 , a :str=1_0 , a :Union[str, Any]=[1_0, 2_0, 3_0, 4_0] , a :Optional[Any]=[1, 1, 2, 1] , a :Optional[Any]=True , a :Dict=True , a :Tuple="relu" , a :List[str]=3 , a :Tuple=None , ) -> Tuple: __UpperCamelCase : Optional[Any] = parent __UpperCamelCase : Dict = batch_size __UpperCamelCase : int = image_size __UpperCamelCase : Dict = num_channels __UpperCamelCase : Optional[int] = embeddings_size __UpperCamelCase : List[Any] = hidden_sizes __UpperCamelCase : Optional[Any] = depths __UpperCamelCase : Optional[int] = is_training __UpperCamelCase : Union[str, Any] = use_labels __UpperCamelCase : Optional[int] = hidden_act __UpperCamelCase : Tuple = num_labels __UpperCamelCase : Tuple = scope __UpperCamelCase : Dict = len(a ) def _lowerCamelCase ( self :Optional[int] ) -> Any: __UpperCamelCase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCamelCase : List[str] = None if self.use_labels: __UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_labels ) __UpperCamelCase : List[Any] = self.get_config() return config, pixel_values, labels def _lowerCamelCase ( self :Union[str, Any] ) -> int: 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 _lowerCamelCase ( self :List[Any] , a :Dict , a :int , a :Optional[Any] ) -> Tuple: __UpperCamelCase : str = TFResNetModel(config=a ) __UpperCamelCase : Union[str, Any] = model(a ) # 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 _lowerCamelCase ( self :Union[str, Any] , a :Optional[int] , a :List[str] , a :Optional[Any] ) -> Any: __UpperCamelCase : str = self.num_labels __UpperCamelCase : Optional[int] = TFResNetForImageClassification(a ) __UpperCamelCase : List[str] = model(a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowerCamelCase ( self :Optional[int] ) -> List[str]: __UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Union[str, Any] = config_and_inputs __UpperCamelCase : List[str] = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class lowerCamelCase__ ( __lowercase , __lowercase , unittest.TestCase): '''simple docstring''' _A = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _A = ( {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification} if is_tf_available() else {} ) _A = False _A = False _A = False _A = False _A = False def _lowerCamelCase ( self :int ) -> List[str]: __UpperCamelCase : Union[str, Any] = TFResNetModelTester(self ) __UpperCamelCase : List[Any] = ConfigTester(self , config_class=a , has_text_modality=a ) def _lowerCamelCase ( self :int ) -> Dict: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _lowerCamelCase ( self :str ) -> Optional[Any]: return @unittest.skip(reason="ResNet does not use inputs_embeds" ) def _lowerCamelCase ( self :Tuple ) -> Tuple: pass @unittest.skip(reason="ResNet does not support input and output embeddings" ) def _lowerCamelCase ( self :List[Any] ) -> List[str]: pass def _lowerCamelCase ( self :Optional[int] ) -> Tuple: __UpperCamelCase , __UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase : Dict = model_class(a ) __UpperCamelCase : Union[str, Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase : Dict = [*signature.parameters.keys()] __UpperCamelCase : Union[str, Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , a ) def _lowerCamelCase ( self :List[str] ) -> List[str]: __UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _lowerCamelCase ( self :Optional[Any] ) -> Tuple: def check_hidden_states_output(a :Optional[Any] , a :Optional[int] , a :List[str] ): __UpperCamelCase : int = model_class(a ) __UpperCamelCase : int = model(**self._prepare_for_class(a , a ) ) __UpperCamelCase : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __UpperCamelCase : Optional[int] = self.model_tester.num_stages self.assertEqual(len(a ) , 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] , ) __UpperCamelCase , __UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase : str = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: __UpperCamelCase : int = layer_type __UpperCamelCase : int = True check_hidden_states_output(a , a , a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCamelCase : int = True check_hidden_states_output(a , a , a ) def _lowerCamelCase ( self :Union[str, Any] ) -> Dict: __UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a ) @slow def _lowerCamelCase ( self :Dict ) -> Dict: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : Optional[Any] = TFResNetModel.from_pretrained(a ) self.assertIsNotNone(a ) def _SCREAMING_SNAKE_CASE ( ) -> int: '''simple docstring''' __UpperCamelCase : Tuple = 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[Any] ) -> Tuple: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def _lowerCamelCase ( self :Optional[int] ) -> Optional[int]: __UpperCamelCase : int = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __UpperCamelCase : List[Any] = self.default_image_processor __UpperCamelCase : List[str] = prepare_img() __UpperCamelCase : List[str] = image_processor(images=a , return_tensors="tf" ) # forward pass __UpperCamelCase : Dict = model(**a ) # verify the logits __UpperCamelCase : Dict = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , a ) __UpperCamelCase : Union[str, Any] = tf.constant([-11.1069, -9.7877, -8.3777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4 ) )
232
1
import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class lowerCamelCase ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): UpperCAmelCase__ : Any = CTRLTokenizer UpperCAmelCase__ : str = False UpperCAmelCase__ : Dict = False def UpperCAmelCase(self : Optional[int] ) -> str: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case = ['adapt', 're@@', 'a@@', 'apt', 'c@@', 't', '<unk>'] snake_case = dict(zip(snake_case__ , range(len(snake_case__ ) ) ) ) snake_case = ['#version: 0.2', 'a p', 'ap t</w>', 'r e', 'a d', 'ad apt</w>', ''] snake_case = {'unk_token': '<unk>'} snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(snake_case__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(snake_case__ ) ) def UpperCAmelCase(self : List[Any] , **_A : int ) -> str: kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **snake_case__ ) def UpperCAmelCase(self : Tuple , _A : str ) -> Optional[int]: snake_case = 'adapt react readapt apt' snake_case = 'adapt react readapt apt' return input_text, output_text def UpperCAmelCase(self : int ) -> int: snake_case = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case = 'adapt react readapt apt' snake_case = 'adapt re@@ a@@ c@@ t re@@ adapt apt'.split() snake_case = tokenizer.tokenize(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) snake_case = tokens + [tokenizer.unk_token] snake_case = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case__ ) , snake_case__ )
353
from ..utils import DummyObject, requires_backends class lowerCamelCase ( metaclass=A_ ): UpperCAmelCase__ : Union[str, Any] = ["onnx"] def __init__(self : Tuple , *_A : Optional[int] , **_A : Any ) -> Dict: requires_backends(self , ["onnx"] ) @classmethod def UpperCAmelCase(cls : int , *_A : Dict , **_A : List[Any] ) -> Optional[Any]: requires_backends(cls , ["onnx"] ) @classmethod def UpperCAmelCase(cls : Dict , *_A : Tuple , **_A : Optional[Any] ) -> int: requires_backends(cls , ["onnx"] )
137
0
"""simple docstring""" from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker a = '''CompVis/stable-diffusion-v1-1''' a = '''CompVis/stable-diffusion-v1-2''' a = '''CompVis/stable-diffusion-v1-3''' a = '''CompVis/stable-diffusion-v1-4''' class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' def __init__( self : Tuple , _UpperCAmelCase : AutoencoderKL , _UpperCAmelCase : CLIPTextModel , _UpperCAmelCase : CLIPTokenizer , _UpperCAmelCase : UNetaDConditionModel , _UpperCAmelCase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , _UpperCAmelCase : StableDiffusionSafetyChecker , _UpperCAmelCase : CLIPImageProcessor , _UpperCAmelCase : bool = True , ): super()._init_() _A = StableDiffusionPipeline.from_pretrained(_UpperCAmelCase ) _A = StableDiffusionPipeline.from_pretrained(_UpperCAmelCase ) _A = StableDiffusionPipeline.from_pretrained(_UpperCAmelCase ) _A = StableDiffusionPipeline( vae=_UpperCAmelCase , text_encoder=_UpperCAmelCase , tokenizer=_UpperCAmelCase , unet=_UpperCAmelCase , scheduler=_UpperCAmelCase , safety_checker=_UpperCAmelCase , feature_extractor=_UpperCAmelCase , requires_safety_checker=_UpperCAmelCase , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def lowerCAmelCase_ ( self : int ): return {k: getattr(self , _UpperCAmelCase ) for k in self.config.keys() if not k.startswith('_' )} def lowerCAmelCase_ ( self : List[Any] , _UpperCAmelCase : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory _A = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_UpperCAmelCase ) def lowerCAmelCase_ ( self : Union[str, Any] ): self.enable_attention_slicing(_UpperCAmelCase ) @torch.no_grad() def lowerCAmelCase_ ( self : Optional[int] , _UpperCAmelCase : Union[str, List[str]] , _UpperCAmelCase : int = 512 , _UpperCAmelCase : int = 512 , _UpperCAmelCase : int = 50 , _UpperCAmelCase : float = 7.5 , _UpperCAmelCase : Optional[Union[str, List[str]]] = None , _UpperCAmelCase : Optional[int] = 1 , _UpperCAmelCase : float = 0.0 , _UpperCAmelCase : Optional[torch.Generator] = None , _UpperCAmelCase : Optional[torch.FloatTensor] = None , _UpperCAmelCase : Optional[str] = "pil" , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , _UpperCAmelCase : int = 1 , **_UpperCAmelCase : Dict , ): return self.pipea( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) @torch.no_grad() def lowerCAmelCase_ ( self : Optional[Any] , _UpperCAmelCase : Union[str, List[str]] , _UpperCAmelCase : int = 512 , _UpperCAmelCase : int = 512 , _UpperCAmelCase : int = 50 , _UpperCAmelCase : float = 7.5 , _UpperCAmelCase : Optional[Union[str, List[str]]] = None , _UpperCAmelCase : Optional[int] = 1 , _UpperCAmelCase : float = 0.0 , _UpperCAmelCase : Optional[torch.Generator] = None , _UpperCAmelCase : Optional[torch.FloatTensor] = None , _UpperCAmelCase : Optional[str] = "pil" , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , _UpperCAmelCase : int = 1 , **_UpperCAmelCase : List[str] , ): return self.pipea( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) @torch.no_grad() def lowerCAmelCase_ ( self : Tuple , _UpperCAmelCase : Union[str, List[str]] , _UpperCAmelCase : int = 512 , _UpperCAmelCase : int = 512 , _UpperCAmelCase : int = 50 , _UpperCAmelCase : float = 7.5 , _UpperCAmelCase : Optional[Union[str, List[str]]] = None , _UpperCAmelCase : Optional[int] = 1 , _UpperCAmelCase : float = 0.0 , _UpperCAmelCase : Optional[torch.Generator] = None , _UpperCAmelCase : Optional[torch.FloatTensor] = None , _UpperCAmelCase : Optional[str] = "pil" , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , _UpperCAmelCase : int = 1 , **_UpperCAmelCase : int , ): return self.pipea( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) @torch.no_grad() def lowerCAmelCase_ ( self : Optional[int] , _UpperCAmelCase : Union[str, List[str]] , _UpperCAmelCase : int = 512 , _UpperCAmelCase : int = 512 , _UpperCAmelCase : int = 50 , _UpperCAmelCase : float = 7.5 , _UpperCAmelCase : Optional[Union[str, List[str]]] = None , _UpperCAmelCase : Optional[int] = 1 , _UpperCAmelCase : float = 0.0 , _UpperCAmelCase : Optional[torch.Generator] = None , _UpperCAmelCase : Optional[torch.FloatTensor] = None , _UpperCAmelCase : Optional[str] = "pil" , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , _UpperCAmelCase : int = 1 , **_UpperCAmelCase : List[Any] , ): return self.pipea( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) @torch.no_grad() def lowerCAmelCase_ ( self : str , _UpperCAmelCase : Union[str, List[str]] , _UpperCAmelCase : int = 512 , _UpperCAmelCase : int = 512 , _UpperCAmelCase : int = 50 , _UpperCAmelCase : float = 7.5 , _UpperCAmelCase : Optional[Union[str, List[str]]] = None , _UpperCAmelCase : Optional[int] = 1 , _UpperCAmelCase : float = 0.0 , _UpperCAmelCase : Optional[torch.Generator] = None , _UpperCAmelCase : Optional[torch.FloatTensor] = None , _UpperCAmelCase : Optional[str] = "pil" , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , _UpperCAmelCase : int = 1 , **_UpperCAmelCase : int , ): _A = 'cuda' if torch.cuda.is_available() else 'cpu' self.to(_UpperCAmelCase ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F'''`height` and `width` must be divisible by 8 but are {height} and {width}.''' ) # Get first result from Stable Diffusion Checkpoint v1.1 _A = self.textaimg_sda_a( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) # Get first result from Stable Diffusion Checkpoint v1.2 _A = self.textaimg_sda_a( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) # Get first result from Stable Diffusion Checkpoint v1.3 _A = self.textaimg_sda_a( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) # Get first result from Stable Diffusion Checkpoint v1.4 _A = self.textaimg_sda_a( prompt=_UpperCAmelCase , height=_UpperCAmelCase , width=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , negative_prompt=_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase , eta=_UpperCAmelCase , generator=_UpperCAmelCase , latents=_UpperCAmelCase , output_type=_UpperCAmelCase , return_dict=_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=_UpperCAmelCase , **_UpperCAmelCase , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
315
"""simple docstring""" from __future__ import annotations def _snake_case ( _snake_case : int , _snake_case : int ) -> list[list[int]]: '''simple docstring''' _A = [] create_all_state(1 , _snake_case , _snake_case , [] , _snake_case ) return result def _snake_case ( _snake_case : int , _snake_case : int , _snake_case : int , _snake_case : list[int] , _snake_case : list[list[int]] , ) -> None: '''simple docstring''' if level == 0: total_list.append(current_list[:] ) return for i in range(_snake_case , total_number - level + 2 ): current_list.append(_snake_case ) create_all_state(i + 1 , _snake_case , level - 1 , _snake_case , _snake_case ) current_list.pop() def _snake_case ( _snake_case : list[list[int]] ) -> None: '''simple docstring''' for i in total_list: print(*_snake_case ) if __name__ == "__main__": a = 4 a = 2 a = generate_all_combinations(n, k) print_all_state(total_list)
315
1
from ..utils import DummyObject, requires_backends class _lowercase ( metaclass=lowerCAmelCase ): """simple docstring""" __A = ["note_seq"] def __init__(self , *lowerCamelCase_ , **lowerCamelCase_ ): """simple docstring""" requires_backends(self , ["note_seq"] ) @classmethod def UpperCamelCase_ (cls , *lowerCamelCase_ , **lowerCamelCase_ ): """simple docstring""" requires_backends(cls , ["note_seq"] ) @classmethod def UpperCamelCase_ (cls , *lowerCamelCase_ , **lowerCamelCase_ ): """simple docstring""" requires_backends(cls , ["note_seq"] )
71
def a( A : int , A : float , A : float ) -> float: """simple docstring""" return round(float(moles / volume ) * nfactor ) def a( A : float , A : float , A : float ) -> float: """simple docstring""" return round(float((moles * 0.0_821 * temperature) / (volume) ) ) def a( A : float , A : float , A : float ) -> float: """simple docstring""" return round(float((moles * 0.0_821 * temperature) / (pressure) ) ) def a( A : float , A : float , A : float ) -> float: """simple docstring""" return round(float((pressure * volume) / (0.0_821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
71
1
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["image_processor", "tokenizer"] __lowerCAmelCase = "AutoImageProcessor" __lowerCAmelCase = "AutoTokenizer" def __init__( self , __A , __A ) -> List[str]: super().__init__(__A , __A ) a =self.image_processor def __call__( self , __A=None , __A=None , __A=None , **__A ) -> Optional[int]: if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: a =self.tokenizer(__A , return_tensors=__A , **__A ) if images is not None: a =self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: a =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def SCREAMING_SNAKE_CASE ( self , *__A , **__A ) -> str: return self.tokenizer.batch_decode(*__A , **__A ) def SCREAMING_SNAKE_CASE ( self , *__A , **__A ) -> str: return self.tokenizer.decode(*__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: return ["input_ids", "attention_mask", "pixel_values"]
81
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" a =ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=lowercase , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=lowercase , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=lowercase ) return parser.parse_args() def _A ( ): """simple docstring""" a =parse_args() # Import training_script as a module. a =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a =script_fpath.stem a =importlib.import_module(lowercase ) # Patch sys.argv a =[args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
81
1
def SCREAMING_SNAKE_CASE__ ( __a , __a ): if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) snake_case_ : Union[str, Any] = str(bin(__a ) )[2:] # remove the leading "0b" snake_case_ : List[Any] = str(bin(__a ) )[2:] # remove the leading "0b" snake_case_ : Optional[int] = max(len(__a ) , len(__a ) ) return "0b" + "".join( str(int(char_a == '1' and char_b == '1' ) ) for char_a, char_b in zip(a_binary.zfill(__a ) , b_binary.zfill(__a ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
88
import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( __a , __a , __a , __a , __a ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file snake_case_ : Optional[int] = TapasConfig.from_json_file(__a ) # set absolute/relative position embeddings parameter snake_case_ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": snake_case_ : int = TapasForQuestionAnswering(config=__a ) elif task == "WTQ": # run_task_main.py hparams snake_case_ : Optional[int] = 4 snake_case_ : List[str] = True # hparam_utils.py hparams snake_case_ : Optional[Any] = 0.664694 snake_case_ : Dict = 0.207951 snake_case_ : Tuple = 0.121194 snake_case_ : Dict = True snake_case_ : int = True snake_case_ : int = False snake_case_ : str = 0.0352513 snake_case_ : int = TapasForQuestionAnswering(config=__a ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams snake_case_ : int = 4 snake_case_ : Optional[int] = False # hparam_utils.py hparams snake_case_ : str = 36.4519 snake_case_ : Optional[Any] = 0.903421 snake_case_ : List[Any] = 222.088 snake_case_ : Optional[int] = True snake_case_ : Optional[Any] = True snake_case_ : str = True snake_case_ : int = 0.763141 snake_case_ : str = TapasForQuestionAnswering(config=__a ) elif task == "TABFACT": snake_case_ : List[Any] = TapasForSequenceClassification(config=__a ) elif task == "MLM": snake_case_ : Optional[int] = TapasForMaskedLM(config=__a ) elif task == "INTERMEDIATE_PRETRAINING": snake_case_ : Tuple = TapasModel(config=__a ) else: raise ValueError(f"""Task {task} not supported.""" ) print(f"""Building PyTorch model from configuration: {config}""" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(__a , __a , __a ) # Save pytorch-model (weights and configuration) print(f"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__a ) # Save tokenizer files print(f"""Save tokenizer files to {pytorch_dump_path}""" ) snake_case_ : str = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + 'vocab.txt' , model_max_length=5_12 ) tokenizer.save_pretrained(__a ) print('Used relative position embeddings:' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( """--task""", default="""SQA""", type=str, help="""Model task for which to convert a checkpoint. Defaults to SQA.""" ) parser.add_argument( """--reset_position_index_per_cell""", default=False, action="""store_true""", help="""Whether to use relative position embeddings or not. Defaults to True.""", ) parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--tapas_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained TAPAS model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) _SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
88
1
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging __A =logging.get_logger(__name__) def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(lowerCamelCase__ ) == len(lowerCamelCase__ ), F'{len(lowerCamelCase__ )} != {len(lowerCamelCase__ )}' dest_layers.load_state_dict(layers_to_copy.state_dict() ) __A ={ # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 1_2: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 1_1], 4: [0, 4, 8, 1_1], 6: [0, 2, 4, 7, 9, 1_1], 9: [0, 1, 2, 4, 5, 7, 9, 1_0, 1_1], 1_2: list(range(1_2)), }, 1_6: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 1_5], 3: [0, 8, 1_5], 4: [0, 5, 1_0, 1_5], 6: [0, 3, 6, 9, 1_2, 1_5], 8: [0, 2, 4, 6, 8, 1_0, 1_2, 1_5], 9: [0, 1, 3, 5, 7, 9, 1_1, 1_3, 1_5], 1_2: [0, 1, 2, 3, 4, 5, 6, 7, 9, 1_1, 1_3, 1_5], 1_6: list(range(1_6)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } __A ={ # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 1_2: {1: [1_1], 2: [5, 1_1], 3: [3, 7, 1_1], 6: [1, 3, 5, 8, 1_0, 1_1]}, 1_6: {1: [1_5], 4: [4, 9, 1_2, 1_5], 8: [1, 3, 5, 7, 9, 1_1, 1_3, 1_5]}, } def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): try: lowerCamelCase_ = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F'no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first' F' {n_student}' ) return list(range(lowerCamelCase__ ) ) def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): if n_student > n_teacher: raise ValueError(F'Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}' ) elif n_teacher == n_student: return list(range(lowerCamelCase__ ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ = "student" , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__=False , lowerCamelCase__=None , lowerCamelCase__=None , **lowerCamelCase__ , ): lowerCamelCase_ = "encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher." assert (e is not None) or (d is not None), _msg if isinstance(lowerCamelCase__ , lowerCamelCase__ ): AutoTokenizer.from_pretrained(lowerCamelCase__ ).save_pretrained(lowerCamelCase__ ) # purely for convenience lowerCamelCase_ = AutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__ ).eval() else: assert isinstance(lowerCamelCase__ , lowerCamelCase__ ), F'teacher must be a model or string got type {type(lowerCamelCase__ )}' lowerCamelCase_ = teacher.config.to_diff_dict() try: lowerCamelCase_ , lowerCamelCase_ = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: lowerCamelCase_ = teacher_e if d is None: lowerCamelCase_ = teacher_d init_kwargs.update({"encoder_layers": e, "decoder_layers": d} ) except AttributeError: # T5 if hasattr(teacher.config , "num_encoder_layers" ): lowerCamelCase_ , lowerCamelCase_ = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: lowerCamelCase_ , lowerCamelCase_ = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: lowerCamelCase_ = teacher_e if d is None: lowerCamelCase_ = teacher_d if hasattr(teacher.config , "num_encoder_layers" ): init_kwargs.update({"num_encoder_layers": e, "num_decoder_layers": d} ) else: init_kwargs.update({"num_layers": e, "num_decoder_layers": d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(lowerCamelCase__ ) # Copy weights lowerCamelCase_ = teacher.config_class(**lowerCamelCase__ ) lowerCamelCase_ = AutoModelForSeqaSeqLM.from_config(lowerCamelCase__ ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. lowerCamelCase_ = student.load_state_dict(teacher.state_dict() , strict=lowerCamelCase__ ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save lowerCamelCase_ , lowerCamelCase_ = list(range(lowerCamelCase__ ) ), list(range(lowerCamelCase__ ) ) logger.info( F'Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to' F' {save_path}' ) student.save_pretrained(lowerCamelCase__ ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: lowerCamelCase_ = pick_layers_to_copy(lowerCamelCase__ , lowerCamelCase__ ) if d_layers_to_copy is None: lowerCamelCase_ = pick_layers_to_copy(lowerCamelCase__ , lowerCamelCase__ ) try: if hasattr( lowerCamelCase__ , "prophetnet" ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , lowerCamelCase__ ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , lowerCamelCase__ ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , lowerCamelCase__ ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , lowerCamelCase__ ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , lowerCamelCase__ ) copy_layers(teacher.decoder.block , student.decoder.block , lowerCamelCase__ ) logger.info( F'Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}' ) lowerCamelCase_ = { "teacher_type": teacher.config.model_type, "copied_encoder_layers": e_layers_to_copy, "copied_decoder_layers": d_layers_to_copy, } student.save_pretrained(lowerCamelCase__ ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
19
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A =logging.get_logger(__name__) def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: lowerCamelCase_ = 1_9_2 lowerCamelCase_ = 7_6_8 lowerCamelCase_ = 1_2 lowerCamelCase_ = 3 lowerCamelCase_ = [8_0_0, 1_3_3_3] lowerCamelCase_ = False elif yolos_name == "yolos_s_dWr": lowerCamelCase_ = 3_3_0 lowerCamelCase_ = 1_4 lowerCamelCase_ = 6 lowerCamelCase_ = 1_3_2_0 elif "yolos_s" in yolos_name: lowerCamelCase_ = 3_8_4 lowerCamelCase_ = 1_5_3_6 lowerCamelCase_ = 1_2 lowerCamelCase_ = 6 elif "yolos_b" in yolos_name: lowerCamelCase_ = [8_0_0, 1_3_4_4] lowerCamelCase_ = 9_1 lowerCamelCase_ = "huggingface/label-files" lowerCamelCase_ = "coco-detection-id2label.json" lowerCamelCase_ = json.load(open(hf_hub_download(lowerCamelCase__ , lowerCamelCase__ , repo_type="dataset" ) , "r" ) ) lowerCamelCase_ = {int(lowerCamelCase__ ): v for k, v in idalabel.items()} lowerCamelCase_ = idalabel lowerCamelCase_ = {v: k for k, v in idalabel.items()} return config def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = False ): for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowerCamelCase_ = state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) lowerCamelCase_ = state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict lowerCamelCase_ = in_proj_weight[: config.hidden_size, :] lowerCamelCase_ = in_proj_bias[: config.hidden_size] lowerCamelCase_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCamelCase_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowerCamelCase_ = in_proj_weight[-config.hidden_size :, :] lowerCamelCase_ = in_proj_bias[-config.hidden_size :] def lowerCamelCase_ ( lowerCamelCase__ ): if "backbone" in name: lowerCamelCase_ = name.replace("backbone" , "vit" ) if "cls_token" in name: lowerCamelCase_ = name.replace("cls_token" , "embeddings.cls_token" ) if "det_token" in name: lowerCamelCase_ = name.replace("det_token" , "embeddings.detection_tokens" ) if "mid_pos_embed" in name: lowerCamelCase_ = name.replace("mid_pos_embed" , "encoder.mid_position_embeddings" ) if "pos_embed" in name: lowerCamelCase_ = name.replace("pos_embed" , "embeddings.position_embeddings" ) if "patch_embed.proj" in name: lowerCamelCase_ = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "blocks" in name: lowerCamelCase_ = name.replace("blocks" , "encoder.layer" ) 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 "class_embed" in name: lowerCamelCase_ = name.replace("class_embed" , "class_labels_classifier" ) if "bbox_embed" in name: lowerCamelCase_ = name.replace("bbox_embed" , "bbox_predictor" ) if "vit.norm" in name: lowerCamelCase_ = name.replace("vit.norm" , "vit.layernorm" ) return name def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): for key in orig_state_dict.copy().keys(): lowerCamelCase_ = orig_state_dict.pop(lowerCamelCase__ ) if "qkv" in key: lowerCamelCase_ = key.split("." ) lowerCamelCase_ = int(key_split[2] ) lowerCamelCase_ = model.vit.encoder.layer[layer_num].attention.attention.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_ ( ): lowerCamelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCamelCase_ = Image.open(requests.get(lowerCamelCase__ , stream=lowerCamelCase__ ).raw ) return im @torch.no_grad() def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = False ): lowerCamelCase_ = get_yolos_config(lowerCamelCase__ ) # load original state_dict lowerCamelCase_ = torch.load(lowerCamelCase__ , map_location="cpu" )["model"] # load 🤗 model lowerCamelCase_ = YolosForObjectDetection(lowerCamelCase__ ) model.eval() lowerCamelCase_ = convert_state_dict(lowerCamelCase__ , lowerCamelCase__ ) model.load_state_dict(lowerCamelCase__ ) # Check outputs on an image, prepared by YolosImageProcessor lowerCamelCase_ = 8_0_0 if yolos_name != "yolos_ti" else 5_1_2 lowerCamelCase_ = YolosImageProcessor(format="coco_detection" , size=lowerCamelCase__ ) lowerCamelCase_ = image_processor(images=prepare_img() , return_tensors="pt" ) lowerCamelCase_ = model(**lowerCamelCase__ ) lowerCamelCase_ , lowerCamelCase_ = outputs.logits, outputs.pred_boxes lowerCamelCase_ , lowerCamelCase_ = None, None if yolos_name == "yolos_ti": lowerCamelCase_ = torch.tensor( [[-39.50_22, -11.98_20, -17.68_88], [-29.95_74, -9.97_69, -17.76_91], [-42.32_81, -20.72_00, -30.62_94]] ) lowerCamelCase_ = torch.tensor( [[0.40_21, 0.08_36, 0.79_79], [0.01_84, 0.26_09, 0.03_64], [0.17_81, 0.20_04, 0.20_95]] ) elif yolos_name == "yolos_s_200_pre": lowerCamelCase_ = torch.tensor( [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]] ) lowerCamelCase_ = torch.tensor( [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]] ) elif yolos_name == "yolos_s_300_pre": lowerCamelCase_ = torch.tensor( [[-36.22_20, -14.43_85, -23.54_57], [-35.69_70, -14.75_83, -21.39_35], [-31.59_39, -13.60_42, -16.80_49]] ) lowerCamelCase_ = torch.tensor( [[0.76_14, 0.23_16, 0.47_28], [0.71_68, 0.44_95, 0.38_55], [0.49_96, 0.14_66, 0.99_96]] ) elif yolos_name == "yolos_s_dWr": lowerCamelCase_ = torch.tensor( [[-42.86_68, -24.10_49, -41.16_90], [-34.74_56, -14.12_74, -24.91_94], [-33.78_98, -12.19_46, -25.64_95]] ) lowerCamelCase_ = torch.tensor( [[0.55_87, 0.27_73, 0.06_05], [0.50_04, 0.30_14, 0.99_94], [0.49_99, 0.15_48, 0.99_94]] ) elif yolos_name == "yolos_base": lowerCamelCase_ = torch.tensor( [[-40.60_64, -24.30_84, -32.64_47], [-55.19_90, -30.77_19, -35.58_77], [-51.43_11, -33.35_07, -35.64_62]] ) lowerCamelCase_ = torch.tensor( [[0.55_55, 0.27_94, 0.06_55], [0.90_49, 0.26_64, 0.18_94], [0.91_83, 0.19_84, 0.16_35]] ) else: raise ValueError(F'Unknown yolos_name: {yolos_name}' ) assert torch.allclose(logits[0, :3, :3] , lowerCamelCase__ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , lowerCamelCase__ , atol=1e-4 ) Path(lowerCamelCase__ ).mkdir(exist_ok=lowerCamelCase__ ) print(F'Saving model {yolos_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCamelCase__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(lowerCamelCase__ ) if push_to_hub: lowerCamelCase_ = { "yolos_ti": "yolos-tiny", "yolos_s_200_pre": "yolos-small", "yolos_s_300_pre": "yolos-small-300", "yolos_s_dWr": "yolos-small-dwr", "yolos_base": "yolos-base", } print("Pushing to the hub..." ) lowerCamelCase_ = model_mapping[yolos_name] image_processor.push_to_hub(lowerCamelCase__ , organization="hustvl" ) model.push_to_hub(lowerCamelCase__ , organization="hustvl" ) if __name__ == "__main__": __A =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--yolos_name''', default='''yolos_s_200_pre''', type=str, help=( '''Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',''' ''' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.''' ), ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original state dict (.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.''' ) __A =parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
19
1
A__ = [ 999, 800, 799, 600, 599, 500, 400, 399, 377, 355, 333, 311, 288, 266, 244, 222, 200, 199, 177, 155, 133, 111, 88, 66, 44, 22, 0, ] A__ = [ 999, 976, 952, 928, 905, 882, 858, 857, 810, 762, 715, 714, 572, 429, 428, 286, 285, 238, 190, 143, 142, 118, 95, 71, 47, 24, 0, ] A__ = [ 999, 988, 977, 966, 955, 944, 933, 922, 911, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 350, 300, 299, 266, 233, 200, 199, 179, 159, 140, 120, 100, 99, 88, 77, 66, 55, 44, 33, 22, 11, 0, ] A__ = [ 999, 995, 992, 989, 985, 981, 978, 975, 971, 967, 964, 961, 957, 956, 951, 947, 942, 937, 933, 928, 923, 919, 914, 913, 908, 903, 897, 892, 887, 881, 876, 871, 870, 864, 858, 852, 846, 840, 834, 828, 827, 820, 813, 806, 799, 792, 785, 784, 777, 770, 763, 756, 749, 742, 741, 733, 724, 716, 707, 699, 698, 688, 677, 666, 656, 655, 645, 634, 623, 613, 612, 598, 584, 570, 569, 555, 541, 527, 526, 505, 484, 483, 462, 440, 439, 396, 395, 352, 351, 308, 307, 264, 263, 220, 219, 176, 132, 88, 44, 0, ] A__ = [ 999, 997, 995, 992, 990, 988, 986, 984, 981, 979, 977, 975, 972, 970, 968, 966, 964, 961, 959, 957, 956, 954, 951, 949, 946, 944, 941, 939, 936, 934, 931, 929, 926, 924, 921, 919, 916, 914, 913, 910, 907, 905, 902, 899, 896, 893, 891, 888, 885, 882, 879, 877, 874, 871, 870, 867, 864, 861, 858, 855, 852, 849, 846, 843, 840, 837, 834, 831, 828, 827, 824, 821, 817, 814, 811, 808, 804, 801, 798, 795, 791, 788, 785, 784, 780, 777, 774, 770, 766, 763, 760, 756, 752, 749, 746, 742, 741, 737, 733, 730, 726, 722, 718, 714, 710, 707, 703, 699, 698, 694, 690, 685, 681, 677, 673, 669, 664, 660, 656, 655, 650, 646, 641, 636, 632, 627, 622, 618, 613, 612, 607, 602, 596, 591, 586, 580, 575, 570, 569, 563, 557, 551, 545, 539, 533, 527, 526, 519, 512, 505, 498, 491, 484, 483, 474, 466, 457, 449, 440, 439, 428, 418, 407, 396, 395, 381, 366, 352, 351, 330, 308, 307, 286, 264, 263, 242, 220, 219, 176, 175, 132, 131, 88, 44, 0, ] A__ = [ 999, 991, 982, 974, 966, 958, 950, 941, 933, 925, 916, 908, 900, 899, 874, 850, 825, 800, 799, 700, 600, 500, 400, 300, 200, 100, 0, ] A__ = [ 999, 992, 985, 978, 971, 964, 957, 949, 942, 935, 928, 921, 914, 907, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 300, 299, 200, 199, 100, 99, 0, ] A__ = [ 999, 996, 992, 989, 985, 982, 979, 975, 972, 968, 965, 961, 958, 955, 951, 948, 944, 941, 938, 934, 931, 927, 924, 920, 917, 914, 910, 907, 903, 900, 899, 891, 884, 876, 869, 861, 853, 846, 838, 830, 823, 815, 808, 800, 799, 788, 777, 766, 755, 744, 733, 722, 711, 700, 699, 688, 677, 666, 655, 644, 633, 622, 611, 600, 599, 585, 571, 557, 542, 528, 514, 500, 499, 485, 471, 457, 442, 428, 414, 400, 399, 379, 359, 340, 320, 300, 299, 279, 259, 240, 220, 200, 199, 166, 133, 100, 99, 66, 33, 0, ]
371
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device A__ = False class a ( unittest.TestCase ): pass @nightly @require_torch_gpu class a ( unittest.TestCase ): def __lowerCamelCase ( self :List[Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self :List[str] ): snake_case__ : Dict = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' ,torch_dtype=torch.floataa ) pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) snake_case__ : str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) snake_case__ : List[Any] = torch.manual_seed(0 ) snake_case__ : Optional[int] = pipe.dual_guided( prompt='''first prompt''' ,image=__lowercase ,text_to_image_strength=0.75 ,generator=__lowercase ,guidance_scale=7.5 ,num_inference_steps=2 ,output_type='''numpy''' ,).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__lowercase ) snake_case__ : Any = VersatileDiffusionPipeline.from_pretrained(__lowercase ,torch_dtype=torch.floataa ) pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) snake_case__ : List[str] = generator.manual_seed(0 ) snake_case__ : Any = pipe.dual_guided( prompt='''first prompt''' ,image=__lowercase ,text_to_image_strength=0.75 ,generator=__lowercase ,guidance_scale=7.5 ,num_inference_steps=2 ,output_type='''numpy''' ,).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def __lowerCamelCase ( self :Dict ): snake_case__ : Optional[int] = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' ,torch_dtype=torch.floataa ) pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) snake_case__ : List[Any] = '''cyberpunk 2077''' snake_case__ : Optional[int] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) snake_case__ : Optional[int] = torch.manual_seed(0 ) snake_case__ : Any = pipe.dual_guided( prompt=__lowercase ,image=__lowercase ,text_to_image_strength=0.75 ,generator=__lowercase ,guidance_scale=7.5 ,num_inference_steps=5_0 ,output_type='''numpy''' ,).images snake_case__ : int = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) snake_case__ : List[str] = np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 snake_case__ : Any = '''A painting of a squirrel eating a burger ''' snake_case__ : List[str] = torch.manual_seed(0 ) snake_case__ : int = pipe.text_to_image( prompt=__lowercase ,generator=__lowercase ,guidance_scale=7.5 ,num_inference_steps=5_0 ,output_type='''numpy''' ).images snake_case__ : Optional[int] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) snake_case__ : str = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 snake_case__ : List[Any] = pipe.image_variation(__lowercase ,generator=__lowercase ,output_type='''numpy''' ).images snake_case__ : str = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) snake_case__ : Optional[int] = np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
44
0
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } _lowerCAmelCase = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" for attribute in key.split(""".""" ): lowerCAmelCase__ : Optional[Any] = getattr(UpperCamelCase , UpperCamelCase ) if weight_type is not None: lowerCAmelCase__ : int = getattr(UpperCamelCase , UpperCamelCase ).shape else: lowerCAmelCase__ : int = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": lowerCAmelCase__ : Union[str, Any] = value elif weight_type == "weight_g": lowerCAmelCase__ : Any = value elif weight_type == "weight_v": lowerCAmelCase__ : Optional[int] = value elif weight_type == "bias": lowerCAmelCase__ : List[str] = value elif weight_type == "running_mean": lowerCAmelCase__ : List[str] = value elif weight_type == "running_var": lowerCAmelCase__ : int = value elif weight_type == "num_batches_tracked": lowerCAmelCase__ : Tuple = value elif weight_type == "inv_freq": lowerCAmelCase__ : str = value else: lowerCAmelCase__ : str = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : List[str] = [] lowerCAmelCase__ : List[str] = fairseq_model.state_dict() lowerCAmelCase__ : Any = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): lowerCAmelCase__ : int = False if "conv_layers" in name: load_conv_layer( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , hf_model.config.feat_extract_norm == """group""" , ) lowerCAmelCase__ : Optional[int] = True else: for key, mapped_key in MAPPING.items(): lowerCAmelCase__ : List[Any] = """wav2vec2_conformer.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: lowerCAmelCase__ : List[Any] = True if "*" in mapped_key: lowerCAmelCase__ : str = name.split(UpperCamelCase )[0].split(""".""" )[-2] lowerCAmelCase__ : List[str] = mapped_key.replace("""*""" , UpperCamelCase ) if "pos_bias_u" in name: lowerCAmelCase__ : List[str] = None elif "pos_bias_v" in name: lowerCAmelCase__ : List[str] = None elif "weight_g" in name: lowerCAmelCase__ : Optional[int] = """weight_g""" elif "weight_v" in name: lowerCAmelCase__ : Union[str, Any] = """weight_v""" elif "bias" in name: lowerCAmelCase__ : Union[str, Any] = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj lowerCAmelCase__ : Union[str, Any] = """weight""" elif "running_mean" in name: lowerCAmelCase__ : List[Any] = """running_mean""" elif "inv_freq" in name: lowerCAmelCase__ : int = """inv_freq""" elif "running_var" in name: lowerCAmelCase__ : Any = """running_var""" elif "num_batches_tracked" in name: lowerCAmelCase__ : Union[str, Any] = """num_batches_tracked""" else: lowerCAmelCase__ : str = None set_recursively(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) continue if not is_used: unused_weights.append(UpperCamelCase ) logger.warning(f"""Unused weights: {unused_weights}""" ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : Optional[Any] = full_name.split("""conv_layers.""" )[-1] lowerCAmelCase__ : Any = name.split(""".""" ) lowerCAmelCase__ : Optional[int] = int(items[0] ) lowerCAmelCase__ : Tuple = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) lowerCAmelCase__ : 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.""" ) lowerCAmelCase__ : Any = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) lowerCAmelCase__ : int = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) lowerCAmelCase__ : Union[str, Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(UpperCamelCase ) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase=True ): """simple docstring""" if config_path is not None: lowerCAmelCase__ : Tuple = WavaVecaConformerConfig.from_pretrained(UpperCamelCase , hidden_act="""swish""" ) else: lowerCAmelCase__ : Union[str, Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: lowerCAmelCase__ : Tuple = """rotary""" if is_finetuned: if dict_path: lowerCAmelCase__ : int = Dictionary.load(UpperCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq lowerCAmelCase__ : Tuple = target_dict.pad_index lowerCAmelCase__ : Union[str, Any] = target_dict.bos_index lowerCAmelCase__ : List[str] = target_dict.eos_index lowerCAmelCase__ : Dict = len(target_dict.symbols ) lowerCAmelCase__ : Tuple = os.path.join(UpperCamelCase , """vocab.json""" ) if not os.path.isdir(UpperCamelCase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(UpperCamelCase ) ) return os.makedirs(UpperCamelCase , exist_ok=UpperCamelCase ) lowerCAmelCase__ : Optional[Any] = target_dict.indices # fairseq has the <pad> and <s> switched lowerCAmelCase__ : Optional[int] = 0 lowerCAmelCase__ : int = 1 with open(UpperCamelCase , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : Tuple = WavaVecaCTCTokenizer( UpperCamelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=UpperCamelCase , ) lowerCAmelCase__ : int = True if config.feat_extract_norm == """layer""" else False lowerCAmelCase__ : Union[str, Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=UpperCamelCase , return_attention_mask=UpperCamelCase , ) lowerCAmelCase__ : List[Any] = WavaVecaProcessor(feature_extractor=UpperCamelCase , tokenizer=UpperCamelCase ) processor.save_pretrained(UpperCamelCase ) lowerCAmelCase__ : List[str] = WavaVecaConformerForCTC(UpperCamelCase ) else: lowerCAmelCase__ : Tuple = WavaVecaConformerForPreTraining(UpperCamelCase ) if is_finetuned: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: lowerCAmelCase__ : List[Any] = argparse.Namespace(task="""audio_pretraining""" ) lowerCAmelCase__ : List[str] = fairseq.tasks.setup_task(UpperCamelCase ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ : str = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=UpperCamelCase ) lowerCAmelCase__ : Union[str, Any] = model[0].eval() recursively_load_weights(UpperCamelCase , UpperCamelCase , not is_finetuned ) hf_wavavec.save_pretrained(UpperCamelCase ) if __name__ == "__main__": _lowerCAmelCase = 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''' ) _lowerCAmelCase = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
37
'''simple docstring''' import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __lowercase : Any = logging.get_logger(__name__) __lowercase : Any = OrderedDict( [ ('''audio-spectrogram-transformer''', '''ASTFeatureExtractor'''), ('''beit''', '''BeitFeatureExtractor'''), ('''chinese_clip''', '''ChineseCLIPFeatureExtractor'''), ('''clap''', '''ClapFeatureExtractor'''), ('''clip''', '''CLIPFeatureExtractor'''), ('''clipseg''', '''ViTFeatureExtractor'''), ('''conditional_detr''', '''ConditionalDetrFeatureExtractor'''), ('''convnext''', '''ConvNextFeatureExtractor'''), ('''cvt''', '''ConvNextFeatureExtractor'''), ('''data2vec-audio''', '''Wav2Vec2FeatureExtractor'''), ('''data2vec-vision''', '''BeitFeatureExtractor'''), ('''deformable_detr''', '''DeformableDetrFeatureExtractor'''), ('''deit''', '''DeiTFeatureExtractor'''), ('''detr''', '''DetrFeatureExtractor'''), ('''dinat''', '''ViTFeatureExtractor'''), ('''donut-swin''', '''DonutFeatureExtractor'''), ('''dpt''', '''DPTFeatureExtractor'''), ('''encodec''', '''EncodecFeatureExtractor'''), ('''flava''', '''FlavaFeatureExtractor'''), ('''glpn''', '''GLPNFeatureExtractor'''), ('''groupvit''', '''CLIPFeatureExtractor'''), ('''hubert''', '''Wav2Vec2FeatureExtractor'''), ('''imagegpt''', '''ImageGPTFeatureExtractor'''), ('''layoutlmv2''', '''LayoutLMv2FeatureExtractor'''), ('''layoutlmv3''', '''LayoutLMv3FeatureExtractor'''), ('''levit''', '''LevitFeatureExtractor'''), ('''maskformer''', '''MaskFormerFeatureExtractor'''), ('''mctct''', '''MCTCTFeatureExtractor'''), ('''mobilenet_v1''', '''MobileNetV1FeatureExtractor'''), ('''mobilenet_v2''', '''MobileNetV2FeatureExtractor'''), ('''mobilevit''', '''MobileViTFeatureExtractor'''), ('''nat''', '''ViTFeatureExtractor'''), ('''owlvit''', '''OwlViTFeatureExtractor'''), ('''perceiver''', '''PerceiverFeatureExtractor'''), ('''poolformer''', '''PoolFormerFeatureExtractor'''), ('''regnet''', '''ConvNextFeatureExtractor'''), ('''resnet''', '''ConvNextFeatureExtractor'''), ('''segformer''', '''SegformerFeatureExtractor'''), ('''sew''', '''Wav2Vec2FeatureExtractor'''), ('''sew-d''', '''Wav2Vec2FeatureExtractor'''), ('''speech_to_text''', '''Speech2TextFeatureExtractor'''), ('''speecht5''', '''SpeechT5FeatureExtractor'''), ('''swiftformer''', '''ViTFeatureExtractor'''), ('''swin''', '''ViTFeatureExtractor'''), ('''swinv2''', '''ViTFeatureExtractor'''), ('''table-transformer''', '''DetrFeatureExtractor'''), ('''timesformer''', '''VideoMAEFeatureExtractor'''), ('''tvlt''', '''TvltFeatureExtractor'''), ('''unispeech''', '''Wav2Vec2FeatureExtractor'''), ('''unispeech-sat''', '''Wav2Vec2FeatureExtractor'''), ('''van''', '''ConvNextFeatureExtractor'''), ('''videomae''', '''VideoMAEFeatureExtractor'''), ('''vilt''', '''ViltFeatureExtractor'''), ('''vit''', '''ViTFeatureExtractor'''), ('''vit_mae''', '''ViTFeatureExtractor'''), ('''vit_msn''', '''ViTFeatureExtractor'''), ('''wav2vec2''', '''Wav2Vec2FeatureExtractor'''), ('''wav2vec2-conformer''', '''Wav2Vec2FeatureExtractor'''), ('''wavlm''', '''Wav2Vec2FeatureExtractor'''), ('''whisper''', '''WhisperFeatureExtractor'''), ('''xclip''', '''CLIPFeatureExtractor'''), ('''yolos''', '''YolosFeatureExtractor'''), ] ) __lowercase : List[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def lowercase_ ( _lowercase ) -> List[Any]: '''simple docstring''' for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: lowerCamelCase_ : Dict = model_type_to_module_name(_lowercase ) lowerCamelCase_ : Any = importlib.import_module(F""".{module_name}""" , '''transformers.models''' ) try: return getattr(_lowercase , _lowercase ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(_lowercase , '''__name__''' , _lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. lowerCamelCase_ : Optional[Any] = importlib.import_module('''transformers''' ) if hasattr(_lowercase , _lowercase ): return getattr(_lowercase , _lowercase ) return None def lowercase_ ( _lowercase , _lowercase = None , _lowercase = False , _lowercase = False , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = False , **_lowercase , ) -> List[str]: '''simple docstring''' lowerCamelCase_ : Optional[int] = get_file_from_repo( _lowercase , _lowercase , cache_dir=_lowercase , force_download=_lowercase , resume_download=_lowercase , proxies=_lowercase , use_auth_token=_lowercase , revision=_lowercase , local_files_only=_lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the feature extractor configuration file, will try to use the model config instead.''' ) return {} with open(_lowercase , encoding='''utf-8''' ) as reader: return json.load(_lowercase ) class __lowercase : def __init__(self ): raise EnvironmentError( '''AutoFeatureExtractor is designed to be instantiated ''' '''using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(A ) def UpperCAmelCase__ (cls , A , **A ): lowerCamelCase_ : Optional[Any] = kwargs.pop('''config''' , A ) lowerCamelCase_ : Union[str, Any] = kwargs.pop('''trust_remote_code''' , A ) lowerCamelCase_ : List[Any] = True lowerCamelCase_, lowerCamelCase_ : List[Any] = FeatureExtractionMixin.get_feature_extractor_dict(A , **A ) lowerCamelCase_ : Tuple = config_dict.get('''feature_extractor_type''' , A ) lowerCamelCase_ : List[Any] = None if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): lowerCamelCase_ : Optional[Any] = config_dict['''auto_map''']['''AutoFeatureExtractor'''] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(A , A ): lowerCamelCase_ : List[str] = AutoConfig.from_pretrained(A , **A ) # It could be in `config.feature_extractor_type`` lowerCamelCase_ : Union[str, Any] = getattr(A , '''feature_extractor_type''' , A ) if hasattr(A , '''auto_map''' ) and "AutoFeatureExtractor" in config.auto_map: lowerCamelCase_ : Optional[int] = config.auto_map['''AutoFeatureExtractor'''] if feature_extractor_class is not None: lowerCamelCase_ : Any = feature_extractor_class_from_name(A ) lowerCamelCase_ : Optional[int] = feature_extractor_auto_map is not None lowerCamelCase_ : Optional[Any] = feature_extractor_class is not None or type(A ) in FEATURE_EXTRACTOR_MAPPING lowerCamelCase_ : int = resolve_trust_remote_code( A , A , A , A ) if has_remote_code and trust_remote_code: lowerCamelCase_ : Any = get_class_from_dynamic_module( A , A , **A ) lowerCamelCase_ : List[Any] = kwargs.pop('''code_revision''' , A ) if os.path.isdir(A ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(A , **A ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(A , **A ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(A ) in FEATURE_EXTRACTOR_MAPPING: lowerCamelCase_ : Optional[int] = FEATURE_EXTRACTOR_MAPPING[type(A )] return feature_extractor_class.from_dict(A , **A ) raise ValueError( F"""Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a """ F"""`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following """ F"""`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def UpperCAmelCase__ (A , A ): FEATURE_EXTRACTOR_MAPPING.register(A , A )
318
0
def UpperCamelCase ( __lowercase : int = 10_00 ): '''simple docstring''' A_ : Optional[int] = 1, 1 A_ : List[str] = 2 while True: A_ : Dict = 0 A_ : Any = fa + fa A_ : Union[str, Any] = fa, f index += 1 for _ in str(__lowercase ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
366
import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor _UpperCAmelCase = logging.get_logger(__name__) class UpperCAmelCase ( __A ): '''simple docstring''' def __init__( self , *lowercase , **lowercase ): """simple docstring""" warnings.warn( 'The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DonutImageProcessor instead.' , lowercase , ) super().__init__(*lowercase , **lowercase )
192
0
import math import random from typing import Any from .hill_climbing import SearchProblem def A ( _lowerCamelCase , _lowerCamelCase = True , _lowerCamelCase = math.inf , _lowerCamelCase = -math.inf , _lowerCamelCase = math.inf , _lowerCamelCase = -math.inf , _lowerCamelCase = False , _lowerCamelCase = 100 , _lowerCamelCase = 0.01 , _lowerCamelCase = 1 , ): '''simple docstring''' _lowerCAmelCase : List[Any] = False _lowerCAmelCase : Any = search_prob _lowerCAmelCase : str = start_temperate _lowerCAmelCase : Tuple = [] _lowerCAmelCase : List[Any] = 0 _lowerCAmelCase : Union[str, Any] = None while not search_end: _lowerCAmelCase : Dict = current_state.score() if best_state is None or current_score > best_state.score(): _lowerCAmelCase : List[str] = current_state scores.append(_lowerCamelCase ) iterations += 1 _lowerCAmelCase : str = None _lowerCAmelCase : Tuple = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _lowerCAmelCase : str = random.randint(0 , len(_lowerCamelCase ) - 1 ) # picking a random neighbor _lowerCAmelCase : Union[str, Any] = neighbors.pop(_lowerCamelCase ) _lowerCAmelCase : List[Any] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _lowerCAmelCase : Union[str, Any] = change * -1 # in case we are finding minimum if change > 0: # improves the solution _lowerCAmelCase : Optional[int] = picked_neighbor else: _lowerCAmelCase : Optional[int] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _lowerCAmelCase : Dict = picked_neighbor _lowerCAmelCase : Any = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _lowerCAmelCase : Optional[Any] = True else: _lowerCAmelCase : Tuple = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(_lowerCamelCase ) , _lowerCamelCase ) plt.xlabel("Iterations" ) plt.ylabel("Function values" ) plt.show() return best_state if __name__ == "__main__": def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) _snake_case = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) _snake_case = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f'''and 50 > y > - 5 found via hill climbing: {local_min.score()}''' ) # starting the problem with initial coordinates (12, 47) _snake_case = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) _snake_case = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f'''and 50 > y > - 5 found via hill climbing: {local_min.score()}''' ) def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' return (3 * x**2) - (6 * y) _snake_case = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) _snake_case = simulated_annealing(prob, find_max=False, visualization=True) print( "The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f'''{local_min.score()}''' ) _snake_case = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) _snake_case = simulated_annealing(prob, find_max=True, visualization=True) print( "The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f'''{local_min.score()}''' )
36
import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel, CLIPTokenizerFast from utils import get_device, get_timestamp, show_pil class UpperCAmelCase_ : def __init__( self, __a = "cpu", __a = "openai/clip-vit-large-patch14"): '''simple docstring''' _lowerCAmelCase : Optional[int] = device _lowerCAmelCase : Optional[int] = CLIPTokenizerFast.from_pretrained(__a) _lowerCAmelCase : Any = [0.48_145_466, 0.4_578_275, 0.40_821_073] _lowerCAmelCase : Union[str, Any] = [0.26_862_954, 0.26_130_258, 0.27_577_711] _lowerCAmelCase : Tuple = torchvision.transforms.Normalize(self.image_mean, self.image_std) _lowerCAmelCase : Optional[int] = torchvision.transforms.Resize(224) _lowerCAmelCase : Dict = torchvision.transforms.CenterCrop(224) def snake_case__ ( self, __a): '''simple docstring''' _lowerCAmelCase : Optional[Any] = self.resize(__a) _lowerCAmelCase : List[str] = self.center_crop(__a) _lowerCAmelCase : Optional[Any] = self.normalize(__a) return images def __call__( self, __a=None, __a=None, **__a): '''simple docstring''' _lowerCAmelCase : str = self.tokenizer(text=__a, **__a) _lowerCAmelCase : List[str] = self.preprocess_img(__a) _lowerCAmelCase : Tuple = {key: value.to(self.device) for (key, value) in encoding.items()} return encoding class UpperCAmelCase_ ( nn.Module): def __init__( self, __a=10, __a=0.01, __a=None, __a=None, __a=None, __a=None, __a=None, __a=None, __a=False, __a=True, __a="image", __a=True, __a=False, __a=False, __a=False, ): '''simple docstring''' super().__init__() _lowerCAmelCase : List[str] = None _lowerCAmelCase : List[str] = device if device else get_device() if vqgan: _lowerCAmelCase : Union[str, Any] = vqgan else: _lowerCAmelCase : Optional[Any] = load_vqgan(self.device, conf_path=__a, ckpt_path=__a) self.vqgan.eval() if clip: _lowerCAmelCase : str = clip else: _lowerCAmelCase : int = CLIPModel.from_pretrained("openai/clip-vit-base-patch32") self.clip.to(self.device) _lowerCAmelCase : Optional[int] = ProcessorGradientFlow(device=self.device) _lowerCAmelCase : Any = iterations _lowerCAmelCase : List[Any] = lr _lowerCAmelCase : Tuple = log _lowerCAmelCase : List[str] = make_grid _lowerCAmelCase : int = return_val _lowerCAmelCase : Dict = quantize _lowerCAmelCase : Any = self.vqgan.decoder.z_shape def snake_case__ ( self, __a=None, __a=None, __a=5, __a=True): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = [] if output_path is None: _lowerCAmelCase : List[Any] = "./animation.gif" if input_path is None: _lowerCAmelCase : str = self.save_path _lowerCAmelCase : str = sorted(glob(input_path + "/*")) if not len(__a): raise ValueError( "No images found in save path, aborting (did you pass save_intermediate=True to the generate" " function?)") if len(__a) == 1: print("Only one image found in save path, (did you pass save_intermediate=True to the generate function?)") _lowerCAmelCase : Optional[int] = total_duration / len(__a) _lowerCAmelCase : Union[str, Any] = [frame_duration] * len(__a) if extend_frames: _lowerCAmelCase : Any = 1.5 _lowerCAmelCase : List[str] = 3 for file_name in paths: if file_name.endswith(".png"): images.append(imageio.imread(__a)) imageio.mimsave(__a, __a, duration=__a) print(f"gif saved to {output_path}") def snake_case__ ( self, __a=None, __a=None): '''simple docstring''' if not (path or img): raise ValueError("Input either path or tensor") if img is not None: raise NotImplementedError _lowerCAmelCase : Dict = preprocess(Image.open(__a), target_image_size=256).to(self.device) _lowerCAmelCase : Dict = preprocess_vqgan(__a) _lowerCAmelCase , *_lowerCAmelCase : str = self.vqgan.encode(__a) return z def snake_case__ ( self, __a): '''simple docstring''' _lowerCAmelCase : Optional[Any] = self.latent.detach().requires_grad_() _lowerCAmelCase : Dict = base_latent + transform_vector if self.quantize: _lowerCAmelCase , *_lowerCAmelCase : List[Any] = self.vqgan.quantize(__a) else: _lowerCAmelCase : Any = trans_latent return self.vqgan.decode(__a) def snake_case__ ( self, __a, __a, __a=None): '''simple docstring''' _lowerCAmelCase : int = self.clip_preprocessor(text=__a, images=__a, return_tensors="pt", padding=__a) _lowerCAmelCase : Optional[int] = self.clip(**__a) _lowerCAmelCase : Any = clip_outputs.logits_per_image if weights is not None: _lowerCAmelCase : Tuple = similarity_logits * weights return similarity_logits.sum() def snake_case__ ( self, __a, __a, __a): '''simple docstring''' _lowerCAmelCase : List[Any] = self._get_clip_similarity(pos_prompts["prompts"], __a, weights=(1 / pos_prompts["weights"])) if neg_prompts: _lowerCAmelCase : List[Any] = self._get_clip_similarity(neg_prompts["prompts"], __a, weights=neg_prompts["weights"]) else: _lowerCAmelCase : Union[str, Any] = torch.tensor([1], device=self.device) _lowerCAmelCase : List[str] = -torch.log(__a) + torch.log(__a) return loss def snake_case__ ( self, __a, __a, __a): '''simple docstring''' _lowerCAmelCase : Optional[Any] = torch.randn_like(self.latent, requires_grad=__a, device=self.device) _lowerCAmelCase : Optional[int] = torch.optim.Adam([vector], lr=self.lr) for i in range(self.iterations): optim.zero_grad() _lowerCAmelCase : Any = self._add_vector(__a) _lowerCAmelCase : Optional[Any] = loop_post_process(__a) _lowerCAmelCase : Optional[Any] = self._get_CLIP_loss(__a, __a, __a) print("CLIP loss", __a) if self.log: wandb.log({"CLIP Loss": clip_loss}) clip_loss.backward(retain_graph=__a) optim.step() if self.return_val == "image": yield custom_to_pil(transformed_img[0]) else: yield vector def snake_case__ ( self, __a, __a, __a): '''simple docstring''' wandb.init(reinit=__a, project="face-editor") wandb.config.update({"Positive Prompts": positive_prompts}) wandb.config.update({"Negative Prompts": negative_prompts}) wandb.config.update({"lr": self.lr, "iterations": self.iterations}) if image_path: _lowerCAmelCase : str = Image.open(__a) _lowerCAmelCase : int = image.resize((256, 256)) wandb.log("Original Image", wandb.Image(__a)) def snake_case__ ( self, __a): '''simple docstring''' if not prompts: return [] _lowerCAmelCase : int = [] _lowerCAmelCase : List[str] = [] if isinstance(__a, __a): _lowerCAmelCase : Union[str, Any] = [prompt.strip() for prompt in prompts.split("|")] for prompt in prompts: if isinstance(__a, (tuple, list)): _lowerCAmelCase : Optional[Any] = prompt[0] _lowerCAmelCase : Union[str, Any] = float(prompt[1]) elif ":" in prompt: _lowerCAmelCase , _lowerCAmelCase : int = prompt.split(":") _lowerCAmelCase : Optional[Any] = float(__a) else: _lowerCAmelCase : Optional[int] = prompt _lowerCAmelCase : List[Any] = 1.0 processed_prompts.append(__a) weights.append(__a) return { "prompts": processed_prompts, "weights": torch.tensor(__a, device=self.device), } def snake_case__ ( self, __a, __a=None, __a=None, __a=True, __a=False, __a=True, __a=True, __a=None, ): '''simple docstring''' if image_path: _lowerCAmelCase : List[Any] = self._get_latent(__a) else: _lowerCAmelCase : Any = torch.randn(self.latent_dim, device=self.device) if self.log: self._init_logging(__a, __a, __a) assert pos_prompts, "You must provide at least one positive prompt." _lowerCAmelCase : int = self.process_prompts(__a) _lowerCAmelCase : List[str] = self.process_prompts(__a) if save_final and save_path is None: _lowerCAmelCase : int = os.path.join("./outputs/", "_".join(pos_prompts["prompts"])) if not os.path.exists(__a): os.makedirs(__a) else: _lowerCAmelCase : Tuple = save_path + "_" + get_timestamp() os.makedirs(__a) _lowerCAmelCase : Tuple = save_path _lowerCAmelCase : List[Any] = self.vqgan.decode(self.latent)[0] if show_intermediate: print("Original Image") show_pil(custom_to_pil(__a)) _lowerCAmelCase : int = loop_post_process(__a) for iter, transformed_img in enumerate(self._optimize_CLIP(__a, __a, __a)): if show_intermediate: show_pil(__a) if save_intermediate: transformed_img.save(os.path.join(self.save_path, f"iter_{iter:03d}.png")) if self.log: wandb.log({"Image": wandb.Image(__a)}) if show_final: show_pil(__a) if save_final: transformed_img.save(os.path.join(self.save_path, f"iter_{iter:03d}_final.png"))
36
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
366
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class lowercase ( TensorFormatter[Mapping, """torch.Tensor""", Mapping] ): '''simple docstring''' def __init__( self , _snake_case=None , **_snake_case ) -> int: """simple docstring""" super().__init__(features=_snake_case ) UpperCAmelCase = torch_tensor_kwargs import torch # noqa import torch at initialization def snake_case_ ( self , _snake_case ) -> Union[str, Any]: """simple docstring""" import torch if isinstance(_snake_case , _snake_case ) and column: if all( isinstance(_snake_case , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(_snake_case ) return column def snake_case_ ( self , _snake_case ) -> Optional[int]: """simple docstring""" import torch if isinstance(_snake_case , (str, bytes, type(_snake_case )) ): return value elif isinstance(_snake_case , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() UpperCAmelCase = {} if isinstance(_snake_case , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): UpperCAmelCase = {'''dtype''': torch.intaa} elif isinstance(_snake_case , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): UpperCAmelCase = {'''dtype''': torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(_snake_case , PIL.Image.Image ): UpperCAmelCase = np.asarray(_snake_case ) return torch.tensor(_snake_case , **{**default_dtype, **self.torch_tensor_kwargs} ) def snake_case_ ( self , _snake_case ) -> Optional[Any]: """simple docstring""" import torch # support for torch, tf, jax etc. if hasattr(_snake_case , '''__array__''' ) and not isinstance(_snake_case , torch.Tensor ): UpperCAmelCase = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(_snake_case , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(_snake_case ) for substruct in data_struct] ) elif isinstance(_snake_case , (list, tuple) ): return self._consolidate([self.recursive_tensorize(_snake_case ) for substruct in data_struct] ) return self._tensorize(_snake_case ) def snake_case_ ( self , _snake_case ) -> List[Any]: """simple docstring""" return map_nested(self._recursive_tensorize , _snake_case , map_list=_snake_case ) def snake_case_ ( self , _snake_case ) -> Mapping: """simple docstring""" UpperCAmelCase = self.numpy_arrow_extractor().extract_row(_snake_case ) UpperCAmelCase = self.python_features_decoder.decode_row(_snake_case ) return self.recursive_tensorize(_snake_case ) def snake_case_ ( self , _snake_case ) -> "torch.Tensor": """simple docstring""" UpperCAmelCase = self.numpy_arrow_extractor().extract_column(_snake_case ) UpperCAmelCase = self.python_features_decoder.decode_column(_snake_case , pa_table.column_names[0] ) UpperCAmelCase = self.recursive_tensorize(_snake_case ) UpperCAmelCase = self._consolidate(_snake_case ) return column def snake_case_ ( self , _snake_case ) -> Mapping: """simple docstring""" UpperCAmelCase = self.numpy_arrow_extractor().extract_batch(_snake_case ) UpperCAmelCase = self.python_features_decoder.decode_batch(_snake_case ) UpperCAmelCase = self.recursive_tensorize(_snake_case ) for column_name in batch: UpperCAmelCase = self._consolidate(batch[column_name] ) return batch
152
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : List[Any] = logging.get_logger(__name__) UpperCAmelCase_ : str = { 'facebook/deit-base-distilled-patch16-224': ( 'https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Tuple = '''deit''' def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str]=7_6_8 , SCREAMING_SNAKE_CASE__ : List[Any]=1_2 , SCREAMING_SNAKE_CASE__ : List[str]=1_2 , SCREAMING_SNAKE_CASE__ : Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Tuple="gelu" , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : Dict=0.02 , SCREAMING_SNAKE_CASE__ : Tuple=1E-12 , SCREAMING_SNAKE_CASE__ : Optional[int]=2_2_4 , SCREAMING_SNAKE_CASE__ : Tuple=1_6 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=1_6 , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = hidden_size a_ : Dict = num_hidden_layers a_ : int = num_attention_heads a_ : Optional[Any] = intermediate_size a_ : Optional[int] = hidden_act a_ : int = hidden_dropout_prob a_ : Any = attention_probs_dropout_prob a_ : List[str] = initializer_range a_ : Optional[Any] = layer_norm_eps a_ : str = image_size a_ : Dict = patch_size a_ : Union[str, Any] = num_channels a_ : Tuple = qkv_bias a_ : int = encoder_stride class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = version.parse('''1.11''' ) @property def SCREAMING_SNAKE_CASE ( self : str ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def SCREAMING_SNAKE_CASE ( self : int ) -> float: return 1E-4
32
# Lint as: python3 import itertools import os import re lowerCamelCase = re.compile(R'([A-Z]+)([A-Z][a-z])') lowerCamelCase = re.compile(R'([a-z\d])([A-Z])') lowerCamelCase = re.compile(R'(?<!_)_(?!_)') lowerCamelCase = re.compile(R'(_{2,})') lowerCamelCase = R'^\w+(\.\w+)*$' lowerCamelCase = R'<>:/\|?*' def a_ ( SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' _lowerCamelCase : List[str] =_uppercase_uppercase_re.sub(r'\1_\2' , SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : List[Any] =_lowercase_uppercase_re.sub(r'\1_\2' , SCREAMING_SNAKE_CASE__ ) return name.lower() def a_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' _lowerCamelCase : Tuple =_single_underscore_re.split(SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Tuple =[_multiple_underscores_re.split(SCREAMING_SNAKE_CASE__ ) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(SCREAMING_SNAKE_CASE__ ) if n != '' ) def a_ ( SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' if os.path.basename(SCREAMING_SNAKE_CASE__ ) != name: raise ValueError(F'''Should be a dataset name, not a path: {name}''' ) return camelcase_to_snakecase(SCREAMING_SNAKE_CASE__ ) def a_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' if os.path.basename(SCREAMING_SNAKE_CASE__ ) != name: raise ValueError(F'''Should be a dataset name, not a path: {name}''' ) if not re.match(_split_re , SCREAMING_SNAKE_CASE__ ): raise ValueError(F'''Split name should match \'{_split_re}\'\' but got \'{split}\'.''' ) return F'''{filename_prefix_for_name(SCREAMING_SNAKE_CASE__ )}-{split}''' def a_ ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int=None ): '''simple docstring''' _lowerCamelCase : Union[str, Any] =filename_prefix_for_split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if filetype_suffix: prefix += F'''.{filetype_suffix}''' _lowerCamelCase : Optional[Any] =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return F'''{filepath}*''' def a_ ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None ): '''simple docstring''' _lowerCamelCase : Dict =filename_prefix_for_split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Union[str, Any] =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if shard_lengths: _lowerCamelCase : Union[str, Any] =len(SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Optional[int] =[F'''{prefix}-{shard_id:05d}-of-{num_shards:05d}''' for shard_id in range(SCREAMING_SNAKE_CASE__ )] if filetype_suffix: _lowerCamelCase : List[Any] =[filename + F'''.{filetype_suffix}''' for filename in filenames] return filenames else: _lowerCamelCase : Any =prefix if filetype_suffix: filename += F'''.{filetype_suffix}''' return [filename]
199
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __lowercase ( lowerCamelCase : int=None ): if subparsers is not None: UpperCamelCase_ : Optional[Any] = subparsers.add_parser('test' ) else: UpperCamelCase_ : Tuple = argparse.ArgumentParser('Accelerate test command' ) parser.add_argument( '--config_file' , default=lowerCamelCase , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=lowerCamelCase ) return parser def __lowercase ( lowerCamelCase : List[Any] ): UpperCamelCase_ : Tuple = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['test_utils', 'scripts', 'test_script.py'] ) if args.config_file is None: UpperCamelCase_ : int = script_name else: UpperCamelCase_ : Union[str, Any] = F"--config_file={args.config_file} {script_name}" UpperCamelCase_ : Optional[int] = ['accelerate-launch'] + test_args.split() UpperCamelCase_ : int = execute_subprocess_async(lowerCamelCase , env=os.environ.copy() ) if result.returncode == 0: print('Test is a success! You are ready for your distributed training!' ) def __lowercase ( ): UpperCamelCase_ : Any = test_command_parser() UpperCamelCase_ : Optional[int] = parser.parse_args() test_command(lowerCamelCase ) if __name__ == "__main__": main()
354
from typing import Any class _lowercase : def __init__( self : Optional[Any] , snake_case : Any ) -> Any: """simple docstring""" UpperCamelCase_ : Union[str, Any] = data UpperCamelCase_ : Any = None def __repr__( self : int ) -> str: """simple docstring""" return f"Node({self.data})" class _lowercase : def __init__( self : str ) -> int: """simple docstring""" UpperCamelCase_ : int = None def __iter__( self : Optional[Any] ) -> Any: """simple docstring""" UpperCamelCase_ : Tuple = self.head while node: yield node.data UpperCamelCase_ : Dict = node.next def __len__( self : int ) -> int: """simple docstring""" return sum(1 for _ in self ) def __repr__( self : List[Any] ) -> str: """simple docstring""" return "->".join([str(snake_case ) for item in self] ) def __getitem__( self : Union[str, Any] , snake_case : int ) -> Any: """simple docstring""" if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Any , snake_case : int , snake_case : Any ) -> None: """simple docstring""" if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) UpperCamelCase_ : int = self.head for _ in range(snake_case ): UpperCamelCase_ : Union[str, Any] = current.next UpperCamelCase_ : Any = data def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case : Any ) -> None: """simple docstring""" self.insert_nth(len(self ) , snake_case ) def SCREAMING_SNAKE_CASE__ ( self : Dict , snake_case : Any ) -> None: """simple docstring""" self.insert_nth(0 , snake_case ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , snake_case : int , snake_case : Any ) -> None: """simple docstring""" if not 0 <= index <= len(self ): raise IndexError('list index out of range' ) UpperCamelCase_ : Union[str, Any] = Node(snake_case ) if self.head is None: UpperCamelCase_ : Union[str, Any] = new_node elif index == 0: UpperCamelCase_ : int = self.head # link new_node to head UpperCamelCase_ : List[str] = new_node else: UpperCamelCase_ : List[str] = self.head for _ in range(index - 1 ): UpperCamelCase_ : Union[str, Any] = temp.next UpperCamelCase_ : Dict = temp.next UpperCamelCase_ : Optional[Any] = new_node def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> None: # print every node data """simple docstring""" print(self ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Any: """simple docstring""" return self.delete_nth(0 ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Any: # delete from tail """simple docstring""" return self.delete_nth(len(self ) - 1 ) def SCREAMING_SNAKE_CASE__ ( self : Any , snake_case : int = 0 ) -> Any: """simple docstring""" if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError('List index out of range.' ) UpperCamelCase_ : str = self.head # default first node if index == 0: UpperCamelCase_ : List[Any] = self.head.next else: UpperCamelCase_ : Dict = self.head for _ in range(index - 1 ): UpperCamelCase_ : Tuple = temp.next UpperCamelCase_ : List[Any] = temp.next UpperCamelCase_ : Dict = temp.next.next return delete_node.data def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> bool: """simple docstring""" return self.head is None def SCREAMING_SNAKE_CASE__ ( self : str ) -> None: """simple docstring""" UpperCamelCase_ : str = None UpperCamelCase_ : int = self.head while current: # Store the current node's next node. UpperCamelCase_ : Tuple = current.next # Make the current node's next point backwards UpperCamelCase_ : Tuple = prev # Make the previous node be the current node UpperCamelCase_ : List[Any] = current # Make the current node the next node (to progress iteration) UpperCamelCase_ : Dict = next_node # Return prev in order to put the head at the end UpperCamelCase_ : Union[str, Any] = prev def __lowercase ( ): UpperCamelCase_ : Union[str, Any] = LinkedList() assert linked_list.is_empty() is True assert str(lowerCamelCase ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(lowerCamelCase ) == i linked_list.insert_nth(lowerCamelCase , i + 1 ) assert str(lowerCamelCase ) == "->".join(str(lowerCamelCase ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(lowerCamelCase ) == "->".join(str(lowerCamelCase ) for i in range(0 , 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(lowerCamelCase ) == 9 assert str(lowerCamelCase ) == "->".join(str(lowerCamelCase ) for i in range(1 , 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): UpperCamelCase_ : Optional[int] = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(lowerCamelCase ) == "->".join(str(lowerCamelCase ) for i in range(-8 , 1 ) ) def __lowercase ( ): UpperCamelCase_ : List[str] = [ -9, 100, Node(77345112 ), 'dlrow olleH', 7, 5555, 0, -1_9_2.5_5_5_5_5, 'Hello, world!', 7_7.9, Node(10 ), None, None, 1_2.2_0, ] UpperCamelCase_ : Optional[int] = LinkedList() for i in test_input: linked_list.insert_tail(lowerCamelCase ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(lowerCamelCase ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase_ : List[Any] = linked_list.delete_head() assert result == -9 assert ( str(lowerCamelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase_ : Tuple = linked_list.delete_tail() assert result == 1_2.2 assert ( str(lowerCamelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase_ : Optional[Any] = linked_list.delete_nth(10 ) assert result is None assert ( str(lowerCamelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node('Hello again, world!' ) ) assert ( str(lowerCamelCase ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(lowerCamelCase ) assert ( str(lowerCamelCase ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(lowerCamelCase ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def __lowercase ( ): from doctest import testmod testmod() UpperCamelCase_ : Dict = LinkedList() linked_list.insert_head(input('Inserting 1st at head ' ).strip() ) linked_list.insert_head(input('Inserting 2nd at head ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() linked_list.insert_tail(input('\nInserting 1st at tail ' ).strip() ) linked_list.insert_tail(input('Inserting 2nd at tail ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() print('\nDelete head' ) linked_list.delete_head() print('Delete tail' ) linked_list.delete_tail() print('\nPrint list:' ) linked_list.print_list() print('\nReverse linked list' ) linked_list.reverse() print('\nPrint list:' ) linked_list.print_list() print('\nString representation of linked list:' ) print(lowerCamelCase ) print('\nReading/changing Node data using indexing:' ) print(F"Element at Position 1: {linked_list[1]}" ) UpperCamelCase_ : Optional[Any] = input('Enter New Value: ' ).strip() print('New list:' ) print(lowerCamelCase ) print(F"length of linked_list is : {len(lowerCamelCase )}" ) if __name__ == "__main__": main()
50
0
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING A: Optional[int] = logging.get_logger(__name__) A: List[Any] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class SCREAMING_SNAKE_CASE__ ( _lowerCamelCase ): __lowerCAmelCase : Dict = '''deta''' __lowerCAmelCase : List[str] = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=900 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.25 , **_SCREAMING_SNAKE_CASE , ) -> List[str]: '''simple docstring''' if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) UpperCAmelCase : Any = CONFIG_MAPPING['''resnet'''](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(_A , _A ): UpperCAmelCase : Dict = backbone_config.pop("""model_type""" ) UpperCAmelCase : Dict = CONFIG_MAPPING[backbone_model_type] UpperCAmelCase : Any = config_class.from_dict(_A ) UpperCAmelCase : int = backbone_config UpperCAmelCase : Dict = num_queries UpperCAmelCase : Dict = max_position_embeddings UpperCAmelCase : Union[str, Any] = d_model UpperCAmelCase : str = encoder_ffn_dim UpperCAmelCase : Optional[int] = encoder_layers UpperCAmelCase : Tuple = encoder_attention_heads UpperCAmelCase : List[str] = decoder_ffn_dim UpperCAmelCase : Union[str, Any] = decoder_layers UpperCAmelCase : List[str] = decoder_attention_heads UpperCAmelCase : List[Any] = dropout UpperCAmelCase : str = attention_dropout UpperCAmelCase : List[str] = activation_dropout UpperCAmelCase : List[str] = activation_function UpperCAmelCase : Optional[int] = init_std UpperCAmelCase : int = init_xavier_std UpperCAmelCase : int = encoder_layerdrop UpperCAmelCase : Dict = auxiliary_loss UpperCAmelCase : Any = position_embedding_type # deformable attributes UpperCAmelCase : List[str] = num_feature_levels UpperCAmelCase : int = encoder_n_points UpperCAmelCase : Optional[Any] = decoder_n_points UpperCAmelCase : int = two_stage UpperCAmelCase : str = two_stage_num_proposals UpperCAmelCase : Optional[int] = with_box_refine UpperCAmelCase : Union[str, Any] = assign_first_stage 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 UpperCAmelCase : Any = class_cost UpperCAmelCase : Optional[int] = bbox_cost UpperCAmelCase : Tuple = giou_cost # Loss coefficients UpperCAmelCase : int = mask_loss_coefficient UpperCAmelCase : Any = dice_loss_coefficient UpperCAmelCase : int = bbox_loss_coefficient UpperCAmelCase : Optional[Any] = giou_loss_coefficient UpperCAmelCase : int = eos_coefficient UpperCAmelCase : Any = focal_alpha super().__init__(is_encoder_decoder=_A , **_A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' UpperCAmelCase : List[str] = copy.deepcopy(self.__dict__ ) UpperCAmelCase : Union[str, Any] = self.backbone_config.to_dict() UpperCAmelCase : str = self.__class__.model_type return output
109
def snake_case( __magic_name__ = 50 ) -> int: '''simple docstring''' lowercase : Union[str, Any] = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'''{solution() = }''')
308
0
from collections import deque from math import floor from random import random from time import time class lowercase : def __init__( self : Dict ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = {} def __snake_case( self : List[Any] , _UpperCamelCase : int , _UpperCamelCase : Dict , _UpperCamelCase : Dict=1 ) -> Dict: '''simple docstring''' if self.graph.get(_UpperCamelCase ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: SCREAMING_SNAKE_CASE = [[w, v]] if not self.graph.get(_UpperCamelCase ): SCREAMING_SNAKE_CASE = [] def __snake_case( self : Dict ) -> Any: '''simple docstring''' return list(self.graph ) def __snake_case( self : Optional[int] , _UpperCamelCase : str , _UpperCamelCase : Tuple ) -> str: '''simple docstring''' if self.graph.get(_UpperCamelCase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_UpperCamelCase ) def __snake_case( self : Union[str, Any] , _UpperCamelCase : str=-2 , _UpperCamelCase : str=-1 ) -> Union[str, Any]: '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] if s == -2: SCREAMING_SNAKE_CASE = list(self.graph )[0] stack.append(_UpperCamelCase ) visited.append(_UpperCamelCase ) SCREAMING_SNAKE_CASE = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_UpperCamelCase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_UpperCamelCase ) != 0: SCREAMING_SNAKE_CASE = stack[len(_UpperCamelCase ) - 1] else: SCREAMING_SNAKE_CASE = ss # check if se have reached the starting point if len(_UpperCamelCase ) == 0: return visited def __snake_case( self : Tuple , _UpperCamelCase : str=-1 ) -> List[str]: '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE = floor(random() * 10_000 ) + 10 for i in range(_UpperCamelCase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): SCREAMING_SNAKE_CASE = floor(random() * c ) + 1 if n != i: self.add_pair(_UpperCamelCase , _UpperCamelCase , 1 ) def __snake_case( self : Dict , _UpperCamelCase : Optional[int]=-2 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = deque() SCREAMING_SNAKE_CASE = [] if s == -2: SCREAMING_SNAKE_CASE = list(self.graph )[0] d.append(_UpperCamelCase ) visited.append(_UpperCamelCase ) while d: SCREAMING_SNAKE_CASE = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def __snake_case( self : int , _UpperCamelCase : str ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def __snake_case( self : Dict , _UpperCamelCase : List[str] ) -> Optional[Any]: '''simple docstring''' return len(self.graph[u] ) def __snake_case( self : List[Any] , _UpperCamelCase : List[str]=-2 ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] if s == -2: SCREAMING_SNAKE_CASE = list(self.graph )[0] stack.append(_UpperCamelCase ) visited.append(_UpperCamelCase ) SCREAMING_SNAKE_CASE = s SCREAMING_SNAKE_CASE = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(_UpperCamelCase ) != 0: SCREAMING_SNAKE_CASE = stack[len(_UpperCamelCase ) - 1] else: SCREAMING_SNAKE_CASE = ss # check if se have reached the starting point if len(_UpperCamelCase ) == 0: return sorted_nodes def __snake_case( self : int ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = list(self.graph )[0] stack.append(_UpperCamelCase ) visited.append(_UpperCamelCase ) SCREAMING_SNAKE_CASE = -2 SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = s SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE = len(_UpperCamelCase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE = True if len(_UpperCamelCase ) != 0: SCREAMING_SNAKE_CASE = stack[len(_UpperCamelCase ) - 1] else: SCREAMING_SNAKE_CASE = False indirect_parents.append(_UpperCamelCase ) SCREAMING_SNAKE_CASE = s SCREAMING_SNAKE_CASE = ss # check if se have reached the starting point if len(_UpperCamelCase ) == 0: return list(_UpperCamelCase ) def __snake_case( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = list(self.graph )[0] stack.append(_UpperCamelCase ) visited.append(_UpperCamelCase ) SCREAMING_SNAKE_CASE = -2 SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = s SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE = len(_UpperCamelCase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE = True if len(_UpperCamelCase ) != 0: SCREAMING_SNAKE_CASE = stack[len(_UpperCamelCase ) - 1] else: SCREAMING_SNAKE_CASE = False indirect_parents.append(_UpperCamelCase ) SCREAMING_SNAKE_CASE = s SCREAMING_SNAKE_CASE = ss # check if se have reached the starting point if len(_UpperCamelCase ) == 0: return False def __snake_case( self : str , _UpperCamelCase : str=-2 , _UpperCamelCase : List[str]=-1 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = time() self.dfs(_UpperCamelCase , _UpperCamelCase ) SCREAMING_SNAKE_CASE = time() return end - begin def __snake_case( self : Tuple , _UpperCamelCase : str=-2 ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = time() self.bfs(_UpperCamelCase ) SCREAMING_SNAKE_CASE = time() return end - begin class lowercase : def __init__( self : List[str] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = {} def __snake_case( self : Optional[Any] , _UpperCamelCase : str , _UpperCamelCase : str , _UpperCamelCase : Any=1 ) -> Tuple: '''simple docstring''' if self.graph.get(_UpperCamelCase ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist SCREAMING_SNAKE_CASE = [[w, v]] # add the other way if self.graph.get(_UpperCamelCase ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist SCREAMING_SNAKE_CASE = [[w, u]] def __snake_case( self : Optional[int] , _UpperCamelCase : List[Any] , _UpperCamelCase : List[Any] ) -> int: '''simple docstring''' if self.graph.get(_UpperCamelCase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_UpperCamelCase ) # the other way round if self.graph.get(_UpperCamelCase ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_UpperCamelCase ) def __snake_case( self : Union[str, Any] , _UpperCamelCase : Optional[Any]=-2 , _UpperCamelCase : Tuple=-1 ) -> Any: '''simple docstring''' if s == d: return [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] if s == -2: SCREAMING_SNAKE_CASE = list(self.graph )[0] stack.append(_UpperCamelCase ) visited.append(_UpperCamelCase ) SCREAMING_SNAKE_CASE = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(_UpperCamelCase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(_UpperCamelCase ) != 0: SCREAMING_SNAKE_CASE = stack[len(_UpperCamelCase ) - 1] else: SCREAMING_SNAKE_CASE = ss # check if se have reached the starting point if len(_UpperCamelCase ) == 0: return visited def __snake_case( self : List[str] , _UpperCamelCase : Any=-1 ) -> Optional[Any]: '''simple docstring''' if c == -1: SCREAMING_SNAKE_CASE = floor(random() * 10_000 ) + 10 for i in range(_UpperCamelCase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): SCREAMING_SNAKE_CASE = floor(random() * c ) + 1 if n != i: self.add_pair(_UpperCamelCase , _UpperCamelCase , 1 ) def __snake_case( self : List[str] , _UpperCamelCase : str=-2 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = deque() SCREAMING_SNAKE_CASE = [] if s == -2: SCREAMING_SNAKE_CASE = list(self.graph )[0] d.append(_UpperCamelCase ) visited.append(_UpperCamelCase ) while d: SCREAMING_SNAKE_CASE = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def __snake_case( self : Dict , _UpperCamelCase : Optional[int] ) -> Optional[int]: '''simple docstring''' return len(self.graph[u] ) def __snake_case( self : Union[str, Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = list(self.graph )[0] stack.append(_UpperCamelCase ) visited.append(_UpperCamelCase ) SCREAMING_SNAKE_CASE = -2 SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = s SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE = len(_UpperCamelCase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE = True if len(_UpperCamelCase ) != 0: SCREAMING_SNAKE_CASE = stack[len(_UpperCamelCase ) - 1] else: SCREAMING_SNAKE_CASE = False indirect_parents.append(_UpperCamelCase ) SCREAMING_SNAKE_CASE = s SCREAMING_SNAKE_CASE = ss # check if se have reached the starting point if len(_UpperCamelCase ) == 0: return list(_UpperCamelCase ) def __snake_case( self : List[str] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = list(self.graph )[0] stack.append(_UpperCamelCase ) visited.append(_UpperCamelCase ) SCREAMING_SNAKE_CASE = -2 SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = s SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: SCREAMING_SNAKE_CASE = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): SCREAMING_SNAKE_CASE = len(_UpperCamelCase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) SCREAMING_SNAKE_CASE = node[1] break # check if all the children are visited if s == ss: stack.pop() SCREAMING_SNAKE_CASE = True if len(_UpperCamelCase ) != 0: SCREAMING_SNAKE_CASE = stack[len(_UpperCamelCase ) - 1] else: SCREAMING_SNAKE_CASE = False indirect_parents.append(_UpperCamelCase ) SCREAMING_SNAKE_CASE = s SCREAMING_SNAKE_CASE = ss # check if se have reached the starting point if len(_UpperCamelCase ) == 0: return False def __snake_case( self : str ) -> Dict: '''simple docstring''' return list(self.graph ) def __snake_case( self : List[str] , _UpperCamelCase : Tuple=-2 , _UpperCamelCase : Dict=-1 ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = time() self.dfs(_UpperCamelCase , _UpperCamelCase ) SCREAMING_SNAKE_CASE = time() return end - begin def __snake_case( self : List[Any] , _UpperCamelCase : List[Any]=-2 ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = time() self.bfs(_UpperCamelCase ) SCREAMING_SNAKE_CASE = time() return end - begin
206
from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image 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_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract _lowerCamelCase : str = logging.get_logger(__name__) def __lowerCamelCase (UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ): return [ int(1_0_0_0 * (box[0] / width) ), int(1_0_0_0 * (box[1] / height) ), int(1_0_0_0 * (box[2] / width) ), int(1_0_0_0 * (box[3] / height) ), ] def __lowerCamelCase (UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Optional[str] , UpperCAmelCase__ : Optional[str] ): SCREAMING_SNAKE_CASE = to_pil_image(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = pil_image.size SCREAMING_SNAKE_CASE = pytesseract.image_to_data(UpperCAmelCase__ , lang=UpperCAmelCase__ , output_type="dict" , config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = data["text"], data["left"], data["top"], data["width"], data["height"] # filter empty words and corresponding coordinates SCREAMING_SNAKE_CASE = [idx for idx, word in enumerate(UpperCAmelCase__ ) if not word.strip()] SCREAMING_SNAKE_CASE = [word for idx, word in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format SCREAMING_SNAKE_CASE = [] for x, y, w, h in zip(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ): SCREAMING_SNAKE_CASE = [x, y, x + w, y + h] actual_boxes.append(UpperCAmelCase__ ) # finally, normalize the bounding boxes SCREAMING_SNAKE_CASE = [] for box in actual_boxes: normalized_boxes.append(normalize_box(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) ) assert len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class lowercase ( a ): lowercase__ : Optional[int] = ["""pixel_values"""] def __init__( self : int , _UpperCamelCase : bool = True , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCamelCase : bool = True , _UpperCamelCase : float = 1 / 255 , _UpperCamelCase : bool = True , _UpperCamelCase : Union[float, Iterable[float]] = None , _UpperCamelCase : Union[float, Iterable[float]] = None , _UpperCamelCase : bool = True , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[str] = "" , **_UpperCamelCase : Union[str, Any] , ) -> None: '''simple docstring''' super().__init__(**_UpperCamelCase ) SCREAMING_SNAKE_CASE = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = resample SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_value SCREAMING_SNAKE_CASE = do_normalize SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE = image_std if image_std is not None else IMAGENET_STANDARD_STD SCREAMING_SNAKE_CASE = apply_ocr SCREAMING_SNAKE_CASE = ocr_lang SCREAMING_SNAKE_CASE = tesseract_config def __snake_case( self : Dict , _UpperCamelCase : np.ndarray , _UpperCamelCase : Dict[str, int] , _UpperCamelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : List[Any] , ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) SCREAMING_SNAKE_CASE = (size["height"], size["width"]) return resize(_UpperCamelCase , size=_UpperCamelCase , resample=_UpperCamelCase , data_format=_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : Union[str, Any] , _UpperCamelCase : np.ndarray , _UpperCamelCase : Union[int, float] , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : Optional[int] , ) -> np.ndarray: '''simple docstring''' return rescale(_UpperCamelCase , scale=_UpperCamelCase , data_format=_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : int , _UpperCamelCase : np.ndarray , _UpperCamelCase : Union[float, Iterable[float]] , _UpperCamelCase : Union[float, Iterable[float]] , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : Optional[Any] , ) -> np.ndarray: '''simple docstring''' return normalize(_UpperCamelCase , mean=_UpperCamelCase , std=_UpperCamelCase , data_format=_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : Tuple , _UpperCamelCase : ImageInput , _UpperCamelCase : bool = None , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : Optional[Any]=None , _UpperCamelCase : bool = None , _UpperCamelCase : float = None , _UpperCamelCase : bool = None , _UpperCamelCase : Union[float, Iterable[float]] = None , _UpperCamelCase : Union[float, Iterable[float]] = None , _UpperCamelCase : bool = None , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[Union[str, TensorType]] = None , _UpperCamelCase : ChannelDimension = ChannelDimension.FIRST , **_UpperCamelCase : List[Any] , ) -> PIL.Image.Image: '''simple docstring''' SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE = apply_ocr if apply_ocr is not None else self.apply_ocr SCREAMING_SNAKE_CASE = ocr_lang if ocr_lang is not None else self.ocr_lang SCREAMING_SNAKE_CASE = tesseract_config if tesseract_config is not None else self.tesseract_config SCREAMING_SNAKE_CASE = make_list_of_images(_UpperCamelCase ) if not valid_images(_UpperCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("If do_normalize is True, image_mean and image_std must be specified." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(_UpperCamelCase ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self , "pytesseract" ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for image in images: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = apply_tesseract(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) words_batch.append(_UpperCamelCase ) boxes_batch.append(_UpperCamelCase ) if do_resize: SCREAMING_SNAKE_CASE = [self.resize(image=_UpperCamelCase , size=_UpperCamelCase , resample=_UpperCamelCase ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=_UpperCamelCase , scale=_UpperCamelCase ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE = [self.normalize(image=_UpperCamelCase , mean=_UpperCamelCase , std=_UpperCamelCase ) for image in images] SCREAMING_SNAKE_CASE = [to_channel_dimension_format(_UpperCamelCase , _UpperCamelCase ) for image in images] SCREAMING_SNAKE_CASE = BatchFeature(data={"pixel_values": images} , tensor_type=_UpperCamelCase ) if apply_ocr: SCREAMING_SNAKE_CASE = words_batch SCREAMING_SNAKE_CASE = boxes_batch return data
206
1
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' a__ : Any = DDIMPipeline a__ : Dict = UNCONDITIONAL_IMAGE_GENERATION_PARAMS a__ : str = PipelineTesterMixin.required_optional_params - { """num_images_per_prompt""", """latents""", """callback""", """callback_steps""", } a__ : int = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS a__ : List[Any] = False def UpperCamelCase__ ( self) -> Optional[Any]: torch.manual_seed(0) __UpperCamelCase :Optional[int] = 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''') , ) __UpperCamelCase :Union[str, Any] = DDIMScheduler() __UpperCamelCase :str = {'''unet''': unet, '''scheduler''': scheduler} return components def UpperCamelCase__ ( self , __lowercase , __lowercase=0) -> Optional[Any]: if str(__lowercase).startswith('''mps'''): __UpperCamelCase :Optional[Any] = torch.manual_seed(__lowercase) else: __UpperCamelCase :Dict = torch.Generator(device=__lowercase).manual_seed(__lowercase) __UpperCamelCase :List[str] = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def UpperCamelCase__ ( self) -> List[Any]: __UpperCamelCase :str = '''cpu''' __UpperCamelCase :Tuple = self.get_dummy_components() __UpperCamelCase :Optional[Any] = self.pipeline_class(**__lowercase) pipe.to(__lowercase) pipe.set_progress_bar_config(disable=__lowercase) __UpperCamelCase :Any = self.get_dummy_inputs(__lowercase) __UpperCamelCase :Optional[Any] = pipe(**__lowercase).images __UpperCamelCase :Union[str, Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3)) __UpperCamelCase :Optional[int] = np.array( [1.0_0_0E0_0, 5.7_1_7E-0_1, 4.7_1_7E-0_1, 1.0_0_0E0_0, 0.0_0_0E0_0, 1.0_0_0E0_0, 3.0_0_0E-0_4, 0.0_0_0E0_0, 9.0_0_0E-0_4]) __UpperCamelCase :str = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(__lowercase , 1E-3) def UpperCamelCase__ ( self) -> Union[str, Any]: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3) def UpperCamelCase__ ( self) -> Optional[int]: super().test_save_load_local(expected_max_difference=3E-3) def UpperCamelCase__ ( self) -> List[Any]: super().test_save_load_optional_components(expected_max_difference=3E-3) def UpperCamelCase__ ( self) -> Any: super().test_inference_batch_single_identical(expected_max_diff=3E-3) @slow @require_torch_gpu class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ ( self) -> Tuple: __UpperCamelCase :List[str] = '''google/ddpm-cifar10-32''' __UpperCamelCase :Union[str, Any] = UNetaDModel.from_pretrained(__lowercase) __UpperCamelCase :str = DDIMScheduler() __UpperCamelCase :Union[str, Any] = DDIMPipeline(unet=__lowercase , scheduler=__lowercase) ddim.to(__lowercase) ddim.set_progress_bar_config(disable=__lowercase) __UpperCamelCase :List[Any] = torch.manual_seed(0) __UpperCamelCase :Any = ddim(generator=__lowercase , eta=0.0 , output_type='''numpy''').images __UpperCamelCase :int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCamelCase :int = np.array([0.17_23, 0.16_17, 0.16_00, 0.16_26, 0.14_97, 0.15_13, 0.15_05, 0.14_42, 0.14_53]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def UpperCamelCase__ ( self) -> List[Any]: __UpperCamelCase :Optional[Any] = '''google/ddpm-ema-bedroom-256''' __UpperCamelCase :List[str] = UNetaDModel.from_pretrained(__lowercase) __UpperCamelCase :Dict = DDIMScheduler.from_pretrained(__lowercase) __UpperCamelCase :Optional[Any] = DDIMPipeline(unet=__lowercase , scheduler=__lowercase) ddpm.to(__lowercase) ddpm.set_progress_bar_config(disable=__lowercase) __UpperCamelCase :Dict = torch.manual_seed(0) __UpperCamelCase :str = ddpm(generator=__lowercase , output_type='''numpy''').images __UpperCamelCase :Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __UpperCamelCase :Tuple = np.array([0.00_60, 0.02_01, 0.03_44, 0.00_24, 0.00_18, 0.00_02, 0.00_22, 0.00_00, 0.00_69]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
43
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_ : str = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : int = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[int] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys a_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
137
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 ( A_ ): '''simple docstring''' lowerCAmelCase : str = ["image_processor", "tokenizer"] lowerCAmelCase : Dict = "LayoutLMv2ImageProcessor" lowerCAmelCase : int = ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__( self : List[Any] ,_snake_case : Dict=None ,_snake_case : List[str]=None ,**_snake_case : Optional[int] ) -> int: """simple docstring""" if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' ,_snake_case ,) lowercase__ : Optional[Any] = kwargs.pop('''feature_extractor''' ) lowercase__ : Optional[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(_snake_case ,_snake_case ) def __call__( self : str ,_snake_case : List[str] ,_snake_case : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,_snake_case : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None ,_snake_case : Union[List[List[int]], List[List[List[int]]]] = None ,_snake_case : Optional[Union[List[int], List[List[int]]]] = None ,_snake_case : bool = True ,_snake_case : Union[bool, str, PaddingStrategy] = False ,_snake_case : Union[bool, str, TruncationStrategy] = None ,_snake_case : Optional[int] = None ,_snake_case : int = 0 ,_snake_case : Optional[int] = None ,_snake_case : Optional[bool] = None ,_snake_case : Optional[bool] = None ,_snake_case : bool = False ,_snake_case : bool = False ,_snake_case : bool = False ,_snake_case : bool = False ,_snake_case : bool = True ,_snake_case : Optional[Union[str, TensorType]] = None ,**_snake_case : Union[str, Any] ,) -> BatchEncoding: """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes ''' '''if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError('''You cannot return overflowing tokens without returning the offsets mapping.''' ) # first, apply the image processor lowercase__ : Tuple = self.image_processor(images=_snake_case ,return_tensors=_snake_case ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_snake_case ,_snake_case ): lowercase__ : int = [text] # add batch dimension (as the image processor always adds a batch dimension) lowercase__ : List[Any] = features['''words'''] lowercase__ : Union[str, Any] = self.tokenizer( text=text if text is not None else features['''words'''] ,text_pair=text_pair if text_pair is not None else None ,boxes=boxes if boxes is not None else features['''boxes'''] ,word_labels=_snake_case ,add_special_tokens=_snake_case ,padding=_snake_case ,truncation=_snake_case ,max_length=_snake_case ,stride=_snake_case ,pad_to_multiple_of=_snake_case ,return_token_type_ids=_snake_case ,return_attention_mask=_snake_case ,return_overflowing_tokens=_snake_case ,return_special_tokens_mask=_snake_case ,return_offsets_mapping=_snake_case ,return_length=_snake_case ,verbose=_snake_case ,return_tensors=_snake_case ,**_snake_case ,) # add pixel values lowercase__ : Any = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: lowercase__ : str = self.get_overflowing_images(_snake_case ,encoded_inputs['''overflow_to_sample_mapping'''] ) lowercase__ : str = images return encoded_inputs def UpperCAmelCase ( self : Union[str, Any] ,_snake_case : List[str] ,_snake_case : Optional[int] ) -> List[Any]: """simple docstring""" lowercase__ : Union[str, Any] = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_snake_case ) != len(_snake_case ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f""" {len(_snake_case )} and {len(_snake_case )}""" ) return images_with_overflow def UpperCAmelCase ( self : Optional[Any] ,*_snake_case : Union[str, Any] ,**_snake_case : Dict ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*_snake_case ,**_snake_case ) def UpperCAmelCase ( self : Optional[int] ,*_snake_case : Tuple ,**_snake_case : Optional[Any] ) -> List[Any]: """simple docstring""" return self.tokenizer.decode(*_snake_case ,**_snake_case ) @property def UpperCAmelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" return ["input_ids", "bbox", "attention_mask", "image"] @property def UpperCAmelCase ( self : Optional[Any] ) -> int: """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' ,_snake_case ,) return self.image_processor_class @property def UpperCAmelCase ( self : List[Any] ) -> Tuple: """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' ,_snake_case ,) return self.image_processor
302
"""simple docstring""" import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class __A ( unittest.TestCase ): '''simple docstring''' @slow def UpperCAmelCase ( self : List[str] ) -> Any: """simple docstring""" lowercase__ : List[str] = FlaxXLMRobertaModel.from_pretrained('''xlm-roberta-base''' ) lowercase__ : List[str] = AutoTokenizer.from_pretrained('''xlm-roberta-base''' ) lowercase__ : List[str] = '''The dog is cute and lives in the garden house''' lowercase__ : int = jnp.array([tokenizer.encode(_snake_case )] ) lowercase__ : Any = (1, 12, 768) # batch_size, sequence_length, embedding_vector_dim lowercase__ : Tuple = jnp.array( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) lowercase__ : Optional[Any] = model(_snake_case )['''last_hidden_state'''] self.assertEqual(output.shape ,_snake_case ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] ,_snake_case ,atol=1e-3 ) )
302
1
import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class lowerCAmelCase_ ( a__ ): def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=None, **SCREAMING_SNAKE_CASE_ ) -> Dict: UpperCamelCase : Any = parent UpperCamelCase : Any = config_class UpperCamelCase : Dict = has_text_modality UpperCamelCase : Optional[Any] = kwargs UpperCamelCase : Tuple = common_properties def snake_case_ ( self ) -> Tuple: UpperCamelCase : Optional[int] = self.config_class(**self.inputs_dict ) UpperCamelCase : Any = ( ['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(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ), msg=F"""`{prop}` does not exist""" ) # Test that config has the common properties as setter for idx, name in enumerate(SCREAMING_SNAKE_CASE_ ): try: setattr(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( getattr(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ), SCREAMING_SNAKE_CASE_, msg=F"""`{name} value {idx} expected, but was {getattr(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ )}""" ) 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(SCREAMING_SNAKE_CASE_ ): try: UpperCamelCase : int = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ), SCREAMING_SNAKE_CASE_, msg=F"""`{name} value {idx} expected, but was {getattr(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def snake_case_ ( self ) -> List[str]: UpperCamelCase : Optional[int] = self.config_class(**self.inputs_dict ) UpperCamelCase : List[str] = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key], SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Optional[int]: UpperCamelCase : Union[str, Any] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase : str = os.path.join(SCREAMING_SNAKE_CASE_, 'config.json' ) config_first.to_json_file(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.config_class.from_json_file(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict() ) def snake_case_ ( self ) -> str: UpperCamelCase : List[Any] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.config_class.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict() ) def snake_case_ ( self ) -> Union[str, Any]: UpperCamelCase : Optional[int] = self.config_class(**self.inputs_dict ) UpperCamelCase : int = 'test' with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase : Optional[int] = os.path.join(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) config_first.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.config_class.from_pretrained(SCREAMING_SNAKE_CASE_, subfolder=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict() ) def snake_case_ ( self ) -> Union[str, Any]: UpperCamelCase : Any = self.config_class(**self.inputs_dict, num_labels=5 ) self.parent.assertEqual(len(config.idalabel ), 5 ) self.parent.assertEqual(len(config.labelaid ), 5 ) UpperCamelCase : str = 3 self.parent.assertEqual(len(config.idalabel ), 3 ) self.parent.assertEqual(len(config.labelaid ), 3 ) def snake_case_ ( self ) -> str: if self.config_class.is_composition: return UpperCamelCase : Tuple = self.config_class() self.parent.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> int: UpperCamelCase : int = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = self.config_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = [] 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(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) != value: wrong_values.append((key, getattr(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ), value) ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : List[Any] = '\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 snake_case_ ( self ) -> Any: 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()
119
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { '''bigscience/bloom''': '''https://huggingface.co/bigscience/bloom/resolve/main/config.json''', '''bigscience/bloom-560m''': '''https://huggingface.co/bigscience/bloom-560m/blob/main/config.json''', '''bigscience/bloom-1b1''': '''https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json''', '''bigscience/bloom-1b7''': '''https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json''', '''bigscience/bloom-3b''': '''https://huggingface.co/bigscience/bloom-3b/blob/main/config.json''', '''bigscience/bloom-7b1''': '''https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json''', } class lowerCAmelCase_ ( a__ ): UpperCAmelCase__ : Tuple = "bloom" UpperCAmelCase__ : List[Any] = ["past_key_values"] UpperCAmelCase__ : str = { "num_hidden_layers": "n_layer", "num_attention_heads": "n_head", } def __init__( self, SCREAMING_SNAKE_CASE_=25_0880, SCREAMING_SNAKE_CASE_=64, SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_=8, SCREAMING_SNAKE_CASE_=1e-5, SCREAMING_SNAKE_CASE_=0.02, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=1, SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=0.0, SCREAMING_SNAKE_CASE_=0.0, SCREAMING_SNAKE_CASE_=1, SCREAMING_SNAKE_CASE_=False, **SCREAMING_SNAKE_CASE_, ) -> Tuple: UpperCamelCase : str = vocab_size # Backward compatibility with n_embed kwarg UpperCamelCase : Optional[Any] = kwargs.pop('n_embed', SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = hidden_size if n_embed is None else n_embed UpperCamelCase : Tuple = n_layer UpperCamelCase : Dict = n_head UpperCamelCase : List[Any] = layer_norm_epsilon UpperCamelCase : Optional[int] = initializer_range UpperCamelCase : int = use_cache UpperCamelCase : int = pretraining_tp UpperCamelCase : Optional[int] = apply_residual_connection_post_layernorm UpperCamelCase : str = hidden_dropout UpperCamelCase : str = attention_dropout UpperCamelCase : List[Any] = bos_token_id UpperCamelCase : Tuple = eos_token_id UpperCamelCase : Union[str, Any] = slow_but_exact super().__init__(bos_token_id=SCREAMING_SNAKE_CASE_, eos_token_id=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) class lowerCAmelCase_ ( a__ ): UpperCAmelCase__ : Any = version.parse("1.12" ) def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = "default", SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = False, ) -> Any: super().__init__(SCREAMING_SNAKE_CASE_, task=SCREAMING_SNAKE_CASE_, patching_specs=SCREAMING_SNAKE_CASE_, use_past=SCREAMING_SNAKE_CASE_ ) if not getattr(self._config, 'pad_token_id', SCREAMING_SNAKE_CASE_ ): # TODO: how to do that better? UpperCamelCase : Tuple = 0 @property def snake_case_ ( self ) -> Mapping[str, Mapping[int, str]]: UpperCamelCase : str = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE_, direction='inputs', inverted_values_shape=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = {0: 'batch', 1: 'past_sequence + sequence'} else: UpperCamelCase : Optional[int] = {0: 'batch', 1: 'sequence'} return common_inputs @property def snake_case_ ( self ) -> int: return self._config.n_layer @property def snake_case_ ( self ) -> int: return self._config.n_head @property def snake_case_ ( self ) -> float: return 1e-3 def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = -1, SCREAMING_SNAKE_CASE_ = -1, SCREAMING_SNAKE_CASE_ = False, SCREAMING_SNAKE_CASE_ = None, ) -> Mapping[str, Any]: UpperCamelCase : Dict = super(SCREAMING_SNAKE_CASE_, self ).generate_dummy_inputs( SCREAMING_SNAKE_CASE_, batch_size=SCREAMING_SNAKE_CASE_, seq_length=SCREAMING_SNAKE_CASE_, is_pair=SCREAMING_SNAKE_CASE_, framework=SCREAMING_SNAKE_CASE_ ) # We need to order the input in the way they appears in the forward() UpperCamelCase : Any = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch UpperCamelCase , UpperCamelCase : int = common_inputs['input_ids'].shape # Not using the same length for past_key_values UpperCamelCase : Any = seqlen + 2 UpperCamelCase : Optional[int] = self._config.hidden_size // self.num_attention_heads UpperCamelCase : Any = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) UpperCamelCase : Optional[Any] = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) UpperCamelCase : List[str] = [ (torch.zeros(SCREAMING_SNAKE_CASE_ ), torch.zeros(SCREAMING_SNAKE_CASE_ )) for _ in range(self.num_layers ) ] UpperCamelCase : str = common_inputs['attention_mask'] if self.use_past: UpperCamelCase : int = ordered_inputs['attention_mask'].dtype UpperCamelCase : List[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, dtype=SCREAMING_SNAKE_CASE_ )], dim=1 ) return ordered_inputs @property def snake_case_ ( self ) -> int: return 13
119
1
import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a__ ( _SCREAMING_SNAKE_CASE ): def __init__( self , *_UpperCamelCase , _UpperCamelCase=None , _UpperCamelCase=None , **_UpperCamelCase ): """simple docstring""" super().__init__(*_UpperCamelCase , **_UpperCamelCase ) _lowercase : Union[str, Any] = eval_examples _lowercase : Optional[int] = post_process_function def _lowerCamelCase ( self , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase = "eval" ): """simple docstring""" _lowercase : Dict = self.eval_dataset if eval_dataset is None else eval_dataset _lowercase : Tuple = self.get_eval_dataloader(_UpperCamelCase ) _lowercase : int = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. _lowercase : List[Any] = self.compute_metrics _lowercase : Tuple = None _lowercase : Optional[Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _lowercase : List[str] = time.time() try: _lowercase : str = eval_loop( _UpperCamelCase , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_UpperCamelCase , metric_key_prefix=_UpperCamelCase , ) finally: _lowercase : Optional[Any] = compute_metrics _lowercase : Tuple = self.args.eval_batch_size * self.args.world_size if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( _UpperCamelCase , _UpperCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default _lowercase : Union[str, Any] = self.post_process_function(_UpperCamelCase , _UpperCamelCase , output.predictions ) _lowercase : Dict = self.compute_metrics(_UpperCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): _lowercase : str = metrics.pop(_UpperCamelCase ) metrics.update(output.metrics ) else: _lowercase : Dict = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_UpperCamelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) _lowercase : Tuple = self.callback_handler.on_evaluate(self.args , self.state , self.control , _UpperCamelCase ) return metrics def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=None , _UpperCamelCase = "test" ): """simple docstring""" _lowercase : Any = self.get_test_dataloader(_UpperCamelCase ) # Temporarily disable metric computation, we will do it in the loop here. _lowercase : Any = self.compute_metrics _lowercase : int = None _lowercase : str = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop _lowercase : List[str] = time.time() try: _lowercase : Union[str, Any] = eval_loop( _UpperCamelCase , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_UpperCamelCase , metric_key_prefix=_UpperCamelCase , ) finally: _lowercase : List[str] = compute_metrics _lowercase : Union[str, Any] = self.args.eval_batch_size * self.args.world_size if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( _UpperCamelCase , _UpperCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output _lowercase : Optional[int] = self.post_process_function(_UpperCamelCase , _UpperCamelCase , output.predictions , "predict" ) _lowercase : List[Any] = self.compute_metrics(_UpperCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): _lowercase : Any = metrics.pop(_UpperCamelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_UpperCamelCase )
351
'''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 a__ ( lowerCamelCase_ ): _SCREAMING_SNAKE_CASE : List[Any] = ['image_processor', 'tokenizer'] _SCREAMING_SNAKE_CASE : str = 'OwlViTImageProcessor' _SCREAMING_SNAKE_CASE : List[str] = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self , _UpperCamelCase=None , _UpperCamelCase=None , **_UpperCamelCase ): """simple docstring""" _lowercase : Dict = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , _UpperCamelCase , ) _lowercase : Optional[int] = kwargs.pop("feature_extractor" ) _lowercase : 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__(_UpperCamelCase , _UpperCamelCase ) def __call__( self , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase="max_length" , _UpperCamelCase="np" , **_UpperCamelCase ): """simple docstring""" 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(_UpperCamelCase , _UpperCamelCase ) or (isinstance(_UpperCamelCase , _UpperCamelCase ) and not isinstance(text[0] , _UpperCamelCase )): _lowercase : int = [self.tokenizer(_UpperCamelCase , padding=_UpperCamelCase , return_tensors=_UpperCamelCase , **_UpperCamelCase )] elif isinstance(_UpperCamelCase , _UpperCamelCase ) and isinstance(text[0] , _UpperCamelCase ): _lowercase : str = [] # Maximum number of queries across batch _lowercase : str = max([len(_UpperCamelCase ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(_UpperCamelCase ) != max_num_queries: _lowercase : List[Any] = t + [" "] * (max_num_queries - len(_UpperCamelCase )) _lowercase : Tuple = self.tokenizer(_UpperCamelCase , padding=_UpperCamelCase , return_tensors=_UpperCamelCase , **_UpperCamelCase ) encodings.append(_UpperCamelCase ) else: raise TypeError("Input text should be a string, a list of strings or a nested list of strings" ) if return_tensors == "np": _lowercase : List[Any] = np.concatenate([encoding["input_ids"] for encoding in encodings] , axis=0 ) _lowercase : Optional[Any] = np.concatenate([encoding["attention_mask"] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp _lowercase : Union[str, Any] = jnp.concatenate([encoding["input_ids"] for encoding in encodings] , axis=0 ) _lowercase : int = jnp.concatenate([encoding["attention_mask"] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch _lowercase : int = torch.cat([encoding["input_ids"] for encoding in encodings] , dim=0 ) _lowercase : Dict = torch.cat([encoding["attention_mask"] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf _lowercase : Optional[int] = tf.stack([encoding["input_ids"] for encoding in encodings] , axis=0 ) _lowercase : List[str] = tf.stack([encoding["attention_mask"] for encoding in encodings] , axis=0 ) else: raise ValueError("Target return tensor type could not be returned" ) _lowercase : Optional[int] = BatchEncoding() _lowercase : List[Any] = input_ids _lowercase : Dict = attention_mask if query_images is not None: _lowercase : int = BatchEncoding() _lowercase : Any = self.image_processor( _UpperCamelCase , return_tensors=_UpperCamelCase , **_UpperCamelCase ).pixel_values _lowercase : Any = query_pixel_values if images is not None: _lowercase : str = self.image_processor(_UpperCamelCase , return_tensors=_UpperCamelCase , **_UpperCamelCase ) if text is not None and images is not None: _lowercase : List[Any] = image_features.pixel_values return encoding elif query_images is not None and images is not None: _lowercase : Optional[Any] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**_UpperCamelCase ) , tensor_type=_UpperCamelCase ) def _lowerCamelCase ( self , *_UpperCamelCase , **_UpperCamelCase ): """simple docstring""" return self.image_processor.post_process(*_UpperCamelCase , **_UpperCamelCase ) def _lowerCamelCase ( self , *_UpperCamelCase , **_UpperCamelCase ): """simple docstring""" return self.image_processor.post_process_object_detection(*_UpperCamelCase , **_UpperCamelCase ) def _lowerCamelCase ( self , *_UpperCamelCase , **_UpperCamelCase ): """simple docstring""" return self.image_processor.post_process_image_guided_detection(*_UpperCamelCase , **_UpperCamelCase ) def _lowerCamelCase ( self , *_UpperCamelCase , **_UpperCamelCase ): """simple docstring""" return self.tokenizer.batch_decode(*_UpperCamelCase , **_UpperCamelCase ) def _lowerCamelCase ( self , *_UpperCamelCase , **_UpperCamelCase ): """simple docstring""" return self.tokenizer.decode(*_UpperCamelCase , **_UpperCamelCase ) @property def _lowerCamelCase ( self ): """simple docstring""" warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , _UpperCamelCase , ) return self.image_processor_class @property def _lowerCamelCase ( self ): """simple docstring""" warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , _UpperCamelCase , ) return self.image_processor
199
0
'''simple docstring''' import re def lowerCamelCase ( __lowerCamelCase : str ) ->bool: _SCREAMING_SNAKE_CASE = re.compile(R"""^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$""" ) if match := re.search(__lowerCamelCase , __lowerCamelCase ): return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator("""+918827897895"""))
58
def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = [] lowerCAmelCase__ : List[str] = 1 while len(lowerCamelCase_) < 1E6: constant.append(str(lowerCamelCase_)) i += 1 lowerCAmelCase__ : Union[str, Any] = ''''''.join(lowerCamelCase_) return ( int(constant[0]) * int(constant[9]) * int(constant[99]) * int(constant[999]) * int(constant[9999]) * int(constant[99999]) * int(constant[999999]) ) if __name__ == "__main__": print(solution())
129
0
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets _UpperCamelCase = '''\ @inproceedings{popovic-2015-chrf, title = "chr{F}: character n-gram {F}-score for automatic {MT} evaluation", author = "Popovi{\'c}, Maja", booktitle = "Proceedings of the Tenth Workshop on Statistical Machine Translation", month = sep, year = "2015", address = "Lisbon, Portugal", publisher = "Association for Computational Linguistics", url = "https://aclanthology.org/W15-3049", doi = "10.18653/v1/W15-3049", pages = "392--395", } @inproceedings{popovic-2017-chrf, title = "chr{F}++: words helping character n-grams", author = "Popovi{\'c}, Maja", booktitle = "Proceedings of the Second Conference on Machine Translation", month = sep, year = "2017", address = "Copenhagen, Denmark", publisher = "Association for Computational Linguistics", url = "https://aclanthology.org/W17-4770", doi = "10.18653/v1/W17-4770", pages = "612--618", } @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", } ''' _UpperCamelCase = '''\ ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches, and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation that is already present in sacrebleu. The implementation here is slightly different from sacrebleu in terms of the required input format. The length of the references and hypotheses lists need to be the same, so you may need to transpose your references compared to sacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534 See the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information. ''' _UpperCamelCase = ''' Produces ChrF(++) scores for hypotheses given reference translations. Args: predictions (list of str): The predicted sentences. references (list of list of str): The references. There should be one reference sub-list for each prediction sentence. char_order (int): Character n-gram order. Defaults to `6`. word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`. beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`. lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`. whitespace (bool): If `True`, include whitespaces when extracting character n-grams. eps_smoothing (bool): If `True`, applies epsilon smoothing similar to reference chrF++.py, NLTK and Moses implementations. If `False`, it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`. Returns: \'score\' (float): The chrF (chrF++) score, \'char_order\' (int): The character n-gram order, \'word_order\' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++, \'beta\' (int): Determine the importance of recall w.r.t precision Examples: Example 1--a simple example of calculating chrF: >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."] >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]] >>> chrf = datasets.load_metric("chrf") >>> results = chrf.compute(predictions=prediction, references=reference) >>> print(results) {\'score\': 84.64214891738334, \'char_order\': 6, \'word_order\': 0, \'beta\': 2} Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF: >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."] >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]] >>> chrf = datasets.load_metric("chrf") >>> results = chrf.compute(predictions=prediction, ... references=reference, ... word_order=2) >>> print(results) {\'score\': 82.87263732906315, \'char_order\': 6, \'word_order\': 2, \'beta\': 2} Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case: >>> prediction = ["The relationship between cats and dogs is not exactly friendly.", "a good bookshop is just a genteel black hole that knows how to read."] >>> reference = [["The relationship between dogs and cats is not exactly friendly."], ["A good bookshop is just a genteel Black Hole that knows how to read."]] >>> chrf = datasets.load_metric("chrf") >>> results = chrf.compute(predictions=prediction, ... references=reference, ... word_order=2, ... lowercase=True) >>> print(results) {\'score\': 92.12853119829202, \'char_order\': 6, \'word_order\': 2, \'beta\': 2} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase__ (self ) -> Tuple: """simple docstring""" if version.parse(scb.__version__ ) < version.parse('1.4.12' ): raise ImportWarning( 'To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n' 'You can install it with `pip install "sacrebleu>=1.4.12"`.' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='https://github.com/mjpost/sacreBLEU#chrf--chrf' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Sequence(datasets.Value('string' , id='sequence' ) , id='references' ), } ) , codebase_urls=['https://github.com/mjpost/sacreBLEU#chrf--chrf'] , reference_urls=[ 'https://github.com/m-popovic/chrF', ] , ) def UpperCamelCase__ (self , __a , __a , __a = CHRF.CHAR_ORDER , __a = CHRF.WORD_ORDER , __a = CHRF.BETA , __a = False , __a = False , __a = False , ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = len(references[0] ) if any(len(__a ) != references_per_prediction for refs in references ): raise ValueError('Sacrebleu requires the same number of references for each prediction' ) UpperCAmelCase__ = [[refs[i] for refs in references] for i in range(__a )] UpperCAmelCase__ = CHRF(__a , __a , __a , __a , __a , __a ) UpperCAmelCase__ = sb_chrf.corpus_score(__a , __a ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
363
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING _UpperCamelCase = logging.get_logger(__name__) @add_end_docstrings(_UpperCamelCase ) class lowercase ( _UpperCamelCase ): '''simple docstring''' def __init__(self , **__a ) -> Optional[Any]: """simple docstring""" super().__init__(**__a ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) self.check_model_type(__a ) def UpperCamelCase__ (self , **__a ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = {} UpperCAmelCase__ = {} UpperCAmelCase__ = {} # preprocess args if "points_per_batch" in kwargs: UpperCAmelCase__ = kwargs['points_per_batch'] if "points_per_crop" in kwargs: UpperCAmelCase__ = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: UpperCAmelCase__ = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: UpperCAmelCase__ = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: UpperCAmelCase__ = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: UpperCAmelCase__ = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: UpperCAmelCase__ = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: UpperCAmelCase__ = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: UpperCAmelCase__ = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: UpperCAmelCase__ = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: UpperCAmelCase__ = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: UpperCAmelCase__ = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self , __a , *__a , __a=None , __a=None , **__a ) -> List[str]: """simple docstring""" return super().__call__(__a , *__a , num_workers=__a , batch_size=__a , **__a ) def UpperCamelCase__ (self , __a , __a=64 , __a = 0 , __a = 512 / 1500 , __a = 32 , __a = 1 , ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = load_image(__a ) UpperCAmelCase__ = self.image_processor.size['longest_edge'] UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = self.image_processor.generate_crop_boxes( __a , __a , __a , __a , __a , __a ) UpperCAmelCase__ = self.image_processor(images=__a , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": UpperCAmelCase__ = self.get_inference_context() with inference_context(): UpperCAmelCase__ = self._ensure_tensor_on_device(__a , device=self.device ) UpperCAmelCase__ = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) UpperCAmelCase__ = image_embeddings UpperCAmelCase__ = grid_points.shape[1] UpperCAmelCase__ = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , __a , __a ): UpperCAmelCase__ = grid_points[:, i : i + points_per_batch, :, :] UpperCAmelCase__ = input_labels[:, i : i + points_per_batch] UpperCAmelCase__ = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def UpperCamelCase__ (self , __a , __a=0.88 , __a=0.95 , __a=0 , __a=1 , ) -> Dict: """simple docstring""" UpperCAmelCase__ = model_inputs.pop('input_boxes' ) UpperCAmelCase__ = model_inputs.pop('is_last' ) UpperCAmelCase__ = model_inputs.pop('original_sizes' ).tolist() UpperCAmelCase__ = model_inputs.pop('reshaped_input_sizes' ).tolist() UpperCAmelCase__ = self.model(**__a ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks UpperCAmelCase__ = model_outputs['pred_masks'] UpperCAmelCase__ = self.image_processor.post_process_masks( __a , __a , __a , __a , binarize=__a ) UpperCAmelCase__ = model_outputs['iou_scores'] UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __a , __a , __a , __a , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def UpperCamelCase__ (self , __a , __a=False , __a=False , __a=0.7 , ) -> Dict: """simple docstring""" UpperCAmelCase__ = [] UpperCAmelCase__ = [] UpperCAmelCase__ = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) UpperCAmelCase__ = torch.cat(__a ) UpperCAmelCase__ = torch.cat(__a ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = self.image_processor.post_process_for_mask_generation( __a , __a , __a , __a ) UpperCAmelCase__ = defaultdict(__a ) for output in model_outputs: for k, v in output.items(): extra[k].append(__a ) UpperCAmelCase__ = {} if output_rle_mask: UpperCAmelCase__ = rle_mask if output_bboxes_mask: UpperCAmelCase__ = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
335
0
from __future__ import annotations from math import pow, sqrt def snake_case__ ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ): '''simple docstring''' if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if resistance == 0: return {"resistance": sqrt(pow(_lowerCamelCase , 2 ) - pow(_lowerCamelCase , 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(_lowerCamelCase , 2 ) - pow(_lowerCamelCase , 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(_lowerCamelCase , 2 ) + pow(_lowerCamelCase , 2 ) )} else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
214
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : List[Any] = KandinskyImgaImgPipeline _UpperCamelCase : Optional[Any] = ["prompt", "image_embeds", "negative_image_embeds", "image"] _UpperCamelCase : List[Any] = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", ] _UpperCamelCase : Dict = [ "generator", "height", "width", "strength", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] _UpperCamelCase : Union[str, Any] = False @property def __A ( self ): return 32 @property def __A ( self ): return 32 @property def __A ( self ): return self.time_input_dim @property def __A ( self ): return self.time_input_dim * 4 @property def __A ( self ): return 100 @property def __A ( self ): _lowerCAmelCase : Optional[Any] = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : List[Any] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) _lowerCAmelCase : int = MultilingualCLIP(a__ ) _lowerCAmelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } _lowerCAmelCase : Optional[Any] = UNetaDConditionModel(**a__ ) return model @property def __A ( self ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __A ( self ): torch.manual_seed(0 ) _lowerCAmelCase : str = VQModel(**self.dummy_movq_kwargs ) return model def __A ( self ): _lowerCAmelCase : Union[str, Any] = self.dummy_text_encoder _lowerCAmelCase : List[Any] = self.dummy_tokenizer _lowerCAmelCase : int = self.dummy_unet _lowerCAmelCase : Dict = self.dummy_movq _lowerCAmelCase : Tuple = { """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, } _lowerCAmelCase : Optional[Any] = DDIMScheduler(**a__ ) _lowerCAmelCase : List[Any] = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def __A ( self , a__ , a__=0 ): _lowerCAmelCase : Optional[int] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(a__ ) # create init_image _lowerCAmelCase : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(a__ ) ).to(a__ ) _lowerCAmelCase : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase : List[Any] = Image.fromarray(np.uinta(a__ ) ).convert("""RGB""" ).resize((256, 256) ) if str(a__ ).startswith("""mps""" ): _lowerCAmelCase : List[Any] = torch.manual_seed(a__ ) else: _lowerCAmelCase : Tuple = torch.Generator(device=a__ ).manual_seed(a__ ) _lowerCAmelCase : Optional[Any] = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def __A ( self ): _lowerCAmelCase : Any = """cpu""" _lowerCAmelCase : int = self.get_dummy_components() _lowerCAmelCase : int = self.pipeline_class(**a__ ) _lowerCAmelCase : Optional[int] = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Tuple = pipe(**self.get_dummy_inputs(a__ ) ) _lowerCAmelCase : List[Any] = output.images _lowerCAmelCase : Tuple = pipe( **self.get_dummy_inputs(a__ ) , return_dict=a__ , )[0] _lowerCAmelCase : Dict = image[0, -3:, -3:, -1] _lowerCAmelCase : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCAmelCase : str = np.array( [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __A ( unittest.TestCase ): def __A ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self ): _lowerCAmelCase : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) _lowerCAmelCase : List[str] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) _lowerCAmelCase : Union[str, Any] = """A red cartoon frog, 4k""" _lowerCAmelCase : int = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(a__ ) _lowerCAmelCase : Tuple = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) _lowerCAmelCase : Any = pipeline.to(a__ ) pipeline.set_progress_bar_config(disable=a__ ) _lowerCAmelCase : Any = torch.Generator(device="""cpu""" ).manual_seed(0 ) _lowerCAmelCase , _lowerCAmelCase : Dict = pipe_prior( a__ , generator=a__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() _lowerCAmelCase : Union[str, Any] = pipeline( a__ , image=a__ , image_embeds=a__ , negative_image_embeds=a__ , generator=a__ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) _lowerCAmelCase : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a__ , a__ )
44
0
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE ) -> None: create_state_space_tree(_SCREAMING_SNAKE_CASE , [] , 0 , [0 for i in range(len(_SCREAMING_SNAKE_CASE ) )] ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> None: if index == len(_SCREAMING_SNAKE_CASE ): print(_SCREAMING_SNAKE_CASE ) return for i in range(len(_SCREAMING_SNAKE_CASE ) ): if not index_used[i]: current_sequence.append(sequence[i] ) snake_case_ = True create_state_space_tree(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 , _SCREAMING_SNAKE_CASE ) current_sequence.pop() snake_case_ = False __SCREAMING_SNAKE_CASE : list[int | str] = [3, 1, 2, 4] generate_all_permutations(sequence) __SCREAMING_SNAKE_CASE : list[int | str] = ["A", "B", "C"] generate_all_permutations(sequence_a)
233
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "\n".join( f"""{number} * {i} = {number * i}""" for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
233
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "s-JoL/Open-Llama-V1": "https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json", } class __lowerCAmelCase ( A ): UpperCamelCase = '''open-llama''' def __init__( self : str , A : List[Any]=10_00_00 , A : Tuple=40_96 , A : Tuple=1_10_08 , A : List[str]=32 , A : Tuple=32 , A : Optional[Any]="silu" , A : int=20_48 , A : Optional[Any]=0.0_2 , A : Dict=1E-6 , A : Optional[Any]=True , A : List[Any]=0 , A : Dict=1 , A : int=2 , A : Dict=False , A : Optional[int]=True , A : List[Any]=0.1 , A : str=0.1 , A : Dict=True , A : Optional[Any]=True , A : Dict=None , **A : Union[str, Any] , ) -> Dict: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = hidden_size _UpperCAmelCase = intermediate_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = hidden_act _UpperCAmelCase = initializer_range _UpperCAmelCase = rms_norm_eps _UpperCAmelCase = use_cache _UpperCAmelCase = kwargs.pop( 'use_memorry_efficient_attention' , A) _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_dropout_prob _UpperCAmelCase = use_stable_embedding _UpperCAmelCase = shared_input_output_embedding _UpperCAmelCase = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=A , bos_token_id=A , eos_token_id=A , tie_word_embeddings=A , **A , ) def _lowerCamelCase ( self : List[str]) -> Union[str, Any]: """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , A) or len(self.rope_scaling) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' F"got {self.rope_scaling}") _UpperCAmelCase = self.rope_scaling.get('type' , A) _UpperCAmelCase = self.rope_scaling.get('factor' , A) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}") if rope_scaling_factor is None or not isinstance(A , A) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
339
# This code is adapted from OpenAI's release # https://github.com/openai/human-eval/blob/master/human_eval/execution.py import contextlib import faulthandler import io import multiprocessing import os import platform import signal import tempfile def A ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Dict , _UpperCAmelCase : Dict , _UpperCAmelCase : Dict ) -> Any: '''simple docstring''' _UpperCAmelCase = multiprocessing.Manager() _UpperCAmelCase = manager.list() _UpperCAmelCase = multiprocessing.Process(target=_UpperCAmelCase , args=(check_program, result, timeout) ) p.start() p.join(timeout=timeout + 1 ) if p.is_alive(): p.kill() if not result: result.append('timed out' ) return { "task_id": task_id, "passed": result[0] == "passed", "result": result[0], "completion_id": completion_id, } def A ( _UpperCAmelCase : str , _UpperCAmelCase : List[str] , _UpperCAmelCase : Dict ) -> Optional[int]: '''simple docstring''' with create_tempdir(): # These system calls are needed when cleaning up tempdir. import os import shutil _UpperCAmelCase = shutil.rmtree _UpperCAmelCase = os.rmdir _UpperCAmelCase = os.chdir # Disable functionalities that can make destructive changes to the test. reliability_guard() # Run program. try: _UpperCAmelCase = {} with swallow_io(): with time_limit(_UpperCAmelCase ): exec(_UpperCAmelCase , _UpperCAmelCase ) result.append('passed' ) except TimeoutException: result.append('timed out' ) except BaseException as e: result.append(F"failed: {e}" ) # Needed for cleaning up. _UpperCAmelCase = rmtree _UpperCAmelCase = rmdir _UpperCAmelCase = chdir @contextlib.contextmanager def A ( _UpperCAmelCase : Union[str, Any] ) -> Any: '''simple docstring''' def signal_handler(_UpperCAmelCase : List[Any] , _UpperCAmelCase : Dict ): raise TimeoutException('Timed out!' ) signal.setitimer(signal.ITIMER_REAL , _UpperCAmelCase ) signal.signal(signal.SIGALRM , _UpperCAmelCase ) try: yield finally: signal.setitimer(signal.ITIMER_REAL , 0 ) @contextlib.contextmanager def A ( ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase = WriteOnlyStringIO() with contextlib.redirect_stdout(_UpperCAmelCase ): with contextlib.redirect_stderr(_UpperCAmelCase ): with redirect_stdin(_UpperCAmelCase ): yield @contextlib.contextmanager def A ( ) -> Any: '''simple docstring''' with tempfile.TemporaryDirectory() as dirname: with chdir(_UpperCAmelCase ): yield dirname class __lowerCAmelCase ( A ): pass class __lowerCAmelCase ( io.StringIO ): def _lowerCamelCase ( self : Tuple , *A : str , **A : Any) -> Any: """simple docstring""" raise OSError def _lowerCamelCase ( self : List[str] , *A : Optional[Any] , **A : Optional[Any]) -> Optional[int]: """simple docstring""" raise OSError def _lowerCamelCase ( self : str , *A : List[str] , **A : List[Any]) -> Union[str, Any]: """simple docstring""" raise OSError def _lowerCamelCase ( self : Union[str, Any] , *A : Optional[Any] , **A : List[str]) -> Optional[int]: """simple docstring""" return False class __lowerCAmelCase ( contextlib._RedirectStream ): # type: ignore UpperCamelCase = '''stdin''' @contextlib.contextmanager def A ( _UpperCAmelCase : List[Any] ) -> Dict: '''simple docstring''' if root == ".": yield return _UpperCAmelCase = os.getcwd() os.chdir(_UpperCAmelCase ) try: yield except BaseException as exc: raise exc finally: os.chdir(_UpperCAmelCase ) def A ( _UpperCAmelCase : List[str]=None ) -> Any: '''simple docstring''' if maximum_memory_bytes is not None: import resource resource.setrlimit(resource.RLIMIT_AS , (maximum_memory_bytes, maximum_memory_bytes) ) resource.setrlimit(resource.RLIMIT_DATA , (maximum_memory_bytes, maximum_memory_bytes) ) if not platform.uname().system == "Darwin": resource.setrlimit(resource.RLIMIT_STACK , (maximum_memory_bytes, maximum_memory_bytes) ) faulthandler.disable() import builtins _UpperCAmelCase = None _UpperCAmelCase = None import os _UpperCAmelCase = '1' _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None import shutil _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None import subprocess _UpperCAmelCase = None # type: ignore _UpperCAmelCase = None import sys _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None
339
1
"""simple docstring""" from math import isclose, sqrt def _lowerCAmelCase ( UpperCAmelCase__ : float, UpperCAmelCase__ : float, UpperCAmelCase__ : float ) ->tuple[float, float, float]: A__ : List[Any] = point_y / 4 / point_x A__ : Any = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) A__ : str = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) A__ : Dict = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 A__ : Optional[int] = outgoing_gradient**2 + 4 A__ : List[Any] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) A__ : Any = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 A__ : Dict = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) A__ : List[str] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point A__ : int = x_minus if isclose(UpperCAmelCase__, UpperCAmelCase__ ) else x_plus A__ : Any = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _lowerCAmelCase ( UpperCAmelCase__ : float = 1.4, UpperCAmelCase__ : float = -9.6 ) ->int: A__ : int = 0 A__ : float = first_x_coord A__ : float = first_y_coord A__ : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): A__ , A__ , A__ : Optional[Any] = next_point(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F'{solution() = }')
296
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels A_ = object() # For specifying empty leaf dict `{}` A_ = object() def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any] ) ->Dict: A__ : Union[str, Any] = tuple((re.compile(x + """$""" ) for x in qs) ) for i in range(len(UpperCAmelCase__ ) - len(UpperCAmelCase__ ) + 1 ): A__ : Optional[Any] = [x.match(UpperCAmelCase__ ) for x, y in zip(UpperCAmelCase__, ks[i:] )] if matches and all(UpperCAmelCase__ ): return True return False def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->Dict: def replace(UpperCAmelCase__ : int, UpperCAmelCase__ : List[str] ): for rule, replacement in rules: if _match(UpperCAmelCase__, UpperCAmelCase__ ): return replacement return val return replace def _lowerCAmelCase ( ) ->Tuple: return [ # embeddings (("transformer", "wpe", "embedding"), P("""mp""", UpperCAmelCase__ )), (("transformer", "wte", "embedding"), P("""mp""", UpperCAmelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(UpperCAmelCase__, """mp""" )), (("attention", "out_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(UpperCAmelCase__, """mp""" )), (("mlp", "c_fc", "bias"), P("""mp""" )), (("mlp", "c_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def _lowerCAmelCase ( UpperCAmelCase__ : Tuple ) ->Any: A__ : Union[str, Any] = _get_partition_rules() A__ : int = _replacement_rules(UpperCAmelCase__ ) A__ : Tuple = {k: _unmatched for k in flatten_dict(UpperCAmelCase__ )} A__ : Optional[int] = {k: replace(UpperCAmelCase__, UpperCAmelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(UpperCAmelCase__ ) )
296
1
"""simple docstring""" from graphs.minimum_spanning_tree_kruskal import kruskal def lowercase ( )-> Any: '''simple docstring''' a : str = 9 a : Tuple = [ [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(A_ , A_ ) a : List[Any] = [ [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(A_ ) == sorted(A_ )
40
"""simple docstring""" def _snake_case ( lowerCamelCase__ : str , lowerCamelCase__ : str , lowerCamelCase__ : List[Any] , lowerCamelCase__ : str ) -> str: global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: lowerCamelCase_ : Optional[Any] =mf_knapsack(i - 1 , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: lowerCamelCase_ : Union[str, Any] =max( mf_knapsack(i - 1 , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , mf_knapsack(i - 1 , lowerCamelCase__ , lowerCamelCase__ , j - wt[i - 1] ) + val[i - 1] , ) lowerCamelCase_ : int =val return f[i][j] def _snake_case ( lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Dict , lowerCamelCase__ : Any , lowerCamelCase__ : int ) -> Dict: lowerCamelCase_ : List[Any] =[[0] * (w + 1) for _ in range(n + 1 )] for i in range(1 , n + 1 ): for w_ in range(1 , w + 1 ): if wt[i - 1] <= w_: lowerCamelCase_ : Union[str, Any] =max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] ) else: lowerCamelCase_ : Optional[int] =dp[i - 1][w_] return dp[n][w_], dp def _snake_case ( lowerCamelCase__ : int , lowerCamelCase__ : list , lowerCamelCase__ : list ) -> Tuple: if not (isinstance(lowerCamelCase__ , (list, tuple) ) and isinstance(lowerCamelCase__ , (list, tuple) )): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) lowerCamelCase_ : Optional[int] =len(lowerCamelCase__ ) if num_items != len(lowerCamelCase__ ): lowerCamelCase_ : Optional[Any] =( "The number of weights must be the same as the number of values.\n" F"""But got {num_items} weights and {len(lowerCamelCase__ )} values""" ) raise ValueError(lowerCamelCase__ ) for i in range(lowerCamelCase__ ): if not isinstance(wt[i] , lowerCamelCase__ ): lowerCamelCase_ : Optional[Any] =( "All weights must be integers but got weight of " F"""type {type(wt[i] )} at index {i}""" ) raise TypeError(lowerCamelCase__ ) lowerCamelCase_ , lowerCamelCase_ : Optional[int] =knapsack(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) lowerCamelCase_ : set =set() _construct_solution(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) return optimal_val, example_optional_set def _snake_case ( lowerCamelCase__ : list , lowerCamelCase__ : list , lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : set ) -> Optional[int]: # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(lowerCamelCase__ , lowerCamelCase__ , i - 1 , lowerCamelCase__ , lowerCamelCase__ ) else: optimal_set.add(lowerCamelCase__ ) _construct_solution(lowerCamelCase__ , lowerCamelCase__ , i - 1 , j - wt[i - 1] , lowerCamelCase__ ) if __name__ == "__main__": A__ : Optional[Any] = [3, 2, 4, 4] A__ : str = [4, 3, 2, 3] A__ : List[Any] = 4 A__ : Union[str, Any] = 6 A__ : List[str] = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] A__ , A__ : Any = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 A__ , A__ : str = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print('optimal_value = ', optimal_solution) print('An optimal subset corresponding to the optimal value', optimal_subset)
144
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowerCAmelCase : Any = { "configuration_efficientformer": [ "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientFormerConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : int = ["EfficientFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Tuple = [ "EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientFormerForImageClassification", "EfficientFormerForImageClassificationWithTeacher", "EfficientFormerModel", "EfficientFormerPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Dict = [ "TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFEfficientFormerForImageClassification", "TFEfficientFormerForImageClassificationWithTeacher", "TFEfficientFormerModel", "TFEfficientFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys _lowerCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
202
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo _lowerCAmelCase : Tuple = "\\n@misc{wu2016googles,\n title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n" _lowerCAmelCase : Optional[int] = "\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n" _lowerCAmelCase : Any = "\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n 'google_bleu': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.4\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): def snake_case_ ( self : List[str] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def snake_case_ ( self : str , A : List[List[List[str]]] , A : List[List[str]] , A : int = 1 , A : int = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=A , hypotheses=A , min_len=A , max_len=A ) }
202
1
"""simple docstring""" import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowercase_ : '''simple docstring''' def __init__( self : Tuple , _UpperCAmelCase : Any , _UpperCAmelCase : List[Any]=13 , _UpperCAmelCase : Dict=30 , _UpperCAmelCase : Dict=2 , _UpperCAmelCase : int=3 , _UpperCAmelCase : Dict=True , _UpperCAmelCase : str=True , _UpperCAmelCase : Dict=32 , _UpperCAmelCase : List[Any]=5 , _UpperCAmelCase : str=4 , _UpperCAmelCase : List[Any]=37 , _UpperCAmelCase : Dict="gelu" , _UpperCAmelCase : Optional[Any]=0.1 , _UpperCAmelCase : Tuple=0.1 , _UpperCAmelCase : List[Any]=10 , _UpperCAmelCase : List[Any]=0.02 , _UpperCAmelCase : Dict=3 , _UpperCAmelCase : int=0.6 , _UpperCAmelCase : Union[str, Any]=None , ): _A = parent _A = batch_size _A = image_size _A = patch_size _A = num_channels _A = is_training _A = use_labels _A = hidden_size _A = num_hidden_layers _A = num_attention_heads _A = intermediate_size _A = hidden_act _A = hidden_dropout_prob _A = attention_probs_dropout_prob _A = type_sequence_label_size _A = initializer_range _A = mask_ratio _A = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) _A = (image_size // patch_size) ** 2 _A = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowerCAmelCase_ ( self : List[Any] ): _A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A = None if self.use_labels: _A = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _A = self.get_config() return config, pixel_values, labels def lowerCAmelCase_ ( self : str ): return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_UpperCAmelCase , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def lowerCAmelCase_ ( self : Optional[Any] , _UpperCAmelCase : Tuple , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : int ): _A = ViTMAEModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _A = model(_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase_ ( self : List[str] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Any , _UpperCAmelCase : Union[str, Any] ): _A = ViTMAEForPreTraining(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _A = model(_UpperCAmelCase ) _A = (self.image_size // self.patch_size) ** 2 _A = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images _A = 1 _A = ViTMAEForPreTraining(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _A = model(_UpperCAmelCase ) _A = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowerCAmelCase_ ( self : Dict ): _A = self.prepare_config_and_inputs() _A = config_and_inputs _A = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class lowercase_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' UpperCAmelCase : Union[str, Any] = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () UpperCAmelCase : List[Any] = {'''feature-extraction''': ViTMAEModel} if is_torch_available() else {} UpperCAmelCase : Any = False UpperCAmelCase : str = False UpperCAmelCase : Any = False UpperCAmelCase : Union[str, Any] = False def lowerCAmelCase_ ( self : List[str] ): _A = ViTMAEModelTester(self ) _A = ConfigTester(self , config_class=_UpperCAmelCase , has_text_modality=_UpperCAmelCase , hidden_size=37 ) def lowerCAmelCase_ ( self : str ): self.config_tester.run_common_tests() @unittest.skip(reason='ViTMAE does not use inputs_embeds' ) def lowerCAmelCase_ ( self : Tuple ): pass def lowerCAmelCase_ ( self : List[str] ): _A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A = model_class(_UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase , nn.Linear ) ) def lowerCAmelCase_ ( self : Optional[int] ): _A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A = model_class(_UpperCAmelCase ) _A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A = [*signature.parameters.keys()] _A = ['pixel_values'] self.assertListEqual(arg_names[:1] , _UpperCAmelCase ) def lowerCAmelCase_ ( self : List[Any] ): _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def lowerCAmelCase_ ( self : Any ): _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_UpperCAmelCase ) def lowerCAmelCase_ ( self : str , _UpperCAmelCase : List[Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : int ): # make masks reproducible np.random.seed(2 ) _A = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) _A = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) _A = torch.from_numpy(_UpperCAmelCase ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument _A = pt_noise super().check_pt_tf_models(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) def lowerCAmelCase_ ( self : List[Any] ): _A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): _A = model(**self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase ) ) _A = outputs[0].cpu().numpy() _A = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_UpperCAmelCase ) _A = model_class.from_pretrained(_UpperCAmelCase ) model.to(_UpperCAmelCase ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): _A = model(**self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase ) ) # Make sure we don't have nans _A = after_outputs[0].cpu().numpy() _A = 0 _A = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_UpperCAmelCase , 1E-5 ) @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 : int ): pass @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 : List[str] ): pass @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 : List[str] ): pass @unittest.skip(reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load' ) def lowerCAmelCase_ ( self : Tuple ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def lowerCAmelCase_ ( self : List[Any] ): pass @slow def lowerCAmelCase_ ( self : int ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A = ViTMAEModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def _snake_case ( ) -> List[str]: '''simple docstring''' _A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class lowercase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def lowerCAmelCase_ ( self : Dict ): return ViTImageProcessor.from_pretrained('facebook/vit-mae-base' ) if is_vision_available() else None @slow def lowerCAmelCase_ ( self : str ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) _A = ViTMAEForPreTraining.from_pretrained('facebook/vit-mae-base' ).to(_UpperCAmelCase ) _A = self.default_image_processor _A = prepare_img() _A = image_processor(images=_UpperCAmelCase , return_tensors='pt' ).to(_UpperCAmelCase ) # 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) _A = ViTMAEConfig() _A = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) _A = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): _A = model(**_UpperCAmelCase , noise=torch.from_numpy(_UpperCAmelCase ).to(device=_UpperCAmelCase ) ) # verify the logits _A = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , _UpperCAmelCase ) _A = torch.tensor( [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(_UpperCAmelCase ) , atol=1E-4 ) )
315
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> set: lowerCamelCase__ : Optional[Any] = set() # edges = list of graph's edges lowerCamelCase__ : List[str] = get_edges(_UpperCAmelCase ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: lowerCamelCase__ , lowerCamelCase__ : str = edges.pop() chosen_vertices.add(_UpperCAmelCase ) chosen_vertices.add(_UpperCAmelCase ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(_UpperCAmelCase ) return chosen_vertices def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> set: lowerCamelCase__ : Union[str, Any] = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
50
0
def __lowercase ( _UpperCamelCase = 600851475143 ) ->int: """simple docstring""" try: lowercase : Optional[int] = int(_UpperCamelCase ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: raise ValueError('''Parameter n must be greater than or equal to one.''' ) lowercase : Optional[Any] = 2 lowercase : Optional[int] = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 lowercase : int = i while n % i == 0: lowercase : Any = n // i i += 1 return int(_UpperCamelCase ) if __name__ == "__main__": print(F'''{solution() = }''')
173
from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class __SCREAMING_SNAKE_CASE ( A__ ): A : Union[str, Any] = 'audio-spectrogram-transformer' def __init__( self , SCREAMING_SNAKE_CASE__=768 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=3072 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-12 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=1024 , SCREAMING_SNAKE_CASE__=128 , **SCREAMING_SNAKE_CASE__ , ): super().__init__(**SCREAMING_SNAKE_CASE__ ) lowercase : Any = hidden_size lowercase : Optional[Any] = num_hidden_layers lowercase : Any = num_attention_heads lowercase : Optional[int] = intermediate_size lowercase : List[str] = hidden_act lowercase : Tuple = hidden_dropout_prob lowercase : Optional[Any] = attention_probs_dropout_prob lowercase : Optional[Any] = initializer_range lowercase : str = layer_norm_eps lowercase : Any = patch_size lowercase : Tuple = qkv_bias lowercase : str = frequency_stride lowercase : Union[str, Any] = time_stride lowercase : Dict = max_length lowercase : List[str] = num_mel_bins
173
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A_ : Dict = { 'configuration_blip': [ 'BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlipConfig', 'BlipTextConfig', 'BlipVisionConfig', ], 'processing_blip': ['BlipProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = ['BlipImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[str] = [ 'BLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlipModel', 'BlipPreTrainedModel', 'BlipForConditionalGeneration', 'BlipForQuestionAnswering', 'BlipVisionModel', 'BlipTextModel', 'BlipForImageTextRetrieval', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : str = [ 'TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFBlipModel', 'TFBlipPreTrainedModel', 'TFBlipForConditionalGeneration', 'TFBlipForQuestionAnswering', 'TFBlipVisionModel', 'TFBlipTextModel', 'TFBlipForImageTextRetrieval', ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys A_ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
192
import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline A_ : List[str] = { 'n_samples': 64, 'horizon': 32, 'num_inference_steps': 20, 'n_guide_steps': 2, # can set to 0 for faster sampling, does not use value network 'scale_grad_by_std': True, 'scale': 0.1, 'eta': 0.0, 't_grad_cutoff': 2, 'device': 'cpu', } if __name__ == "__main__": A_ : Optional[int] = 'hopper-medium-v2' A_ : List[Any] = gym.make(env_name) A_ : str = ValueGuidedRLPipeline.from_pretrained( 'bglick13/hopper-medium-v2-value-function-hor32', env=env, ) env.seed(0) A_ : List[Any] = env.reset() A_ : Optional[int] = 0 A_ : str = 0 A_ : Optional[Any] = 1000 A_ : Union[str, Any] = [obs.copy()] try: for t in tqdm.tqdm(range(T)): # call the policy A_ : Tuple = pipeline(obs, planning_horizon=32) # execute action in environment A_ , A_ , A_ , A_ : Dict = env.step(denorm_actions) A_ : List[str] = env.get_normalized_score(total_reward) # update return total_reward += reward total_score += score print( f'''Step: {t}, Reward: {reward}, Total Reward: {total_reward}, Score: {score}, Total Score:''' f''' {total_score}''' ) # save observations for rendering rollout.append(next_observation.copy()) A_ : int = next_observation except KeyboardInterrupt: pass print(f'''Total reward: {total_reward}''')
192
1
"""simple docstring""" def A_ ( _lowerCAmelCase : str ): """simple docstring""" if n_term == "": return [] _a = [] for temp in range(int(_lowerCAmelCase ) ): series.append(f'1/{temp + 1}' if series else '''1''' ) return series if __name__ == "__main__": __snake_case = 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))
153
"""simple docstring""" import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class __lowerCamelCase : '''simple docstring''' @staticmethod def _UpperCAmelCase ( *__UpperCAmelCase , **__UpperCAmelCase ) -> Tuple: pass def A_ ( _lowerCAmelCase : Image ): """simple docstring""" _a = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' A_ : List[Any] = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> str: _a = DepthEstimationPipeline(model=__UpperCAmelCase , image_processor=__UpperCAmelCase ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Dict: _a = depth_estimator('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) self.assertEqual({'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )} , __UpperCAmelCase ) import datasets _a = datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''' ) _a = 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 _UpperCAmelCase ( self ) -> Tuple: pass @slow @require_torch def _UpperCAmelCase ( self ) -> List[str]: _a = '''Intel/dpt-large''' _a = pipeline('''depth-estimation''' , model=__UpperCAmelCase ) _a = depth_estimator('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) _a = hashimage(outputs['''depth'''] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs['''predicted_depth'''].max().item() ) , 29.304 ) self.assertEqual(nested_simplify(outputs['''predicted_depth'''].min().item() ) , 2.662 ) @require_torch def _UpperCAmelCase ( self ) -> List[Any]: # This is highly irregular to have no small tests. self.skipTest('''There is not hf-internal-testing tiny model for either GLPN nor DPT''' )
153
1
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def __snake_case ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str]=1 ): if n_shave_prefix_segments >= 0: return ".".join(path.split("." )[n_shave_prefix_segments:] ) else: return ".".join(path.split("." )[:n_shave_prefix_segments] ) def __snake_case ( UpperCAmelCase_ : str , UpperCAmelCase_ : List[str]=0 ): lowerCamelCase_ = [] for old_item in old_list: lowerCamelCase_ = old_item.replace("in_layers.0" , "norm1" ) lowerCamelCase_ = new_item.replace("in_layers.2" , "conv1" ) lowerCamelCase_ = new_item.replace("out_layers.0" , "norm2" ) lowerCamelCase_ = new_item.replace("out_layers.3" , "conv2" ) lowerCamelCase_ = new_item.replace("emb_layers.1" , "time_emb_proj" ) lowerCamelCase_ = new_item.replace("skip_connection" , "conv_shortcut" ) lowerCamelCase_ = shave_segments(UpperCAmelCase_ , n_shave_prefix_segments=UpperCAmelCase_ ) mapping.append({"old": old_item, "new": new_item} ) return mapping def __snake_case ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[Any]=0 ): lowerCamelCase_ = [] for old_item in old_list: lowerCamelCase_ = old_item lowerCamelCase_ = new_item.replace("norm.weight" , "group_norm.weight" ) lowerCamelCase_ = new_item.replace("norm.bias" , "group_norm.bias" ) lowerCamelCase_ = new_item.replace("proj_out.weight" , "proj_attn.weight" ) lowerCamelCase_ = new_item.replace("proj_out.bias" , "proj_attn.bias" ) lowerCamelCase_ = shave_segments(UpperCAmelCase_ , n_shave_prefix_segments=UpperCAmelCase_ ) mapping.append({"old": old_item, "new": new_item} ) return mapping def __snake_case ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Union[str, Any]=None ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): lowerCamelCase_ = old_checkpoint[path] lowerCamelCase_ = old_tensor.shape[0] // 3 lowerCamelCase_ = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) lowerCamelCase_ = old_tensor.shape[0] // config["num_head_channels"] // 3 lowerCamelCase_ = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = old_tensor.split(channels // num_heads , dim=1 ) lowerCamelCase_ = query.reshape(UpperCAmelCase_ ) lowerCamelCase_ = key.reshape(UpperCAmelCase_ ) lowerCamelCase_ = value.reshape(UpperCAmelCase_ ) for path in paths: lowerCamelCase_ = path["new"] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here lowerCamelCase_ = new_path.replace("middle_block.0" , "mid_block.resnets.0" ) lowerCamelCase_ = new_path.replace("middle_block.1" , "mid_block.attentions.0" ) lowerCamelCase_ = new_path.replace("middle_block.2" , "mid_block.resnets.1" ) if additional_replacements is not None: for replacement in additional_replacements: lowerCamelCase_ = new_path.replace(replacement["old"] , replacement["new"] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: lowerCamelCase_ = old_checkpoint[path["old"]][:, :, 0] else: lowerCamelCase_ = old_checkpoint[path["old"]] def __snake_case ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] ): lowerCamelCase_ = {} lowerCamelCase_ = checkpoint["time_embed.0.weight"] lowerCamelCase_ = checkpoint["time_embed.0.bias"] lowerCamelCase_ = checkpoint["time_embed.2.weight"] lowerCamelCase_ = checkpoint["time_embed.2.bias"] lowerCamelCase_ = checkpoint["input_blocks.0.0.weight"] lowerCamelCase_ = checkpoint["input_blocks.0.0.bias"] lowerCamelCase_ = checkpoint["out.0.weight"] lowerCamelCase_ = checkpoint["out.0.bias"] lowerCamelCase_ = checkpoint["out.2.weight"] lowerCamelCase_ = checkpoint["out.2.bias"] # Retrieves the keys for the input blocks only lowerCamelCase_ = len({".".join(layer.split("." )[:2] ) for layer in checkpoint if "input_blocks" in layer} ) lowerCamelCase_ = { layer_id: [key for key in checkpoint if F'''input_blocks.{layer_id}''' in key] for layer_id in range(UpperCAmelCase_ ) } # Retrieves the keys for the middle blocks only lowerCamelCase_ = len({".".join(layer.split("." )[:2] ) for layer in checkpoint if "middle_block" in layer} ) lowerCamelCase_ = { layer_id: [key for key in checkpoint if F'''middle_block.{layer_id}''' in key] for layer_id in range(UpperCAmelCase_ ) } # Retrieves the keys for the output blocks only lowerCamelCase_ = len({".".join(layer.split("." )[:2] ) for layer in checkpoint if "output_blocks" in layer} ) lowerCamelCase_ = { layer_id: [key for key in checkpoint if F'''output_blocks.{layer_id}''' in key] for layer_id in range(UpperCAmelCase_ ) } for i in range(1 , UpperCAmelCase_ ): lowerCamelCase_ = (i - 1) // (config["num_res_blocks"] + 1) lowerCamelCase_ = (i - 1) % (config["num_res_blocks"] + 1) lowerCamelCase_ = [key for key in input_blocks[i] if F'''input_blocks.{i}.0''' in key] lowerCamelCase_ = [key for key in input_blocks[i] if F'''input_blocks.{i}.1''' in key] if F'''input_blocks.{i}.0.op.weight''' in checkpoint: lowerCamelCase_ = checkpoint[ F'''input_blocks.{i}.0.op.weight''' ] lowerCamelCase_ = checkpoint[ F'''input_blocks.{i}.0.op.bias''' ] continue lowerCamelCase_ = renew_resnet_paths(UpperCAmelCase_ ) lowerCamelCase_ = {"old": F'''input_blocks.{i}.0''', "new": F'''down_blocks.{block_id}.resnets.{layer_in_block_id}'''} lowerCamelCase_ = {"old": "resnets.2.op", "new": "downsamplers.0.op"} assign_to_checkpoint( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , additional_replacements=[meta_path, resnet_op] , config=UpperCAmelCase_ ) if len(UpperCAmelCase_ ): lowerCamelCase_ = renew_attention_paths(UpperCAmelCase_ ) lowerCamelCase_ = { "old": F'''input_blocks.{i}.1''', "new": F'''down_blocks.{block_id}.attentions.{layer_in_block_id}''', } lowerCamelCase_ = { F'''input_blocks.{i}.1.qkv.bias''': { "key": F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias''', "query": F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias''', "value": F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias''', }, F'''input_blocks.{i}.1.qkv.weight''': { "key": F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight''', "query": F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight''', "value": F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight''', }, } assign_to_checkpoint( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=UpperCAmelCase_ , config=UpperCAmelCase_ , ) lowerCamelCase_ = middle_blocks[0] lowerCamelCase_ = middle_blocks[1] lowerCamelCase_ = middle_blocks[2] lowerCamelCase_ = renew_resnet_paths(UpperCAmelCase_ ) assign_to_checkpoint(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , config=UpperCAmelCase_ ) lowerCamelCase_ = renew_resnet_paths(UpperCAmelCase_ ) assign_to_checkpoint(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , config=UpperCAmelCase_ ) lowerCamelCase_ = renew_attention_paths(UpperCAmelCase_ ) lowerCamelCase_ = { "middle_block.1.qkv.bias": { "key": "mid_block.attentions.0.key.bias", "query": "mid_block.attentions.0.query.bias", "value": "mid_block.attentions.0.value.bias", }, "middle_block.1.qkv.weight": { "key": "mid_block.attentions.0.key.weight", "query": "mid_block.attentions.0.query.weight", "value": "mid_block.attentions.0.value.weight", }, } assign_to_checkpoint( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , attention_paths_to_split=UpperCAmelCase_ , config=UpperCAmelCase_ ) for i in range(UpperCAmelCase_ ): lowerCamelCase_ = i // (config["num_res_blocks"] + 1) lowerCamelCase_ = i % (config["num_res_blocks"] + 1) lowerCamelCase_ = [shave_segments(UpperCAmelCase_ , 2 ) for name in output_blocks[i]] lowerCamelCase_ = {} for layer in output_block_layers: lowerCamelCase_ ,lowerCamelCase_ = layer.split("." )[0], shave_segments(UpperCAmelCase_ , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(UpperCAmelCase_ ) else: lowerCamelCase_ = [layer_name] if len(UpperCAmelCase_ ) > 1: lowerCamelCase_ = [key for key in output_blocks[i] if F'''output_blocks.{i}.0''' in key] lowerCamelCase_ = [key for key in output_blocks[i] if F'''output_blocks.{i}.1''' in key] lowerCamelCase_ = renew_resnet_paths(UpperCAmelCase_ ) lowerCamelCase_ = renew_resnet_paths(UpperCAmelCase_ ) lowerCamelCase_ = {"old": F'''output_blocks.{i}.0''', "new": F'''up_blocks.{block_id}.resnets.{layer_in_block_id}'''} assign_to_checkpoint(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , additional_replacements=[meta_path] , config=UpperCAmelCase_ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): lowerCamelCase_ = list(output_block_list.values() ).index(["conv.weight", "conv.bias"] ) lowerCamelCase_ = checkpoint[ F'''output_blocks.{i}.{index}.conv.weight''' ] lowerCamelCase_ = checkpoint[ F'''output_blocks.{i}.{index}.conv.bias''' ] # Clear attentions as they have been attributed above. if len(UpperCAmelCase_ ) == 2: lowerCamelCase_ = [] if len(UpperCAmelCase_ ): lowerCamelCase_ = renew_attention_paths(UpperCAmelCase_ ) lowerCamelCase_ = { "old": F'''output_blocks.{i}.1''', "new": F'''up_blocks.{block_id}.attentions.{layer_in_block_id}''', } lowerCamelCase_ = { F'''output_blocks.{i}.1.qkv.bias''': { "key": F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias''', "query": F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias''', "value": F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias''', }, F'''output_blocks.{i}.1.qkv.weight''': { "key": F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight''', "query": F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight''', "value": F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight''', }, } assign_to_checkpoint( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any("qkv" in key for key in attentions ) else None , config=UpperCAmelCase_ , ) else: lowerCamelCase_ = renew_resnet_paths(UpperCAmelCase_ , n_shave_prefix_segments=1 ) for path in resnet_0_paths: lowerCamelCase_ = ".".join(["output_blocks", str(UpperCAmelCase_ ), path["old"]] ) lowerCamelCase_ = ".".join(["up_blocks", str(UpperCAmelCase_ ), "resnets", str(UpperCAmelCase_ ), path["new"]] ) lowerCamelCase_ = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": a_ : Optional[int] = argparse.ArgumentParser() parser.add_argument( """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The config json file corresponding to the architecture.""", ) parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") a_ : Union[str, Any] = parser.parse_args() a_ : int = torch.load(args.checkpoint_path) with open(args.config_file) as f: a_ : int = json.loads(f.read()) a_ : int = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] a_ : Tuple = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: a_ : int = DDPMScheduler.from_config("""/""".join(args.checkpoint_path.split("""/""")[:-1])) a_ : int = VQModel.from_pretrained("""/""".join(args.checkpoint_path.split("""/""")[:-1])) a_ : Union[str, Any] = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
55
'''simple docstring''' _UpperCamelCase = ''' # Transformers 설치 방법 ! pip install transformers datasets # 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요. # ! pip install git+https://github.com/huggingface/transformers.git ''' _UpperCamelCase = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] _UpperCamelCase = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
254
0
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE :Union[str, Any] = get_tests_dir("""fixtures/test_sentencepiece_with_bytefallback.model""") @require_sentencepiece @require_tokenizers class __magic_name__ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): UpperCamelCase_ :Optional[Any] = GPTSwaTokenizer UpperCamelCase_ :Optional[Any] = False UpperCamelCase_ :Union[str, Any] = True UpperCamelCase_ :Tuple = False def UpperCAmelCase_ ( self )-> Optional[int]: super().setUp() # We have a SentencePiece fixture for testing UpperCamelCase_ = GPTSwaTokenizer(A_ , eos_token="<unk>" , bos_token="<unk>" , pad_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self , _lowercase )-> List[str]: UpperCamelCase_ = "This is a test" UpperCamelCase_ = "This is a test" return input_text, output_text def UpperCAmelCase_ ( self )-> int: UpperCamelCase_ = "<s>" UpperCamelCase_ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(A_ ) , A_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(A_ ) , A_ ) def UpperCAmelCase_ ( self )-> Dict: UpperCamelCase_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(A_ ) , 2_000 ) def UpperCAmelCase_ ( self )-> Any: self.assertEqual(self.get_tokenizer().vocab_size , 2_000 ) def UpperCAmelCase_ ( self )-> int: UpperCamelCase_ = GPTSwaTokenizer(A_ ) UpperCamelCase_ = tokenizer.tokenize("This is a test" ) self.assertListEqual(A_ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [465, 287, 265, 631, 842] ) UpperCamelCase_ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) # fmt: off self.assertListEqual( A_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] , ) # fmt: on UpperCamelCase_ = tokenizer.convert_tokens_to_ids(A_ ) self.assertListEqual( A_ , [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , ) UpperCamelCase_ = tokenizer.convert_ids_to_tokens(A_ ) # fmt: off self.assertListEqual( A_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] ) # fmt: on def UpperCAmelCase_ ( self )-> Tuple: UpperCamelCase_ = GPTSwaTokenizer(A_ ) UpperCamelCase_ = ["This is a test", "I was born in 92000, and this is falsé."] UpperCamelCase_ = [ [465, 287, 265, 631, 842], [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(A_ , A_ ): self.assertListEqual(tokenizer.encode_fast(A_ ) , A_ ) # Test that decode_fast returns the input text for text, token_ids in zip(A_ , A_ ): self.assertEqual(tokenizer.decode_fast(A_ ) , A_ ) @slow def UpperCAmelCase_ ( self )-> List[Any]: UpperCamelCase_ = [ "<|python|>def fibonacci(n)\n if n < 0:\n print(\'Incorrect input\')", "Hey there, how are you doing this fine day?", "This is a text with a trailing spaces followed by a dot .", "Häj sväjs lillebrör! =)", "Det är inget fel på Mr. Cool", ] # fmt: off UpperCamelCase_ = {"input_ids": [[63_423, 5, 6_811, 14_954, 282, 816, 3_821, 63_466, 63_425, 63_462, 18, 63_978, 678, 301, 1_320, 63_423, 63_455, 63_458, 18, 63_982, 4_246, 3_940, 1_901, 47_789, 5_547, 18_994], [19_630, 1_100, 63_446, 1_342, 633, 544, 4_488, 593, 5_102, 2_416, 63_495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_652, 428, 268, 1_936, 515, 268, 58_593, 22_413, 9_106, 546, 268, 33_213, 63_979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55_130, 63_450, 924, 63_449, 2_249, 4_062, 1_558, 318, 63_504, 21_498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2_827, 2_559, 332, 6_575, 63_443, 26_801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=A_ , model_name="AI-Sweden/gpt-sw3-126m" , sequences=A_ , )
371
def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False )-> str: """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase_ = f"Expected string as input, found {type(SCREAMING_SNAKE_CASE_ )}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase_ = f"Expected boolean as use_pascal parameter, found {type(SCREAMING_SNAKE_CASE_ )}" raise ValueError(SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = input_str.split("_" ) UpperCamelCase_ = 0 if use_pascal else 1 UpperCamelCase_ = words[start_index:] UpperCamelCase_ = [word[0].upper() + word[1:] for word in words_to_capitalize] UpperCamelCase_ = "" if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
60
0
'''simple docstring''' import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort _snake_case = logging.get_logger(__name__) _snake_case = { 'tensor(bool)': np.bool_, 'tensor(int8)': np.inta, 'tensor(uint8)': np.uinta, 'tensor(int16)': np.intaa, 'tensor(uint16)': np.uintaa, 'tensor(int32)': np.intaa, 'tensor(uint32)': np.uintaa, 'tensor(int64)': np.intaa, 'tensor(uint64)': np.uintaa, 'tensor(float16)': np.floataa, 'tensor(float)': np.floataa, 'tensor(double)': np.floataa, } class a__ : def __init__( self , _UpperCamelCase=None , **_UpperCamelCase ): """simple docstring""" logger.info("`diffusers.OnnxRuntimeModel` is experimental and might change in the future." ) _lowercase : Tuple = model _lowercase : Union[str, Any] = kwargs.get("model_save_dir" , _UpperCamelCase ) _lowercase : List[Any] = kwargs.get("latest_model_name" , _UpperCamelCase ) def __call__( self , **_UpperCamelCase ): """simple docstring""" _lowercase : Tuple = {k: np.array(_UpperCamelCase ) for k, v in kwargs.items()} return self.model.run(_UpperCamelCase , _UpperCamelCase ) @staticmethod def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=None , _UpperCamelCase=None ): """simple docstring""" if provider is None: logger.info("No onnxruntime provider specified, using CPUExecutionProvider" ) _lowercase : Optional[int] = "CPUExecutionProvider" return ort.InferenceSession(_UpperCamelCase , providers=[provider] , sess_options=_UpperCamelCase ) def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase = None , **_UpperCamelCase ): """simple docstring""" _lowercase : int = file_name if file_name is not None else ONNX_WEIGHTS_NAME _lowercase : str = self.model_save_dir.joinpath(self.latest_model_name ) _lowercase : Optional[Any] = Path(_UpperCamelCase ).joinpath(_UpperCamelCase ) try: shutil.copyfile(_UpperCamelCase , _UpperCamelCase ) except shutil.SameFileError: pass # copy external weights (for models >2GB) _lowercase : str = self.model_save_dir.joinpath(_UpperCamelCase ) if src_path.exists(): _lowercase : Dict = Path(_UpperCamelCase ).joinpath(_UpperCamelCase ) try: shutil.copyfile(_UpperCamelCase , _UpperCamelCase ) except shutil.SameFileError: pass def _lowerCamelCase ( self , _UpperCamelCase , **_UpperCamelCase , ): """simple docstring""" if os.path.isfile(_UpperCamelCase ): logger.error(f'''Provided path ({save_directory}) should be a directory, not a file''' ) return os.makedirs(_UpperCamelCase , exist_ok=_UpperCamelCase ) # saving model weights/files self._save_pretrained(_UpperCamelCase , **_UpperCamelCase ) @classmethod def _lowerCamelCase ( cls , _UpperCamelCase , _UpperCamelCase = None , _UpperCamelCase = None , _UpperCamelCase = False , _UpperCamelCase = None , _UpperCamelCase = None , _UpperCamelCase = None , _UpperCamelCase = None , **_UpperCamelCase , ): """simple docstring""" _lowercase : int = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(_UpperCamelCase ): _lowercase : Any = OnnxRuntimeModel.load_model( os.path.join(_UpperCamelCase , _UpperCamelCase ) , provider=_UpperCamelCase , sess_options=_UpperCamelCase ) _lowercase : Optional[Any] = Path(_UpperCamelCase ) # load model from hub else: # download model _lowercase : Any = hf_hub_download( repo_id=_UpperCamelCase , filename=_UpperCamelCase , use_auth_token=_UpperCamelCase , revision=_UpperCamelCase , cache_dir=_UpperCamelCase , force_download=_UpperCamelCase , ) _lowercase : Union[str, Any] = Path(_UpperCamelCase ).parent _lowercase : Dict = Path(_UpperCamelCase ).name _lowercase : Dict = OnnxRuntimeModel.load_model(_UpperCamelCase , provider=_UpperCamelCase , sess_options=_UpperCamelCase ) return cls(model=_UpperCamelCase , **_UpperCamelCase ) @classmethod def _lowerCamelCase ( cls , _UpperCamelCase , _UpperCamelCase = True , _UpperCamelCase = None , _UpperCamelCase = None , **_UpperCamelCase , ): """simple docstring""" _lowercase : Tuple = None if len(str(_UpperCamelCase ).split("@" ) ) == 2: _lowercase , _lowercase : Union[str, Any] = model_id.split("@" ) return cls._from_pretrained( model_id=_UpperCamelCase , revision=_UpperCamelCase , cache_dir=_UpperCamelCase , force_download=_UpperCamelCase , use_auth_token=_UpperCamelCase , **_UpperCamelCase , )
250
'''simple docstring''' 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 a__ : def __init__( self , _UpperCamelCase , _UpperCamelCase=13 , _UpperCamelCase=10 , _UpperCamelCase=3 , _UpperCamelCase=2 , _UpperCamelCase=2 , _UpperCamelCase=2 , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=32 , _UpperCamelCase=5 , _UpperCamelCase=4 , _UpperCamelCase=37 , _UpperCamelCase="gelu" , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=10 , _UpperCamelCase=0.0_2 , _UpperCamelCase=0.9 , _UpperCamelCase=None , ): """simple docstring""" _lowercase : List[str] = parent _lowercase : Tuple = batch_size _lowercase : Tuple = image_size _lowercase : Any = num_channels _lowercase : Tuple = patch_size _lowercase : Union[str, Any] = tubelet_size _lowercase : str = num_frames _lowercase : Any = is_training _lowercase : Tuple = use_labels _lowercase : List[Any] = hidden_size _lowercase : int = num_hidden_layers _lowercase : Tuple = num_attention_heads _lowercase : int = intermediate_size _lowercase : Optional[int] = hidden_act _lowercase : Union[str, Any] = hidden_dropout_prob _lowercase : Optional[Any] = attention_probs_dropout_prob _lowercase : Optional[Any] = type_sequence_label_size _lowercase : Optional[Any] = initializer_range _lowercase : int = mask_ratio _lowercase : Union[str, Any] = scope # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame _lowercase : List[str] = (image_size // patch_size) ** 2 _lowercase : Optional[Any] = (num_frames // tubelet_size) * self.num_patches_per_frame # use this variable to define bool_masked_pos _lowercase : str = int(mask_ratio * self.seq_length ) def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Union[str, Any] = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) _lowercase : Tuple = None if self.use_labels: _lowercase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowercase : Optional[Any] = self.get_config() return config, pixel_values, labels def _lowerCamelCase ( self ): """simple docstring""" 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=_UpperCamelCase , initializer_range=self.initializer_range , ) def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" _lowercase : Dict = VideoMAEModel(config=_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() _lowercase : Dict = model(_UpperCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" _lowercase : Dict = VideoMAEForPreTraining(_UpperCamelCase ) model.to(_UpperCamelCase ) 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 _lowercase : Optional[int] = torch.ones((self.num_masks,) ) _lowercase : List[Any] = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0 ) )] ) _lowercase : Tuple = mask.expand(self.batch_size , -1 ).bool() _lowercase : Tuple = model(_UpperCamelCase , _UpperCamelCase ) # model only returns predictions for masked patches _lowercase : Tuple = mask.sum().item() _lowercase : Optional[Any] = 3 * self.tubelet_size * self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_masked_patches, decoder_num_labels) ) def _lowerCamelCase ( self ): """simple docstring""" _lowercase : List[Any] = self.prepare_config_and_inputs() _lowercase , _lowercase , _lowercase : List[Any] = config_and_inputs _lowercase : str = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a__ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): _SCREAMING_SNAKE_CASE : List[str] = ( (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE : List[Any] = ( {'feature-extraction': VideoMAEModel, 'video-classification': VideoMAEForVideoClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE : Tuple = False _SCREAMING_SNAKE_CASE : Dict = False _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : Optional[Any] = False def _lowerCamelCase ( self ): """simple docstring""" _lowercase : int = VideoMAEModelTester(self ) _lowercase : Union[str, Any] = ConfigTester(self , config_class=_UpperCamelCase , has_text_modality=_UpperCamelCase , hidden_size=37 ) def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=False ): """simple docstring""" _lowercase : Any = copy.deepcopy(_UpperCamelCase ) 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 _lowercase : Union[str, Any] = torch.ones((self.model_tester.num_masks,) ) _lowercase : Dict = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0 ) )] ) _lowercase : List[str] = mask.expand(self.model_tester.batch_size , -1 ).bool() _lowercase : Any = bool_masked_pos.to(_UpperCamelCase ) if return_labels: if model_class in [ *get_values(_UpperCamelCase ), ]: _lowercase : Any = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_UpperCamelCase ) return inputs_dict def _lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="VideoMAE does not use inputs_embeds" ) def _lowerCamelCase ( self ): """simple docstring""" pass def _lowerCamelCase ( self ): """simple docstring""" _lowercase , _lowercase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : List[str] = model_class(_UpperCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowercase : Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCamelCase , nn.Linear ) ) def _lowerCamelCase ( self ): """simple docstring""" _lowercase , _lowercase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : List[Any] = model_class(_UpperCamelCase ) _lowercase : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowercase : str = [*signature.parameters.keys()] _lowercase : List[Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , _UpperCamelCase ) def _lowerCamelCase ( self ): """simple docstring""" _lowercase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCamelCase ) def _lowerCamelCase ( self ): """simple docstring""" _lowercase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_UpperCamelCase ) @slow def _lowerCamelCase ( self ): """simple docstring""" for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowercase : int = VideoMAEModel.from_pretrained(_UpperCamelCase ) self.assertIsNotNone(_UpperCamelCase ) def _lowerCamelCase ( self ): """simple docstring""" if not self.has_attentions: pass else: _lowercase , _lowercase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() _lowercase : Optional[int] = True for model_class in self.all_model_classes: _lowercase : List[str] = self.model_tester.seq_length - self.model_tester.num_masks _lowercase : List[Any] = ( num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length ) _lowercase : int = True _lowercase : str = False _lowercase : Any = True _lowercase : Optional[Any] = model_class(_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() with torch.no_grad(): _lowercase : Union[str, Any] = model(**self._prepare_for_class(_UpperCamelCase , _UpperCamelCase ) ) _lowercase : List[str] = outputs.attentions self.assertEqual(len(_UpperCamelCase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _lowercase : Tuple = True _lowercase : Optional[Any] = model_class(_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() with torch.no_grad(): _lowercase : Dict = model(**self._prepare_for_class(_UpperCamelCase , _UpperCamelCase ) ) _lowercase : Tuple = outputs.attentions self.assertEqual(len(_UpperCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) _lowercase : str = len(_UpperCamelCase ) # Check attention is always last and order is fine _lowercase : List[Any] = True _lowercase : List[str] = True _lowercase : Any = model_class(_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() with torch.no_grad(): _lowercase : Optional[int] = model(**self._prepare_for_class(_UpperCamelCase , _UpperCamelCase ) ) self.assertEqual(out_len + 1 , len(_UpperCamelCase ) ) _lowercase : Optional[int] = outputs.attentions self.assertEqual(len(_UpperCamelCase ) , 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 _lowerCamelCase ( self ): """simple docstring""" def check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): _lowercase : Optional[int] = model_class(_UpperCamelCase ) model.to(_UpperCamelCase ) model.eval() with torch.no_grad(): _lowercase : Tuple = model(**self._prepare_for_class(_UpperCamelCase , _UpperCamelCase ) ) _lowercase : List[str] = outputs.hidden_states _lowercase : List[Any] = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(_UpperCamelCase ) , _UpperCamelCase ) _lowercase : List[str] = self.model_tester.seq_length - self.model_tester.num_masks _lowercase : Optional[Any] = 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] , ) _lowercase , _lowercase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : Dict = True check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowercase : List[str] = True check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _lowerCamelCase ( self ): """simple docstring""" pass def _A ( ) -> Any: _lowercase : Tuple = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) _lowercase : int = np.load(snake_case ) return list(snake_case ) @require_torch @require_vision class a__ ( unittest.TestCase ): @cached_property def _lowerCamelCase ( self ): """simple docstring""" 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 _lowerCamelCase ( self ): """simple docstring""" _lowercase : Tuple = VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics" ).to( _UpperCamelCase ) _lowercase : Dict = self.default_image_processor _lowercase : Optional[Any] = prepare_video() _lowercase : Union[str, Any] = image_processor(_UpperCamelCase , return_tensors="pt" ).to(_UpperCamelCase ) # forward pass with torch.no_grad(): _lowercase : str = model(**_UpperCamelCase ) # verify the logits _lowercase : List[Any] = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , _UpperCamelCase ) _lowercase : int = torch.tensor([0.3_6_6_9, -0.0_6_8_8, -0.2_4_2_1] ).to(_UpperCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _UpperCamelCase , atol=1E-4 ) ) @slow def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Union[str, Any] = VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short" ).to(_UpperCamelCase ) _lowercase : Dict = self.default_image_processor _lowercase : Optional[Any] = prepare_video() _lowercase : List[Any] = image_processor(_UpperCamelCase , return_tensors="pt" ).to(_UpperCamelCase ) # add boolean mask, indicating which patches to mask _lowercase : int = hf_hub_download(repo_id="hf-internal-testing/bool-masked-pos" , filename="bool_masked_pos.pt" ) _lowercase : Any = torch.load(_UpperCamelCase ) # forward pass with torch.no_grad(): _lowercase : List[Any] = model(**_UpperCamelCase ) # verify the logits _lowercase : Dict = torch.Size([1, 1408, 1536] ) _lowercase : Tuple = torch.tensor( [[0.7_9_9_4, 0.9_6_1_2, 0.8_5_0_8], [0.7_4_0_1, 0.8_9_5_8, 0.8_3_0_2], [0.5_8_6_2, 0.7_4_6_8, 0.7_3_2_5]] , device=_UpperCamelCase ) self.assertEqual(outputs.logits.shape , _UpperCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , _UpperCamelCase , atol=1E-4 ) ) # verify the loss (`config.norm_pix_loss` = `True`) _lowercase : Tuple = torch.tensor([0.5_1_4_2] , device=_UpperCamelCase ) self.assertTrue(torch.allclose(outputs.loss , _UpperCamelCase , atol=1E-4 ) ) # verify the loss (`config.norm_pix_loss` = `False`) _lowercase : Dict = VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short" , norm_pix_loss=_UpperCamelCase ).to( _UpperCamelCase ) with torch.no_grad(): _lowercase : Optional[int] = model(**_UpperCamelCase ) _lowercase : List[str] = torch.tensor(torch.tensor([0.6_4_6_9] ) , device=_UpperCamelCase ) self.assertTrue(torch.allclose(outputs.loss , _UpperCamelCase , atol=1E-4 ) )
250
1
import unittest from typing import Dict, List, Optional, Union 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 BridgeTowerImageProcessor class lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__(self , _lowerCamelCase , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = 32 , _lowerCamelCase = True , _lowerCamelCase = 1 / 255 , _lowerCamelCase = True , _lowerCamelCase = True , _lowerCamelCase = [0.48_145_466, 0.4_578_275, 0.40_821_073] , _lowerCamelCase = [0.26_862_954, 0.26_130_258, 0.27_577_711] , _lowerCamelCase = True , _lowerCamelCase=7 , _lowerCamelCase=30 , _lowerCamelCase=400 , _lowerCamelCase=3 , ): """simple docstring""" UpperCAmelCase__ : List[Any] = parent UpperCAmelCase__ : Dict = do_resize UpperCAmelCase__ : Union[str, Any] = size if size is not None else {"""shortest_edge""": 288} UpperCAmelCase__ : str = size_divisor UpperCAmelCase__ : Tuple = do_rescale UpperCAmelCase__ : Dict = rescale_factor UpperCAmelCase__ : List[Any] = do_normalize UpperCAmelCase__ : str = do_center_crop UpperCAmelCase__ : Any = image_mean UpperCAmelCase__ : Union[str, Any] = image_std UpperCAmelCase__ : int = do_pad UpperCAmelCase__ : int = batch_size UpperCAmelCase__ : str = num_channels UpperCAmelCase__ : Any = min_resolution UpperCAmelCase__ : Optional[int] = max_resolution def _a (self ): """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def _a (self , _lowerCamelCase , _lowerCamelCase=False ): """simple docstring""" if not batched: UpperCAmelCase__ : Union[str, Any] = self.size["""shortest_edge"""] UpperCAmelCase__ : Any = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): UpperCAmelCase__ : Optional[int] = image.size else: UpperCAmelCase__ : Tuple = image.shape[1], image.shape[2] UpperCAmelCase__ : List[Any] = size / min(_lowerCamelCase , _lowerCamelCase ) if h < w: UpperCAmelCase__ : List[str] = size, scale * w else: UpperCAmelCase__ : Optional[Any] = scale * h, size UpperCAmelCase__ : str = int((1333 / 800) * size ) if max(_lowerCamelCase , _lowerCamelCase ) > max_size: UpperCAmelCase__ : List[Any] = max_size / max(_lowerCamelCase , _lowerCamelCase ) UpperCAmelCase__ : Dict = newh * scale UpperCAmelCase__ : Tuple = neww * scale UpperCAmelCase__ : Optional[Any] = int(newh + 0.5 ), int(neww + 0.5 ) UpperCAmelCase__ : Optional[Any] = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: UpperCAmelCase__ : List[str] = [] for image in image_inputs: UpperCAmelCase__ : Any = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCAmelCase__ : Any = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] UpperCAmelCase__ : Any = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCamelCase ( lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = BridgeTowerImageProcessor if is_vision_available() else None def _a (self ): """simple docstring""" UpperCAmelCase__ : List[Any] = BridgeTowerImageProcessingTester(self ) @property def _a (self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def _a (self ): """simple docstring""" UpperCAmelCase__ : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , """image_mean""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """image_std""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """do_normalize""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """do_resize""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """size""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """size_divisor""" ) ) def _a (self ): """simple docstring""" pass def _a (self ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase__ : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input UpperCAmelCase__ : int = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCAmelCase__ : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ : Tuple = image_processing(_lowerCamelCase , return_tensors="""pt""" ).pixel_values UpperCAmelCase__ : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _a (self ): """simple docstring""" UpperCAmelCase__ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase__ : str = 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 UpperCAmelCase__ : Any = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCAmelCase__ : str = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors="""pt""" ).pixel_values UpperCAmelCase__ : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _a (self ): """simple docstring""" UpperCAmelCase__ : Optional[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=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input UpperCAmelCase__ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCAmelCase__ : int = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ : Optional[int] = image_processing(_lowerCamelCase , return_tensors="""pt""" ).pixel_values UpperCAmelCase__ : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
358
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class lowerCamelCase ( lowerCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE = 42 class lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' @register_to_config def __init__(self , _lowerCamelCase = 65536 , _lowerCamelCase = None , _lowerCamelCase = 2 , _lowerCamelCase = 2 , _lowerCamelCase = 0 , _lowerCamelCase = "fourier" , _lowerCamelCase = True , _lowerCamelCase = False , _lowerCamelCase = 0.0 , _lowerCamelCase = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , _lowerCamelCase = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , _lowerCamelCase = "UNetMidBlock1D" , _lowerCamelCase = None , _lowerCamelCase = (32, 32, 64) , _lowerCamelCase = None , _lowerCamelCase = 8 , _lowerCamelCase = 1 , _lowerCamelCase = False , ): """simple docstring""" super().__init__() UpperCAmelCase__ : str = sample_size # time if time_embedding_type == "fourier": UpperCAmelCase__ : Any = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=_lowerCamelCase , log=_lowerCamelCase , flip_sin_to_cos=_lowerCamelCase ) UpperCAmelCase__ : Tuple = 2 * block_out_channels[0] elif time_embedding_type == "positional": UpperCAmelCase__ : List[str] = Timesteps( block_out_channels[0] , flip_sin_to_cos=_lowerCamelCase , downscale_freq_shift=_lowerCamelCase ) UpperCAmelCase__ : Optional[Any] = block_out_channels[0] if use_timestep_embedding: UpperCAmelCase__ : Optional[Any] = block_out_channels[0] * 4 UpperCAmelCase__ : Any = TimestepEmbedding( in_channels=_lowerCamelCase , time_embed_dim=_lowerCamelCase , act_fn=_lowerCamelCase , out_dim=block_out_channels[0] , ) UpperCAmelCase__ : Optional[Any] = nn.ModuleList([] ) UpperCAmelCase__ : int = None UpperCAmelCase__ : str = nn.ModuleList([] ) UpperCAmelCase__ : Optional[int] = None # down UpperCAmelCase__ : List[str] = in_channels for i, down_block_type in enumerate(_lowerCamelCase ): UpperCAmelCase__ : Optional[Any] = output_channel UpperCAmelCase__ : List[str] = block_out_channels[i] if i == 0: input_channel += extra_in_channels UpperCAmelCase__ : Any = i == len(_lowerCamelCase ) - 1 UpperCAmelCase__ : Dict = get_down_block( _lowerCamelCase , num_layers=_lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(_lowerCamelCase ) # mid UpperCAmelCase__ : Optional[Any] = get_mid_block( _lowerCamelCase , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=_lowerCamelCase , add_downsample=_lowerCamelCase , ) # up UpperCAmelCase__ : Tuple = list(reversed(_lowerCamelCase ) ) UpperCAmelCase__ : List[str] = reversed_block_out_channels[0] if out_block_type is None: UpperCAmelCase__ : int = out_channels else: UpperCAmelCase__ : List[Any] = block_out_channels[0] for i, up_block_type in enumerate(_lowerCamelCase ): UpperCAmelCase__ : Any = output_channel UpperCAmelCase__ : Dict = ( reversed_block_out_channels[i + 1] if i < len(_lowerCamelCase ) - 1 else final_upsample_channels ) UpperCAmelCase__ : Union[str, Any] = i == len(_lowerCamelCase ) - 1 UpperCAmelCase__ : Optional[int] = get_up_block( _lowerCamelCase , num_layers=_lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(_lowerCamelCase ) UpperCAmelCase__ : Dict = output_channel # out UpperCAmelCase__ : Optional[int] = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) UpperCAmelCase__ : int = get_out_block( out_block_type=_lowerCamelCase , num_groups_out=_lowerCamelCase , embed_dim=block_out_channels[0] , out_channels=_lowerCamelCase , act_fn=_lowerCamelCase , fc_dim=block_out_channels[-1] // 4 , ) def _a (self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = True , ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = timestep if not torch.is_tensor(_lowerCamelCase ): UpperCAmelCase__ : Dict = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(_lowerCamelCase ) and len(timesteps.shape ) == 0: UpperCAmelCase__ : List[str] = timesteps[None].to(sample.device ) UpperCAmelCase__ : Optional[Any] = self.time_proj(_lowerCamelCase ) if self.config.use_timestep_embedding: UpperCAmelCase__ : Dict = self.time_mlp(_lowerCamelCase ) else: UpperCAmelCase__ : int = timestep_embed[..., None] UpperCAmelCase__ : List[str] = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) UpperCAmelCase__ : Dict = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down UpperCAmelCase__ : Optional[Any] = () for downsample_block in self.down_blocks: UpperCAmelCase__ , UpperCAmelCase__ : Dict = downsample_block(hidden_states=_lowerCamelCase , temb=_lowerCamelCase ) down_block_res_samples += res_samples # 3. mid if self.mid_block: UpperCAmelCase__ : Optional[Any] = self.mid_block(_lowerCamelCase , _lowerCamelCase ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): UpperCAmelCase__ : int = down_block_res_samples[-1:] UpperCAmelCase__ : Dict = down_block_res_samples[:-1] UpperCAmelCase__ : str = upsample_block(_lowerCamelCase , res_hidden_states_tuple=_lowerCamelCase , temb=_lowerCamelCase ) # 5. post-process if self.out_block: UpperCAmelCase__ : str = self.out_block(_lowerCamelCase , _lowerCamelCase ) if not return_dict: return (sample,) return UNetaDOutput(sample=_lowerCamelCase )
166
0