code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput A : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name def __lowerCAmelCase ( a__ ) -> Union[str, Any]: warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''' , a__ , ) if isinstance(a__ , torch.Tensor ): return image elif isinstance(a__ , PIL.Image.Image ): __a = [image] if isinstance(image[0] , PIL.Image.Image ): __a , __a = image[0].size __a , __a = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 __a = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] __a = np.concatenate(a__ , axis=0 ) __a = np.array(a__ ).astype(np.floataa ) / 255.0 __a = image.transpose(0 , 3 , 1 , 2 ) __a = 2.0 * image - 1.0 __a = torch.from_numpy(a__ ) elif isinstance(image[0] , torch.Tensor ): __a = torch.cat(a__ , dim=0 ) return image def __lowerCAmelCase ( a__ ) -> Any: if isinstance(a__ , torch.Tensor ): return mask elif isinstance(a__ , PIL.Image.Image ): __a = [mask] if isinstance(mask[0] , PIL.Image.Image ): __a , __a = mask[0].size __a , __a = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __a = [np.array(m.convert('''L''' ).resize((w, h) , resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] __a = np.concatenate(a__ , axis=0 ) __a = mask.astype(np.floataa ) / 255.0 __a = 0 __a = 1 __a = torch.from_numpy(a__ ) elif isinstance(mask[0] , torch.Tensor ): __a = torch.cat(a__ , dim=0 ) return mask class __A( a ): snake_case_ = 42 snake_case_ = 42 def __init__( self , _snake_case , _snake_case ) -> List[Any]: '''simple docstring''' super().__init__() self.register_modules(unet=_snake_case , scheduler=_snake_case ) @torch.no_grad() def __call__( self , _snake_case , _snake_case , _snake_case = 250 , _snake_case = 0.0 , _snake_case = 10 , _snake_case = 10 , _snake_case = None , _snake_case = "pil" , _snake_case = True , ) -> Union[ImagePipelineOutput, Tuple]: '''simple docstring''' __a = image __a = _preprocess_image(_snake_case ) __a = original_image.to(device=self.device , dtype=self.unet.dtype ) __a = _preprocess_mask(_snake_case ) __a = mask_image.to(device=self.device , dtype=self.unet.dtype ) __a = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(_snake_case , _snake_case ) and len(_snake_case ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(_snake_case )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) __a = original_image.shape __a = randn_tensor(_snake_case , generator=_snake_case , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(_snake_case , _snake_case , _snake_case , self.device ) __a = eta __a = self.scheduler.timesteps[0] + 1 __a = generator[0] if isinstance(_snake_case , _snake_case ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual __a = self.unet(_snake_case , _snake_case ).sample # compute previous image: x_t -> x_t-1 __a = self.scheduler.step(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ).prev_sample else: # compute the reverse: x_t-1 -> x_t __a = self.scheduler.undo_step(_snake_case , _snake_case , _snake_case ) __a = t __a = (image / 2 + 0.5).clamp(0 , 1 ) __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(_snake_case ) if not return_dict: return (image,) return ImagePipelineOutput(images=_snake_case )
219
def __lowerCAmelCase ( a__ , a__ ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
219
1
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
676
from maths.prime_check import is_prime def A ( snake_case__ : int ) -> int: '''simple docstring''' if not isinstance(snake_case__ , snake_case__ ): __snake_case = f"Input value of [number={number}] must be an integer" raise TypeError(snake_case__ ) if is_prime(snake_case__ ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
676
1
class __magic_name__ : def __init__( self , _lowercase )-> None: UpperCamelCase_ = size UpperCamelCase_ = [0] * size UpperCamelCase_ = [0] * size @staticmethod def UpperCAmelCase_ ( _lowercase )-> int: return index | (index + 1) @staticmethod def UpperCAmelCase_ ( _lowercase )-> int: return (index & (index + 1)) - 1 def UpperCAmelCase_ ( self , _lowercase , _lowercase )-> None: UpperCamelCase_ = value while index < self.size: UpperCamelCase_ = self.get_prev(_lowercase ) + 1 if current_left_border == index: UpperCamelCase_ = value else: UpperCamelCase_ = max(_lowercase , _lowercase , _lowercase ) UpperCamelCase_ = self.get_next(_lowercase ) def UpperCAmelCase_ ( self , _lowercase , _lowercase )-> int: right -= 1 # Because of right is exclusive UpperCamelCase_ = 0 while left <= right: UpperCamelCase_ = self.get_prev(_lowercase ) if left <= current_left: UpperCamelCase_ = max(_lowercase , self.tree[right] ) UpperCamelCase_ = current_left else: UpperCamelCase_ = max(_lowercase , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
628
import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __magic_name__ : @staticmethod def UpperCAmelCase_ ( *_lowercase , **_lowercase )-> Optional[int]: pass @is_pipeline_test @require_vision @require_torch class __magic_name__ ( unittest.TestCase ): UpperCamelCase_ :Optional[Any] = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def UpperCAmelCase_ ( self , _lowercase , _lowercase , _lowercase )-> Union[str, Any]: UpperCamelCase_ = pipeline( "zero-shot-object-detection" , model="hf-internal-testing/tiny-random-owlvit-object-detection" ) UpperCamelCase_ = [ { "image": "./tests/fixtures/tests_samples/COCO/000000039769.png", "candidate_labels": ["cat", "remote", "couch"], } ] return object_detector, examples def UpperCAmelCase_ ( self , _lowercase , _lowercase )-> Union[str, Any]: UpperCamelCase_ = object_detector(examples[0] , threshold=0.0 ) UpperCamelCase_ = len(_lowercase ) self.assertGreater(_lowercase , 0 ) self.assertEqual( _lowercase , [ { "score": ANY(_lowercase ), "label": ANY(_lowercase ), "box": {"xmin": ANY(_lowercase ), "ymin": ANY(_lowercase ), "xmax": ANY(_lowercase ), "ymax": ANY(_lowercase )}, } for i in range(_lowercase ) ] , ) @require_tf @unittest.skip("Zero Shot Object Detection not implemented in TF" ) def UpperCAmelCase_ ( self )-> str: pass @require_torch def UpperCAmelCase_ ( self )-> List[Any]: UpperCamelCase_ = pipeline( "zero-shot-object-detection" , model="hf-internal-testing/tiny-random-owlvit-object-detection" ) UpperCamelCase_ = object_detector( "./tests/fixtures/tests_samples/COCO/000000039769.png" , candidate_labels=["cat", "remote", "couch"] , threshold=0.64 , ) self.assertEqual( nested_simplify(_lowercase , decimals=4 ) , [ {"score": 0.7_235, "label": "cat", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.7_218, "label": "remote", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.7_184, "label": "couch", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.6_748, "label": "remote", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.6_656, "label": "cat", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.6_614, "label": "couch", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.6_456, "label": "remote", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, {"score": 0.642, "label": "remote", "box": {"xmin": 67, "ymin": 274, "xmax": 93, "ymax": 297}}, {"score": 0.6_419, "label": "cat", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, ] , ) UpperCamelCase_ = object_detector( [ { "image": "./tests/fixtures/tests_samples/COCO/000000039769.png", "candidate_labels": ["cat", "remote", "couch"], } ] , threshold=0.64 , ) self.assertEqual( nested_simplify(_lowercase , decimals=4 ) , [ [ {"score": 0.7_235, "label": "cat", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.7_218, "label": "remote", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.7_184, "label": "couch", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.6_748, "label": "remote", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.6_656, "label": "cat", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.6_614, "label": "couch", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.6_456, "label": "remote", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, {"score": 0.642, "label": "remote", "box": {"xmin": 67, "ymin": 274, "xmax": 93, "ymax": 297}}, {"score": 0.6_419, "label": "cat", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, ] ] , ) @require_torch @slow def UpperCAmelCase_ ( self )-> Any: UpperCamelCase_ = pipeline("zero-shot-object-detection" ) UpperCamelCase_ = object_detector( "http://images.cocodataset.org/val2017/000000039769.jpg" , candidate_labels=["cat", "remote", "couch"] , ) self.assertEqual( nested_simplify(_lowercase , decimals=4 ) , [ {"score": 0.2_868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, {"score": 0.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, {"score": 0.1_474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}}, {"score": 0.1_208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}}, ] , ) UpperCamelCase_ = object_detector( [ { "image": "http://images.cocodataset.org/val2017/000000039769.jpg", "candidate_labels": ["cat", "remote", "couch"], }, { "image": "http://images.cocodataset.org/val2017/000000039769.jpg", "candidate_labels": ["cat", "remote", "couch"], }, ] , ) self.assertEqual( nested_simplify(_lowercase , decimals=4 ) , [ [ {"score": 0.2_868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, {"score": 0.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, {"score": 0.1_474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}}, {"score": 0.1_208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}}, ], [ {"score": 0.2_868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, {"score": 0.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, {"score": 0.1_474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}}, {"score": 0.1_208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}}, ], ] , ) @require_tf @unittest.skip("Zero Shot Object Detection not implemented in TF" ) def UpperCAmelCase_ ( self )-> Optional[int]: pass @require_torch @slow def UpperCAmelCase_ ( self )-> Optional[Any]: UpperCamelCase_ = 0.2 UpperCamelCase_ = pipeline("zero-shot-object-detection" ) UpperCamelCase_ = object_detector( "http://images.cocodataset.org/val2017/000000039769.jpg" , candidate_labels=["cat", "remote", "couch"] , threshold=_lowercase , ) self.assertEqual( nested_simplify(_lowercase , decimals=4 ) , [ {"score": 0.2_868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, {"score": 0.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, ] , ) @require_torch @slow def UpperCAmelCase_ ( self )-> Optional[int]: UpperCamelCase_ = 2 UpperCamelCase_ = pipeline("zero-shot-object-detection" ) UpperCamelCase_ = object_detector( "http://images.cocodataset.org/val2017/000000039769.jpg" , candidate_labels=["cat", "remote", "couch"] , top_k=_lowercase , ) self.assertEqual( nested_simplify(_lowercase , decimals=4 ) , [ {"score": 0.2_868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, ] , )
628
1
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'mvp' lowercase_ = ['past_key_values'] lowercase_ = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : List[Any] , a_ : Dict=5_0267 , a_ : Tuple=1024 , a_ : Dict=12 , a_ : str=4096 , a_ : List[Any]=16 , a_ : Optional[Any]=12 , a_ : Optional[int]=4096 , a_ : str=16 , a_ : int=0.0 , a_ : Dict=0.0 , a_ : List[Any]="gelu" , a_ : List[str]=1024 , a_ : Any=0.1 , a_ : List[Any]=0.0 , a_ : Dict=0.0 , a_ : Union[str, Any]=0.02 , a_ : Union[str, Any]=0.0 , a_ : Optional[Any]=False , a_ : Tuple=True , a_ : Optional[Any]=1 , a_ : Dict=0 , a_ : str=2 , a_ : Dict=True , a_ : str=2 , a_ : Optional[int]=2 , a_ : Any=False , a_ : Optional[Any]=100 , a_ : int=800 , **a_ : Union[str, Any] , )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = vocab_size SCREAMING_SNAKE_CASE__ : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = d_model SCREAMING_SNAKE_CASE__ : List[str] = encoder_ffn_dim SCREAMING_SNAKE_CASE__ : int = encoder_layers SCREAMING_SNAKE_CASE__ : Dict = encoder_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = decoder_ffn_dim SCREAMING_SNAKE_CASE__ : Union[str, Any] = decoder_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = decoder_attention_heads SCREAMING_SNAKE_CASE__ : Tuple = dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_dropout SCREAMING_SNAKE_CASE__ : List[str] = activation_dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = activation_function SCREAMING_SNAKE_CASE__ : List[str] = init_std SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_layerdrop SCREAMING_SNAKE_CASE__ : Optional[Any] = decoder_layerdrop SCREAMING_SNAKE_CASE__ : Optional[Any] = classifier_dropout SCREAMING_SNAKE_CASE__ : List[Any] = use_cache SCREAMING_SNAKE_CASE__ : List[Any] = encoder_layers SCREAMING_SNAKE_CASE__ : List[Any] = scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_prompt SCREAMING_SNAKE_CASE__ : Any = prompt_length SCREAMING_SNAKE_CASE__ : int = prompt_mid_dim super().__init__( pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , is_encoder_decoder=a_ , decoder_start_token_id=a_ , forced_eos_token_id=a_ , **a_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , a_ ): SCREAMING_SNAKE_CASE__ : Any = self.bos_token_id warnings.warn( F'''Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ''' 'The config can simply be saved and uploaded again to be fixed.' )
702
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
0
"""simple docstring""" from math import sqrt def snake_case__ ( _snake_case : int ): """simple docstring""" assert isinstance(_snake_case , _snake_case ) and ( number >= 0 ), "'number' must been an int and positive" UpperCamelCase__ = True # 0 and 1 are none primes. if number <= 1: UpperCamelCase__ = False for divisor in range(2 , int(round(sqrt(_snake_case ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: UpperCamelCase__ = False break # precondition assert isinstance(_snake_case , _snake_case ), "'status' must been from type bool" return status def snake_case__ ( _snake_case : Any ): """simple docstring""" assert isinstance(_snake_case , _snake_case ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N UpperCamelCase__ = list(range(2 , n + 1 ) ) UpperCamelCase__ = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(_snake_case ) ): for j in range(i + 1 , len(_snake_case ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): UpperCamelCase__ = 0 # filters actual prime numbers. UpperCamelCase__ = [x for x in begin_list if x != 0] # precondition assert isinstance(_snake_case , _snake_case ), "'ans' must been from type list" return ans def snake_case__ ( _snake_case : int ): """simple docstring""" assert isinstance(_snake_case , _snake_case ) and (n > 2), "'N' must been an int and > 2" UpperCamelCase__ = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(_snake_case ): ans.append(_snake_case ) # precondition assert isinstance(_snake_case , _snake_case ), "'ans' must been from type list" return ans def snake_case__ ( _snake_case : List[Any] ): """simple docstring""" assert isinstance(_snake_case , _snake_case ) and number >= 0, "'number' must been an int and >= 0" UpperCamelCase__ = [] # this list will be returns of the function. # potential prime number factors. UpperCamelCase__ = 2 UpperCamelCase__ = number if number == 0 or number == 1: ans.append(_snake_case ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(_snake_case ): while quotient != 1: if is_prime(_snake_case ) and (quotient % factor == 0): ans.append(_snake_case ) quotient /= factor else: factor += 1 else: ans.append(_snake_case ) # precondition assert isinstance(_snake_case , _snake_case ), "'ans' must been from type list" return ans def snake_case__ ( _snake_case : Dict ): """simple docstring""" assert isinstance(_snake_case , _snake_case ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCamelCase__ = 0 # prime factorization of 'number' UpperCamelCase__ = prime_factorization(_snake_case ) UpperCamelCase__ = max(_snake_case ) # precondition assert isinstance(_snake_case , _snake_case ), "'ans' must been from type int" return ans def snake_case__ ( _snake_case : Dict ): """simple docstring""" assert isinstance(_snake_case , _snake_case ) and ( number >= 0 ), "'number' bust been an int and >= 0" UpperCamelCase__ = 0 # prime factorization of 'number' UpperCamelCase__ = prime_factorization(_snake_case ) UpperCamelCase__ = min(_snake_case ) # precondition assert isinstance(_snake_case , _snake_case ), "'ans' must been from type int" return ans def snake_case__ ( _snake_case : str ): """simple docstring""" assert isinstance(_snake_case , _snake_case ), "'number' must been an int" assert isinstance(number % 2 == 0 , _snake_case ), "compare bust been from type bool" return number % 2 == 0 def snake_case__ ( _snake_case : Dict ): """simple docstring""" assert isinstance(_snake_case , _snake_case ), "'number' must been an int" assert isinstance(number % 2 != 0 , _snake_case ), "compare bust been from type bool" return number % 2 != 0 def snake_case__ ( _snake_case : Dict ): """simple docstring""" assert ( isinstance(_snake_case , _snake_case ) and (number > 2) and is_even(_snake_case ) ), "'number' must been an int, even and > 2" UpperCamelCase__ = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' UpperCamelCase__ = get_prime_numbers(_snake_case ) UpperCamelCase__ = len(_snake_case ) # run variable for while-loops. UpperCamelCase__ = 0 UpperCamelCase__ = None # exit variable. for break up the loops UpperCamelCase__ = True while i < len_pn and loop: UpperCamelCase__ = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: UpperCamelCase__ = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(_snake_case , _snake_case ) and (len(_snake_case ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def snake_case__ ( _snake_case : Dict , _snake_case : Optional[Any] ): """simple docstring""" assert ( isinstance(_snake_case , _snake_case ) and isinstance(_snake_case , _snake_case ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." UpperCamelCase__ = 0 while numbera != 0: UpperCamelCase__ = numbera % numbera UpperCamelCase__ = numbera UpperCamelCase__ = rest # precondition assert isinstance(_snake_case , _snake_case ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def snake_case__ ( _snake_case : Any , _snake_case : str ): """simple docstring""" assert ( isinstance(_snake_case , _snake_case ) and isinstance(_snake_case , _snake_case ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." UpperCamelCase__ = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' UpperCamelCase__ = prime_factorization(_snake_case ) UpperCamelCase__ = prime_factorization(_snake_case ) elif numbera == 1 or numbera == 1: UpperCamelCase__ = [] UpperCamelCase__ = [] UpperCamelCase__ = max(_snake_case , _snake_case ) UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: UpperCamelCase__ = prime_fac_a.count(_snake_case ) UpperCamelCase__ = prime_fac_a.count(_snake_case ) for _ in range(max(_snake_case , _snake_case ) ): ans *= n else: UpperCamelCase__ = prime_fac_a.count(_snake_case ) for _ in range(_snake_case ): ans *= n done.append(_snake_case ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: UpperCamelCase__ = prime_fac_a.count(_snake_case ) for _ in range(_snake_case ): ans *= n done.append(_snake_case ) # precondition assert isinstance(_snake_case , _snake_case ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def snake_case__ ( _snake_case : Any ): """simple docstring""" assert isinstance(_snake_case , _snake_case ) and (n >= 0), "'number' must been a positive int" UpperCamelCase__ = 0 UpperCamelCase__ = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(_snake_case ): ans += 1 # precondition assert isinstance(_snake_case , _snake_case ) and is_prime( _snake_case ), "'ans' must been a prime number and from type int" return ans def snake_case__ ( _snake_case : str , _snake_case : Any ): """simple docstring""" assert ( is_prime(_snake_case ) and is_prime(_snake_case ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" UpperCamelCase__ = p_number_a + 1 # jump to the next number UpperCamelCase__ = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(_snake_case ): number += 1 while number < p_number_a: ans.append(_snake_case ) number += 1 # fetch the next prime number. while not is_prime(_snake_case ): number += 1 # precondition assert ( isinstance(_snake_case , _snake_case ) and ans[0] != p_number_a and ans[len(_snake_case ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def snake_case__ ( _snake_case : Union[str, Any] ): """simple docstring""" assert isinstance(_snake_case , _snake_case ) and (n >= 1), "'n' must been int and >= 1" UpperCamelCase__ = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(_snake_case ) # precondition assert ans[0] == 1 and ans[len(_snake_case ) - 1] == n, "Error in function getDivisiors(...)" return ans def snake_case__ ( _snake_case : Any ): """simple docstring""" assert isinstance(_snake_case , _snake_case ) and ( number > 1 ), "'number' must been an int and >= 1" UpperCamelCase__ = get_divisors(_snake_case ) # precondition assert ( isinstance(_snake_case , _snake_case ) and (divisors[0] == 1) and (divisors[len(_snake_case ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def snake_case__ ( _snake_case : Union[str, Any] , _snake_case : Optional[Any] ): """simple docstring""" assert ( isinstance(_snake_case , _snake_case ) and isinstance(_snake_case , _snake_case ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. UpperCamelCase__ = gcd(abs(_snake_case ) , abs(_snake_case ) ) # precondition assert ( isinstance(_snake_case , _snake_case ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def snake_case__ ( _snake_case : int ): """simple docstring""" assert isinstance(_snake_case , _snake_case ) and (n >= 0), "'n' must been a int and >= 0" UpperCamelCase__ = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def snake_case__ ( _snake_case : int ): """simple docstring""" assert isinstance(_snake_case , _snake_case ) and (n >= 0), "'n' must been an int and >= 0" UpperCamelCase__ = 0 UpperCamelCase__ = 1 UpperCamelCase__ = 1 # this will be return for _ in range(n - 1 ): UpperCamelCase__ = ans ans += fiba UpperCamelCase__ = tmp return ans
516
"""simple docstring""" import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('1.0.0a'): raise Exception('requires fairseq >= 1.0.0a') logging.set_verbosity_info() A : Optional[Any] = logging.get_logger(__name__) A : Tuple = 'Hello world! cécé herlolip' def snake_case__ ( _snake_case : str , _snake_case : str , _snake_case : bool ): """simple docstring""" UpperCamelCase__ = FairseqRobertaModel.from_pretrained(_snake_case ) roberta.eval() # disable dropout UpperCamelCase__ = roberta.model.encoder.sentence_encoder UpperCamelCase__ = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_14 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: UpperCamelCase__ = roberta.model.classification_heads["mnli"].out_proj.weight.shape[0] print("Our RoBERTa config:" , _snake_case ) UpperCamelCase__ = XLMRobertaXLForSequenceClassification(_snake_case ) if classification_head else XLMRobertaXLForMaskedLM(_snake_case ) model.eval() # Now let's copy all the weights. # Embeddings UpperCamelCase__ = roberta_sent_encoder.embed_tokens.weight UpperCamelCase__ = roberta_sent_encoder.embed_positions.weight UpperCamelCase__ = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. UpperCamelCase__ = roberta_sent_encoder.layer_norm.weight UpperCamelCase__ = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer UpperCamelCase__ = model.roberta.encoder.layer[i] UpperCamelCase__ = roberta_sent_encoder.layers[i] UpperCamelCase__ = layer.attention UpperCamelCase__ = roberta_layer.self_attn_layer_norm.weight UpperCamelCase__ = roberta_layer.self_attn_layer_norm.bias # self attention UpperCamelCase__ = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) UpperCamelCase__ = roberta_layer.self_attn.q_proj.weight UpperCamelCase__ = roberta_layer.self_attn.q_proj.bias UpperCamelCase__ = roberta_layer.self_attn.k_proj.weight UpperCamelCase__ = roberta_layer.self_attn.k_proj.bias UpperCamelCase__ = roberta_layer.self_attn.v_proj.weight UpperCamelCase__ = roberta_layer.self_attn.v_proj.bias # self-attention output UpperCamelCase__ = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape UpperCamelCase__ = roberta_layer.self_attn.out_proj.weight UpperCamelCase__ = roberta_layer.self_attn.out_proj.bias # this one is final layer norm UpperCamelCase__ = roberta_layer.final_layer_norm.weight UpperCamelCase__ = roberta_layer.final_layer_norm.bias # intermediate UpperCamelCase__ = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape UpperCamelCase__ = roberta_layer.fca.weight UpperCamelCase__ = roberta_layer.fca.bias # output UpperCamelCase__ = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape UpperCamelCase__ = roberta_layer.fca.weight UpperCamelCase__ = roberta_layer.fca.bias # end of layer if classification_head: UpperCamelCase__ = roberta.model.classification_heads["mnli"].dense.weight UpperCamelCase__ = roberta.model.classification_heads["mnli"].dense.bias UpperCamelCase__ = roberta.model.classification_heads["mnli"].out_proj.weight UpperCamelCase__ = roberta.model.classification_heads["mnli"].out_proj.bias else: # LM Head UpperCamelCase__ = roberta.model.encoder.lm_head.dense.weight UpperCamelCase__ = roberta.model.encoder.lm_head.dense.bias UpperCamelCase__ = roberta.model.encoder.lm_head.layer_norm.weight UpperCamelCase__ = roberta.model.encoder.lm_head.layer_norm.bias UpperCamelCase__ = roberta.model.encoder.lm_head.weight UpperCamelCase__ = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. UpperCamelCase__ = roberta.encode(_snake_case ).unsqueeze(0 ) # batch of size 1 UpperCamelCase__ = model(_snake_case )[0] if classification_head: UpperCamelCase__ = roberta.model.classification_heads["mnli"](roberta.extract_features(_snake_case ) ) else: UpperCamelCase__ = roberta.model(_snake_case )[0] print(our_output.shape , their_output.shape ) UpperCamelCase__ = torch.max(torch.abs(our_output - their_output ) ).item() print(F'max_absolute_diff = {max_absolute_diff}' ) # ~ 1e-7 UpperCamelCase__ = torch.allclose(_snake_case , _snake_case , atol=1E-3 ) print("Do both models output the same tensors?" , "🔥" if success else "💩" ) if not success: raise Exception("Something went wRoNg" ) pathlib.Path(_snake_case ).mkdir(parents=_snake_case , exist_ok=_snake_case ) print(F'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(_snake_case ) if __name__ == "__main__": A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--roberta_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--classification_head', action='store_true', help='Whether to convert a final classification head.' ) A : Any = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
516
1
import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def lowerCAmelCase__ ( UpperCamelCase_ : Dict )-> Optional[Any]: # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. if ( (cp >= 0X4E_00 and cp <= 0X9F_FF) or (cp >= 0X34_00 and cp <= 0X4D_BF) # or (cp >= 0X2_00_00 and cp <= 0X2_A6_DF) # or (cp >= 0X2_A7_00 and cp <= 0X2_B7_3F) # or (cp >= 0X2_B7_40 and cp <= 0X2_B8_1F) # or (cp >= 0X2_B8_20 and cp <= 0X2_CE_AF) # or (cp >= 0XF9_00 and cp <= 0XFA_FF) or (cp >= 0X2_F8_00 and cp <= 0X2_FA_1F) # ): # return True return False def lowerCAmelCase__ ( UpperCamelCase_ : str )-> Optional[Any]: # word like '180' or '身高' or '神' for char in word: A__ = ord(UpperCamelCase_ ) if not _is_chinese_char(UpperCamelCase_ ): return 0 return 1 def lowerCAmelCase__ ( UpperCamelCase_ : List[str] )-> List[Any]: A__ = set() for token in tokens: A__ = len(UpperCamelCase_ ) > 1 and is_chinese(UpperCamelCase_ ) if chinese_word: word_set.add(UpperCamelCase_ ) A__ = list(UpperCamelCase_ ) return word_list def lowerCAmelCase__ ( UpperCamelCase_ : List[str] , UpperCamelCase_ : set() )-> List[Any]: if not chinese_word_set: return bert_tokens A__ = max([len(UpperCamelCase_ ) for w in chinese_word_set] ) A__ = bert_tokens A__ , A__ = 0, len(UpperCamelCase_ ) while start < end: A__ = True if is_chinese(bert_word[start] ): A__ = min(end - start , UpperCamelCase_ ) for i in range(UpperCamelCase_ , 1 , -1 ): A__ = ''''''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): A__ = '''##''' + bert_word[j] A__ = start + i A__ = False break if single_word: start += 1 return bert_word def lowerCAmelCase__ ( UpperCamelCase_ : List[str] , UpperCamelCase_ : LTP , UpperCamelCase_ : BertTokenizer )-> int: A__ = [] for i in range(0 , len(UpperCamelCase_ ) , 1_0_0 ): A__ = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] A__ = [get_chinese_word(UpperCamelCase_ ) for r in res] ltp_res.extend(UpperCamelCase_ ) assert len(UpperCamelCase_ ) == len(UpperCamelCase_ ) A__ = [] for i in range(0 , len(UpperCamelCase_ ) , 1_0_0 ): A__ = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=UpperCamelCase_ , truncation=UpperCamelCase_ , max_length=5_1_2 ) bert_res.extend(res['''input_ids'''] ) assert len(UpperCamelCase_ ) == len(UpperCamelCase_ ) A__ = [] for input_ids, chinese_word in zip(UpperCamelCase_ , UpperCamelCase_ ): A__ = [] for id in input_ids: A__ = bert_tokenizer._convert_id_to_token(UpperCamelCase_ ) input_tokens.append(UpperCamelCase_ ) A__ = add_sub_symbol(UpperCamelCase_ , UpperCamelCase_ ) A__ = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(UpperCamelCase_ ): if token[:2] == "##": A__ = token[2:] # save chinese tokens' pos if len(UpperCamelCase_ ) == 1 and _is_chinese_char(ord(UpperCamelCase_ ) ): ref_id.append(UpperCamelCase_ ) ref_ids.append(UpperCamelCase_ ) assert len(UpperCamelCase_ ) == len(UpperCamelCase_ ) return ref_ids def lowerCAmelCase__ ( UpperCamelCase_ : int )-> List[Any]: # For Chinese (Ro)Bert, the best result is from : RoBERTa-wwm-ext (https://github.com/ymcui/Chinese-BERT-wwm) # If we want to fine-tune these model, we have to use same tokenizer : LTP (https://github.com/HIT-SCIR/ltp) with open(args.file_name , '''r''' , encoding='''utf-8''' ) as f: A__ = f.readlines() A__ = [line.strip() for line in data if len(UpperCamelCase_ ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' A__ = LTP(args.ltp ) # faster in GPU device A__ = BertTokenizer.from_pretrained(args.bert ) A__ = prepare_ref(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) with open(args.save_path , '''w''' , encoding='''utf-8''' ) as f: A__ = [json.dumps(UpperCamelCase_ ) + '''\n''' for ref in ref_ids] f.writelines(UpperCamelCase_ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser(description="prepare_chinese_ref") parser.add_argument( "--file_name", type=str, default="./resources/chinese-demo.txt", help="file need process, same as training data in lm", ) parser.add_argument( "--ltp", type=str, default="./resources/ltp", help="resources for LTP tokenizer, usually a path" ) parser.add_argument("--bert", type=str, default="./resources/robert", help="resources for Bert tokenizer") parser.add_argument("--save_path", type=str, default="./resources/ref.txt", help="path to save res") _lowercase = parser.parse_args() main(args)
702
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class _UpperCAmelCase : def __init__( self , a__ , ): A__ = parent A__ = 1_3 A__ = 7 A__ = True A__ = True A__ = True A__ = True A__ = True A__ = False A__ = False A__ = False A__ = 2 A__ = 9_9 A__ = 0 A__ = 3_2 A__ = 2 A__ = 4 A__ = 0.1 A__ = 0.1 A__ = 5_1_2 A__ = 1_6 A__ = 2 A__ = 0.0_2 A__ = 3 A__ = 4 A__ = '''last''' A__ = True A__ = None A__ = 0 def snake_case_ ( self): A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa) A__ = None if self.use_input_lengths: A__ = ( ids_tensor([self.batch_size] , vocab_size=2) + self.seq_length - 2 ) # small variation of seq_length A__ = None if self.use_token_type_ids: A__ = ids_tensor([self.batch_size, self.seq_length] , self.n_langs) 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] , 2 , dtype=tf.floataa) A__ = ids_tensor([self.batch_size] , self.num_choices) A__ = FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def snake_case_ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): A__ = TFFlaubertModel(config=a__) A__ = {'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids} A__ = model(a__) A__ = [input_ids, input_mask] A__ = model(a__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def snake_case_ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): A__ = TFFlaubertWithLMHeadModel(a__) A__ = {'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids} A__ = model(a__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def snake_case_ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): A__ = TFFlaubertForQuestionAnsweringSimple(a__) A__ = {'''input_ids''': input_ids, '''lengths''': input_lengths} A__ = model(a__) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def snake_case_ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): A__ = TFFlaubertForSequenceClassification(a__) A__ = {'''input_ids''': input_ids, '''lengths''': input_lengths} A__ = model(a__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def snake_case_ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): A__ = self.num_labels A__ = TFFlaubertForTokenClassification(config=a__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(a__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def snake_case_ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): A__ = self.num_choices A__ = TFFlaubertForMultipleChoice(config=a__) A__ = tf.tile(tf.expand_dims(a__ , 1) , (1, self.num_choices, 1)) A__ = tf.tile(tf.expand_dims(a__ , 1) , (1, self.num_choices, 1)) A__ = tf.tile(tf.expand_dims(a__ , 1) , (1, self.num_choices, 1)) A__ = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } A__ = model(a__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def snake_case_ ( self): A__ = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = config_and_inputs A__ = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''langs''': token_type_ids, '''lengths''': input_lengths, } return config, inputs_dict @require_tf class _UpperCAmelCase ( A__ , A__ , unittest.TestCase ): UpperCamelCase__ = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) UpperCamelCase__ = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable UpperCamelCase__ = ( { '''feature-extraction''': TFFlaubertModel, '''fill-mask''': TFFlaubertWithLMHeadModel, '''question-answering''': TFFlaubertForQuestionAnsweringSimple, '''text-classification''': TFFlaubertForSequenceClassification, '''token-classification''': TFFlaubertForTokenClassification, '''zero-shot''': TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) UpperCamelCase__ = False UpperCamelCase__ = False def snake_case_ ( self , a__ , a__ , a__ , a__ , a__): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('''Fast''') ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def snake_case_ ( self): A__ = TFFlaubertModelTester(self) A__ = ConfigTester(self , config_class=a__ , emb_dim=3_7) def snake_case_ ( self): self.config_tester.run_common_tests() def snake_case_ ( self): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*a__) def snake_case_ ( self): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*a__) def snake_case_ ( self): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*a__) def snake_case_ ( self): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*a__) def snake_case_ ( self): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*a__) def snake_case_ ( self): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*a__) @slow def snake_case_ ( self): for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = TFFlaubertModel.from_pretrained(a__) self.assertIsNotNone(a__) @require_tf @require_sentencepiece @require_tokenizers class _UpperCAmelCase ( unittest.TestCase ): @slow def snake_case_ ( self): A__ = TFFlaubertModel.from_pretrained('''jplu/tf-flaubert-small-cased''') A__ = tf.convert_to_tensor( [[0, 1_5_8, 7_3_5, 2_5_9_2, 1_4_2_4, 6_7_2_7, 8_2, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" A__ = model(a__)[0] A__ = tf.TensorShape((1, 8, 5_1_2)) self.assertEqual(output.shape , a__) # compare the actual values for a slice. A__ = tf.convert_to_tensor( [ [ [-1.8_7_6_8_7_7_3, -1.5_6_6_5_5_5, 0.2_7_0_7_2_4_1_8], [-1.6_9_2_0_0_3_8, -0.5_8_7_3_5_0_5, 1.9_3_2_9_5_9_9], [-2.9_5_6_3_9_8_5, -1.6_9_9_3_8_3_5, 1.7_9_7_2_0_5_2], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4))
526
0
import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class _UpperCamelCase : '''simple docstring''' def __init__( self : Optional[Any] , a : Any , a : str=13 , a : Union[str, Any]=7 , a : int=True , a : Optional[Any]=True , a : Optional[int]=True , a : int=True , a : List[Any]=99 , a : List[Any]=16 , a : str=36 , a : Dict=6 , a : str=6 , a : List[str]=6 , a : Any=37 , a : Optional[Any]="gelu" , a : List[str]=0.1 , a : Tuple=0.1 , a : int=512 , a : Optional[Any]=16 , a : List[str]=2 , a : List[str]=0.02 , a : int=3 , a : int=4 , a : Union[str, Any]=None , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : List[str] = batch_size SCREAMING_SNAKE_CASE : int = seq_length SCREAMING_SNAKE_CASE : int = is_training SCREAMING_SNAKE_CASE : Optional[Any] = use_input_mask SCREAMING_SNAKE_CASE : str = use_token_type_ids SCREAMING_SNAKE_CASE : int = use_labels SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE : Optional[int] = embedding_size SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = num_hidden_groups SCREAMING_SNAKE_CASE : Tuple = num_attention_heads SCREAMING_SNAKE_CASE : int = intermediate_size SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = type_vocab_size SCREAMING_SNAKE_CASE : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = num_labels SCREAMING_SNAKE_CASE : int = num_choices SCREAMING_SNAKE_CASE : str = scope def __UpperCamelCase ( self : Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : List[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : Optional[Any] = None SCREAMING_SNAKE_CASE : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase ( self : Tuple ) -> Tuple: """simple docstring""" return AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , ) def __UpperCamelCase ( self : Union[str, Any] , a : Optional[int] , a : Optional[Any] , a : int , a : Dict , a : int , a : Union[str, Any] , a : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = AlbertModel(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Any = model(a , attention_mask=a , token_type_ids=a ) SCREAMING_SNAKE_CASE : Optional[int] = model(a , token_type_ids=a ) SCREAMING_SNAKE_CASE : Dict = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCamelCase ( self : str , a : int , a : Optional[int] , a : Optional[Any] , a : Dict , a : str , a : int , a : Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : int = AlbertForPreTraining(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Union[str, Any] = model( a , attention_mask=a , token_type_ids=a , labels=a , sentence_order_label=a , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def __UpperCamelCase ( self : Any , a : Any , a : Any , a : Optional[int] , a : str , a : int , a : str , a : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : str = AlbertForMaskedLM(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Dict = model(a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase ( self : str , a : Tuple , a : Optional[Any] , a : Union[str, Any] , a : Optional[int] , a : Optional[int] , a : List[Any] , a : Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = AlbertForQuestionAnswering(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model( a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase ( self : List[Any] , a : Tuple , a : Tuple , a : int , a : List[Any] , a : List[Any] , a : Dict , a : Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.num_labels SCREAMING_SNAKE_CASE : Optional[int] = AlbertForSequenceClassification(a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : int = model(a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase ( self : List[str] , a : List[str] , a : str , a : Optional[int] , a : Optional[int] , a : str , a : List[Any] , a : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : str = self.num_labels SCREAMING_SNAKE_CASE : Union[str, Any] = AlbertForTokenClassification(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : str = model(a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase ( self : str , a : Optional[int] , a : Tuple , a : Optional[int] , a : Union[str, Any] , a : Union[str, Any] , a : List[Any] , a : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : str = self.num_choices SCREAMING_SNAKE_CASE : Any = AlbertForMultipleChoice(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : Union[str, Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : List[str] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : List[str] = model( a , attention_mask=a , token_type_ids=a , labels=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase ( self : int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) , ) : int = config_and_inputs SCREAMING_SNAKE_CASE : List[str] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _UpperCamelCase ( __A , __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) lowerCamelCase__ =( { 'feature-extraction': AlbertModel, 'fill-mask': AlbertForMaskedLM, 'question-answering': AlbertForQuestionAnswering, 'text-classification': AlbertForSequenceClassification, 'token-classification': AlbertForTokenClassification, 'zero-shot': AlbertForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase__ =True def __UpperCamelCase ( self : List[str] , a : int , a : List[str] , a : Optional[int]=False ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = super()._prepare_for_class(a , a , return_labels=a ) if return_labels: if model_class in get_values(a ): SCREAMING_SNAKE_CASE : int = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=a ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a ) return inputs_dict def __UpperCamelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = AlbertModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = ConfigTester(self , config_class=a , hidden_size=37 ) def __UpperCamelCase ( self : Tuple ) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() def __UpperCamelCase ( self : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def __UpperCamelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*a ) def __UpperCamelCase ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a ) def __UpperCamelCase ( self : str ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*a ) def __UpperCamelCase ( self : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a ) def __UpperCamelCase ( self : Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a ) def __UpperCamelCase ( self : Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE : Any = type self.model_tester.create_and_check_model(*a ) @slow def __UpperCamelCase ( self : Tuple ) -> str: """simple docstring""" for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Optional[Any] = AlbertModel.from_pretrained(a ) self.assertIsNotNone(a ) @require_torch class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = AlbertModel.from_pretrained("albert-base-v2" ) SCREAMING_SNAKE_CASE : int = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE : List[Any] = model(a , attention_mask=a )[0] SCREAMING_SNAKE_CASE : Optional[int] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , a ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a , atol=1e-4 ) )
25
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Dict ) -> Tuple: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionKDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4" ) SCREAMING_SNAKE_CASE : str = sd_pipe.to(a ) sd_pipe.set_progress_bar_config(disable=a ) sd_pipe.set_scheduler("sample_euler" ) SCREAMING_SNAKE_CASE : Optional[int] = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = sd_pipe([prompt] , generator=a , guidance_scale=9.0 , num_inference_steps=20 , output_type="np" ) SCREAMING_SNAKE_CASE : Tuple = output.images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.0447, 0.0492, 0.0468, 0.0408, 0.0383, 0.0408, 0.0354, 0.0380, 0.0339] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCamelCase ( self : List[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : int = StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) SCREAMING_SNAKE_CASE : Tuple = sd_pipe.to(a ) sd_pipe.set_progress_bar_config(disable=a ) sd_pipe.set_scheduler("sample_euler" ) SCREAMING_SNAKE_CASE : List[str] = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe([prompt] , generator=a , guidance_scale=9.0 , num_inference_steps=20 , output_type="np" ) SCREAMING_SNAKE_CASE : List[Any] = output.images SCREAMING_SNAKE_CASE : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : int = np.array([0.1237, 0.1320, 0.1438, 0.1359, 0.1390, 0.1132, 0.1277, 0.1175, 0.1112] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-1 def __UpperCamelCase ( self : Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe.to(a ) sd_pipe.set_progress_bar_config(disable=a ) sd_pipe.set_scheduler("sample_dpmpp_2m" ) SCREAMING_SNAKE_CASE : str = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = sd_pipe( [prompt] , generator=a , guidance_scale=7.5 , num_inference_steps=15 , output_type="np" , use_karras_sigmas=a , ) SCREAMING_SNAKE_CASE : str = output.images SCREAMING_SNAKE_CASE : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE : int = np.array( [0.1138_1689, 0.1211_2921, 0.138_9457, 0.1254_9606, 0.124_4964, 0.1083_1517, 0.1156_2866, 0.1086_7816, 0.1049_9048] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
25
1
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow lowerCAmelCase_ = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ """text-classification""", """language-modeling""", """summarization""", """token-classification""", """question-answering""", ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) lowerCAmelCase_ = logging.getLogger() def __lowerCAmelCase ( ) -> Union[str, Any]: lowerCAmelCase__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('''-f''' ) lowerCAmelCase__ : str = parser.parse_args() return args.f def __lowerCAmelCase ( UpperCamelCase , UpperCamelCase="eval" ) -> Tuple: lowerCAmelCase__ : Any = os.path.join(UpperCamelCase , F"""{split}_results.json""" ) if os.path.exists(UpperCamelCase ): with open(UpperCamelCase , '''r''' ) as f: return json.load(UpperCamelCase ) raise ValueError(F"""can't find {path}""" ) lowerCAmelCase_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class _lowerCAmelCase ( _lowercase ): def __magic_name__( self ): lowerCAmelCase__ : List[Any] = self.get_auto_remove_tmp_dir() lowerCAmelCase__ : List[str] = f""" run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 """.split() with patch.object(__UpperCAmelCase , '''argv''' , __UpperCAmelCase ): run_flax_glue.main() lowerCAmelCase__ : Dict = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def __magic_name__( self ): lowerCAmelCase__ : str = self.get_auto_remove_tmp_dir() lowerCAmelCase__ : Any = f""" run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(__UpperCAmelCase , '''argv''' , __UpperCAmelCase ): run_clm_flax.main() lowerCAmelCase__ : Optional[int] = get_results(__UpperCAmelCase ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def __magic_name__( self ): lowerCAmelCase__ : str = self.get_auto_remove_tmp_dir() lowerCAmelCase__ : Tuple = f""" run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate """.split() with patch.object(__UpperCAmelCase , '''argv''' , __UpperCAmelCase ): run_summarization_flax.main() lowerCAmelCase__ : Dict = get_results(__UpperCAmelCase , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def __magic_name__( self ): lowerCAmelCase__ : Any = self.get_auto_remove_tmp_dir() lowerCAmelCase__ : Dict = f""" run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 """.split() with patch.object(__UpperCAmelCase , '''argv''' , __UpperCAmelCase ): run_mlm_flax.main() lowerCAmelCase__ : Tuple = get_results(__UpperCAmelCase ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def __magic_name__( self ): lowerCAmelCase__ : int = self.get_auto_remove_tmp_dir() lowerCAmelCase__ : Union[str, Any] = f""" run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(__UpperCAmelCase , '''argv''' , __UpperCAmelCase ): run_ta_mlm_flax.main() lowerCAmelCase__ : Any = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def __magic_name__( self ): # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu lowerCAmelCase__ : List[Any] = 7 if get_gpu_count() > 1 else 2 lowerCAmelCase__ : Union[str, Any] = self.get_auto_remove_tmp_dir() lowerCAmelCase__ : Any = f""" run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 """.split() with patch.object(__UpperCAmelCase , '''argv''' , __UpperCAmelCase ): run_flax_ner.main() lowerCAmelCase__ : List[str] = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def __magic_name__( self ): lowerCAmelCase__ : Tuple = self.get_auto_remove_tmp_dir() lowerCAmelCase__ : Dict = f""" run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 """.split() with patch.object(__UpperCAmelCase , '''argv''' , __UpperCAmelCase ): run_qa.main() lowerCAmelCase__ : Any = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
470
from datetime import datetime import matplotlib.pyplot as plt import torch def __lowerCAmelCase ( UpperCamelCase ) -> str: for param in module.parameters(): lowerCAmelCase__ : int = False def __lowerCAmelCase ( ) -> Optional[Any]: lowerCAmelCase__ : List[Any] = '''cuda''' if torch.cuda.is_available() else '''cpu''' if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCAmelCase__ : Optional[Any] = '''mps''' if device == "mps": print( '''WARNING: MPS currently doesn\'t seem to work, and messes up backpropagation without any visible torch''' ''' errors. I recommend using CUDA on a colab notebook or CPU instead if you\'re facing inexplicable issues''' ''' with generations.''' ) return device def __lowerCAmelCase ( UpperCamelCase ) -> List[Any]: lowerCAmelCase__ : str = plt.imshow(UpperCamelCase ) fig.axes.get_xaxis().set_visible(UpperCamelCase ) fig.axes.get_yaxis().set_visible(UpperCamelCase ) plt.show() def __lowerCAmelCase ( ) -> str: lowerCAmelCase__ : Dict = datetime.now() lowerCAmelCase__ : Optional[int] = current_time.strftime('''%H:%M:%S''' ) return timestamp
470
1
import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class UpperCAmelCase__ : '''simple docstring''' def __init__( self : Optional[Any] , UpperCamelCase : List[str] , UpperCamelCase : Optional[int]=99 , UpperCamelCase : Optional[Any]=13 , UpperCamelCase : List[Any]=16 , UpperCamelCase : Tuple=7 , UpperCamelCase : Any=True , UpperCamelCase : Union[str, Any]=True , UpperCamelCase : List[str]=True , UpperCamelCase : Dict=False , UpperCamelCase : str=True , UpperCamelCase : Any=2 , UpperCamelCase : Union[str, Any]=32 , UpperCamelCase : str=4 , UpperCamelCase : str=4 , UpperCamelCase : Union[str, Any]=30 , UpperCamelCase : Any=0 , UpperCamelCase : Union[str, Any]=1 , UpperCamelCase : int=2 , UpperCamelCase : int=None , ): """simple docstring""" _lowercase : Tuple = parent _lowercase : Optional[Any] = batch_size _lowercase : Any = decoder_seq_length # For common tests _lowercase : Union[str, Any] = self.decoder_seq_length _lowercase : str = is_training _lowercase : int = use_attention_mask _lowercase : Any = use_labels _lowercase : List[str] = vocab_size _lowercase : int = d_model _lowercase : Optional[int] = d_model _lowercase : Optional[int] = decoder_layers _lowercase : str = decoder_layers _lowercase : Dict = decoder_ffn_dim _lowercase : Union[str, Any] = decoder_attention_heads _lowercase : Optional[Any] = decoder_attention_heads _lowercase : int = eos_token_id _lowercase : Optional[Any] = bos_token_id _lowercase : Any = pad_token_id _lowercase : List[str] = decoder_start_token_id _lowercase : str = use_cache _lowercase : str = max_position_embeddings _lowercase : Union[str, Any] = None _lowercase : int = decoder_seq_length _lowercase : List[Any] = 2 _lowercase : str = 1 def lowerCAmelCase_ ( self : Optional[Any] ): """simple docstring""" _lowercase : Dict = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) _lowercase : Optional[Any] = None if self.use_attention_mask: _lowercase : str = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) _lowercase : int = None if self.use_labels: _lowercase : Union[str, Any] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) _lowercase : List[str] = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def lowerCAmelCase_ ( self : Optional[Any] , UpperCamelCase : Dict , UpperCamelCase : Optional[Any] , UpperCamelCase : List[str] , UpperCamelCase : int , ): """simple docstring""" _lowercase : List[str] = True _lowercase : int = TrOCRDecoder(config=UpperCamelCase ).to(UpperCamelCase ).eval() _lowercase : List[Any] = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass _lowercase : List[str] = model(UpperCamelCase , use_cache=UpperCamelCase ) _lowercase : Optional[Any] = model(UpperCamelCase ) _lowercase : Tuple = model(UpperCamelCase , use_cache=UpperCamelCase ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) + 1 ) _lowercase : int = outputs['''past_key_values'''] # create hypothetical next token and extent to next_input_ids _lowercase : Any = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and _lowercase : Dict = torch.cat([input_ids, next_tokens] , dim=-1 ) _lowercase : str = model(UpperCamelCase )['''last_hidden_state'''] _lowercase : str = model(UpperCamelCase , past_key_values=UpperCamelCase )['''last_hidden_state'''] # select random slice _lowercase : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() _lowercase : Dict = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() _lowercase : List[Any] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1E-3 ) def lowerCAmelCase_ ( self : Optional[Any] ): """simple docstring""" _lowercase : Tuple = self.prepare_config_and_inputs() _lowercase , _lowercase , _lowercase , _lowercase : List[Any] = config_and_inputs _lowercase : str = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_torch class UpperCAmelCase__ ( A_ , A_ , A_ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase_ = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () UpperCAmelCase_ = (TrOCRForCausalLM,) if is_torch_available() else () UpperCAmelCase_ = {'''text-generation''': TrOCRForCausalLM} if is_torch_available() else {} UpperCAmelCase_ = True UpperCAmelCase_ = False def lowerCAmelCase_ ( self : List[str] ): """simple docstring""" _lowercase : int = TrOCRStandaloneDecoderModelTester(self , is_training=UpperCamelCase ) _lowercase : Union[str, Any] = ConfigTester(self , config_class=UpperCamelCase ) def lowerCAmelCase_ ( self : List[str] ): """simple docstring""" pass def lowerCAmelCase_ ( self : Union[str, Any] ): """simple docstring""" pass def lowerCAmelCase_ ( self : Optional[Any] ): """simple docstring""" pass def lowerCAmelCase_ ( self : Tuple ): """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase_ ( self : Dict ): """simple docstring""" _lowercase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*UpperCamelCase ) def lowerCAmelCase_ ( self : Tuple ): """simple docstring""" return @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def lowerCAmelCase_ ( self : List[str] ): """simple docstring""" pass
322
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor UpperCamelCase__ = logging.get_logger(__name__) class UpperCAmelCase__ ( A_ ): '''simple docstring''' def __init__( self : int , *UpperCamelCase : Optional[Any] , **UpperCamelCase : int ): """simple docstring""" warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , UpperCamelCase , ) super().__init__(*UpperCamelCase , **UpperCamelCase )
322
1
'''simple docstring''' from __future__ import annotations import math def snake_case_ (_a : int ): 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(_a ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True A =[num for num in range(3, 10_00_01, 2) if not is_prime(num)] def snake_case_ (_a : int ): if not isinstance(_a , _a ): raise ValueError('''n must be an integer''' ) if n <= 0: raise ValueError('''n must be >= 0''' ) UpperCAmelCase = [] for num in range(len(_a ) ): UpperCAmelCase = 0 while 2 * i * i <= odd_composites[num]: UpperCAmelCase = odd_composites[num] - 2 * i * i if is_prime(_a ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(_a ) == n: return list_nums return [] def snake_case_ (): return compute_nums(1 )[0] if __name__ == "__main__": print(f"""{solution() = }""")
711
'''simple docstring''' import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _a ( __a , unittest.TestCase ): __a : Any = MgpstrTokenizer __a : Optional[Any] = False __a : str = {} __a : Optional[int] = False def A ( self : Dict ): '''simple docstring''' super().setUp() # fmt: off UpperCAmelCase = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z'''] # fmt: on UpperCAmelCase = dict(zip(lowercase , range(len(lowercase ) ) ) ) UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(lowercase ) + '''\n''' ) def A ( self : int , **lowercase : Optional[Any] ): '''simple docstring''' return MgpstrTokenizer.from_pretrained(self.tmpdirname , **lowercase ) def A ( self : int , lowercase : str ): '''simple docstring''' UpperCAmelCase = '''tester''' UpperCAmelCase = '''tester''' return input_text, output_text @unittest.skip('''MGP-STR always lower cases letters.''' ) def A ( self : Optional[int] ): '''simple docstring''' pass def A ( self : int ): '''simple docstring''' UpperCAmelCase = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): UpperCAmelCase = '''[SPECIAL_TOKEN]''' tokenizer.add_special_tokens({'''cls_token''': special_token} ) UpperCAmelCase = tokenizer.encode([special_token] , add_special_tokens=lowercase ) self.assertEqual(len(lowercase ) , 1 ) UpperCAmelCase = tokenizer.decode(lowercase , skip_special_tokens=lowercase ) self.assertTrue(special_token not in decoded ) def A ( self : List[Any] ): '''simple docstring''' UpperCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): UpperCAmelCase , UpperCAmelCase = self.get_input_output_texts(lowercase ) UpperCAmelCase = tokenizer.tokenize(lowercase ) UpperCAmelCase = tokenizer.convert_tokens_to_ids(lowercase ) UpperCAmelCase = tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertListEqual(lowercase , lowercase ) UpperCAmelCase = tokenizer.convert_ids_to_tokens(lowercase ) self.assertNotEqual(len(lowercase ) , 0 ) UpperCAmelCase = tokenizer.decode(lowercase ) self.assertIsInstance(lowercase , lowercase ) self.assertEqual(text_a.replace(''' ''' , '''''' ) , lowercase ) @unittest.skip('''MGP-STR tokenizer only handles one sequence.''' ) def A ( self : Any ): '''simple docstring''' pass @unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer''' ) def A ( self : str ): '''simple docstring''' pass
358
0
class _SCREAMING_SNAKE_CASE : def __init__( self , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None ): snake_case__ = data snake_case__ = previous snake_case__ = next_node def __str__( self ): return F"""{self.data}""" def A_ ( self ): return self.data def A_ ( self ): return self.next def A_ ( self ): return self.previous class _SCREAMING_SNAKE_CASE : def __init__( self , lowerCamelCase ): snake_case__ = head def __iter__( self ): return self def A_ ( self ): if not self.current: raise StopIteration else: snake_case__ = self.current.get_data() snake_case__ = self.current.get_next() return value class _SCREAMING_SNAKE_CASE : def __init__( self ): snake_case__ = None # First node in list snake_case__ = None # Last node in list def __str__( self ): snake_case__ = self.head snake_case__ = [] while current is not None: nodes.append(current.get_data() ) snake_case__ = current.get_next() return " ".join(str(lowerCamelCase ) for node in nodes ) def __contains__( self , lowerCamelCase ): snake_case__ = self.head while current: if current.get_data() == value: return True snake_case__ = current.get_next() return False def __iter__( self ): return LinkedListIterator(self.head ) def A_ ( self ): if self.head: return self.head.get_data() return None def A_ ( self ): if self.tail: return self.tail.get_data() return None def A_ ( self , lowerCamelCase ): if self.head is None: snake_case__ = node snake_case__ = node else: self.insert_before_node(self.head , lowerCamelCase ) def A_ ( self , lowerCamelCase ): if self.head is None: self.set_head(lowerCamelCase ) else: self.insert_after_node(self.tail , lowerCamelCase ) def A_ ( self , lowerCamelCase ): snake_case__ = Node(lowerCamelCase ) if self.head is None: self.set_head(lowerCamelCase ) else: self.set_tail(lowerCamelCase ) def A_ ( self , lowerCamelCase , lowerCamelCase ): snake_case__ = node snake_case__ = node.previous if node.get_previous() is None: snake_case__ = node_to_insert else: snake_case__ = node_to_insert snake_case__ = node_to_insert def A_ ( self , lowerCamelCase , lowerCamelCase ): snake_case__ = node snake_case__ = node.next if node.get_next() is None: snake_case__ = node_to_insert else: snake_case__ = node_to_insert snake_case__ = node_to_insert def A_ ( self , lowerCamelCase , lowerCamelCase ): snake_case__ = 1 snake_case__ = Node(lowerCamelCase ) snake_case__ = self.head while node: if current_position == position: self.insert_before_node(lowerCamelCase , lowerCamelCase ) return current_position += 1 snake_case__ = node.next self.insert_after_node(self.tail , lowerCamelCase ) def A_ ( self , lowerCamelCase ): snake_case__ = self.head while node: if node.get_data() == item: return node snake_case__ = node.get_next() raise Exception("Node not found" ) def A_ ( self , lowerCamelCase ): if (node := self.get_node(lowerCamelCase )) is not None: if node == self.head: snake_case__ = self.head.get_next() if node == self.tail: snake_case__ = self.tail.get_previous() self.remove_node_pointers(lowerCamelCase ) @staticmethod def A_ ( lowerCamelCase ): if node.get_next(): snake_case__ = node.previous if node.get_previous(): snake_case__ = node.next snake_case__ = None snake_case__ = None def A_ ( self ): return self.head is None def SCREAMING_SNAKE_CASE__ ( ): pass if __name__ == "__main__": import doctest doctest.testmod()
276
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) __magic_name__ = 299_792_458 # Symbols __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = symbols('''ct x y z''') def SCREAMING_SNAKE_CASE__ ( __lowerCAmelCase ): if velocity > c: raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!" ) elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError("Speed must be greater than or equal to 1!" ) return velocity / c def SCREAMING_SNAKE_CASE__ ( __lowerCAmelCase ): return 1 / sqrt(1 - beta(__lowerCAmelCase ) ** 2 ) def SCREAMING_SNAKE_CASE__ ( __lowerCAmelCase ): return np.array( [ [gamma(__lowerCAmelCase ), -gamma(__lowerCAmelCase ) * beta(__lowerCAmelCase ), 0, 0], [-gamma(__lowerCAmelCase ) * beta(__lowerCAmelCase ), gamma(__lowerCAmelCase ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def SCREAMING_SNAKE_CASE__ ( __lowerCAmelCase , __lowerCAmelCase = None ): # Ensure event is not empty if event is None: snake_case__ = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(__lowerCAmelCase ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: __magic_name__ = transform(29_979_245) print('''Example of four vector: ''') print(F'''ct\' = {four_vector[0]}''') print(F'''x\' = {four_vector[1]}''') print(F'''y\' = {four_vector[2]}''') print(F'''z\' = {four_vector[3]}''') # Substitute symbols with numerical values __magic_name__ = {ct: c, x: 1, y: 1, z: 1} __magic_name__ = [four_vector[i].subs(sub_dict) for i in range(4)] print(F'''\n{numerical_vector}''')
276
1
def _snake_case ( __snake_case ): if not head: return True # split the list to two parts _UpperCamelCase = head.next, head while fast and fast.next: _UpperCamelCase = fast.next.next _UpperCamelCase = slow.next _UpperCamelCase = slow.next _UpperCamelCase = None # Don't forget here! But forget still works! # reverse the second part _UpperCamelCase = None while second: _UpperCamelCase = second.next _UpperCamelCase = node _UpperCamelCase = second _UpperCamelCase = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False _UpperCamelCase = node.next _UpperCamelCase = head.next return True def _snake_case ( __snake_case ): if not head or not head.next: return True # 1. Get the midpoint (slow) _UpperCamelCase = head while fast and fast.next: _UpperCamelCase = fast.next.next, slow.next # 2. Push the second half into the stack _UpperCamelCase = [slow.val] while slow.next: _UpperCamelCase = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False _UpperCamelCase = cur.next return True def _snake_case ( __snake_case ): if not head or not head.next: return True _UpperCamelCase = {} _UpperCamelCase = 0 while head: if head.val in d: d[head.val].append(__snake_case ) else: _UpperCamelCase = [pos] _UpperCamelCase = head.next pos += 1 _UpperCamelCase = pos - 1 _UpperCamelCase = 0 for v in d.values(): if len(__snake_case ) % 2 != 0: middle += 1 else: _UpperCamelCase = 0 for i in range(0 , len(__snake_case ) ): if v[i] + v[len(__snake_case ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
717
def _snake_case ( __snake_case , __snake_case , __snake_case ): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__snake_case , n - 1 , __snake_case ) * a) % mod else: _UpperCamelCase = binary_exponentiation(__snake_case , n / 2 , __snake_case ) return (b * b) % mod # a prime number _lowerCAmelCase = 701 _lowerCAmelCase = 1_000_000_000 _lowerCAmelCase = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
71
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to properly calculate the metrics on the # validation dataset when in a distributed system, and builds off the # `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _lowerCamelCase : List[Any] = 1_6 _lowerCamelCase : List[Any] = 3_2 def _UpperCAmelCase (UpperCamelCase_ : Accelerator , UpperCamelCase_ : int = 16 ): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _lowerCAmelCase : Dict = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(UpperCamelCase_ : Union[str, Any] ): # max_length=None => use the model max length (it's actually the default) _lowerCAmelCase : Tuple = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=UpperCamelCase_ , max_length=UpperCamelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _lowerCAmelCase : Tuple = datasets.map( UpperCamelCase_ , batched=UpperCamelCase_ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _lowerCAmelCase : List[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(UpperCamelCase_ : List[str] ): # On TPU it's best to pad everything to the same length or training will be very slow. _lowerCAmelCase : Dict = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _lowerCAmelCase : List[str] = 16 elif accelerator.mixed_precision != "no": _lowerCAmelCase : Union[str, Any] = 8 else: _lowerCAmelCase : int = None return tokenizer.pad( UpperCamelCase_ , padding="""longest""" , max_length=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_tensors="""pt""" , ) # Instantiate dataloaders. _lowerCAmelCase : Dict = DataLoader( tokenized_datasets["""train"""] , shuffle=UpperCamelCase_ , collate_fn=UpperCamelCase_ , batch_size=UpperCamelCase_ ) _lowerCAmelCase : Tuple = DataLoader( tokenized_datasets["""validation"""] , shuffle=UpperCamelCase_ , collate_fn=UpperCamelCase_ , batch_size=UpperCamelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders _lowerCamelCase : Dict = mocked_dataloaders # noqa: F811 def _UpperCAmelCase (UpperCamelCase_ : List[Any] , UpperCamelCase_ : Dict ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , UpperCamelCase_ ) == "1": _lowerCAmelCase : Optional[Any] = 2 # Initialize accelerator _lowerCAmelCase : str = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _lowerCAmelCase : Optional[int] = config["""lr"""] _lowerCAmelCase : Optional[int] = int(config["""num_epochs"""] ) _lowerCAmelCase : Tuple = int(config["""seed"""] ) _lowerCAmelCase : Any = int(config["""batch_size"""] ) _lowerCAmelCase : List[Any] = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _lowerCAmelCase : List[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _lowerCAmelCase : int = batch_size // MAX_GPU_BATCH_SIZE _lowerCAmelCase : Optional[Any] = MAX_GPU_BATCH_SIZE set_seed(UpperCamelCase_ ) _lowerCAmelCase , _lowerCAmelCase : List[Any] = get_dataloaders(UpperCamelCase_ , UpperCamelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _lowerCAmelCase : str = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=UpperCamelCase_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _lowerCAmelCase : List[Any] = model.to(accelerator.device ) # Instantiate optimizer _lowerCAmelCase : int = AdamW(params=model.parameters() , lr=UpperCamelCase_ ) # Instantiate scheduler _lowerCAmelCase : Any = get_linear_schedule_with_warmup( optimizer=UpperCamelCase_ , num_warmup_steps=100 , num_training_steps=(len(UpperCamelCase_ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : str = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Now we train the model for epoch in range(UpperCamelCase_ ): model.train() for step, batch in enumerate(UpperCamelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _lowerCAmelCase : List[Any] = model(**UpperCamelCase_ ) _lowerCAmelCase : str = outputs.loss _lowerCAmelCase : int = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() _lowerCAmelCase : Union[str, Any] = 0 for step, batch in enumerate(UpperCamelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _lowerCAmelCase : str = model(**UpperCamelCase_ ) _lowerCAmelCase : str = outputs.logits.argmax(dim=-1 ) _lowerCAmelCase , _lowerCAmelCase : int = accelerator.gather((predictions, batch["""labels"""]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(UpperCamelCase_ ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples _lowerCAmelCase : Union[str, Any] = predictions[: len(eval_dataloader.dataset ) - samples_seen] _lowerCAmelCase : List[Any] = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=UpperCamelCase_ , references=UpperCamelCase_ , ) _lowerCAmelCase : Dict = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , UpperCamelCase_ ) def _UpperCAmelCase (): '''simple docstring''' _lowerCAmelCase : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=UpperCamelCase_ , default=UpperCamelCase_ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) _lowerCAmelCase : Tuple = parser.parse_args() _lowerCAmelCase : List[str] = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(UpperCamelCase_ , UpperCamelCase_ ) if __name__ == "__main__": main()
429
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : List[Any] = {name: getattr(transformers, name + "Fast") for name in SLOW_TO_FAST_CONVERTERS} def _UpperCAmelCase (UpperCamelCase_ : List[str] , UpperCamelCase_ : int , UpperCamelCase_ : Dict , UpperCamelCase_ : Union[str, Any] ): '''simple docstring''' if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(F"Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}." ) if tokenizer_name is None: _lowerCAmelCase : Union[str, Any] = TOKENIZER_CLASSES else: _lowerCAmelCase : Dict = {tokenizer_name: getattr(UpperCamelCase_ , tokenizer_name + """Fast""" )} logger.info(F"Loading tokenizer classes: {tokenizer_names}" ) for tokenizer_name in tokenizer_names: _lowerCAmelCase : int = TOKENIZER_CLASSES[tokenizer_name] _lowerCAmelCase : Optional[int] = True if checkpoint_name is None: _lowerCAmelCase : Optional[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: _lowerCAmelCase : Dict = [checkpoint_name] logger.info(F"For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}" ) for checkpoint in checkpoint_names: logger.info(F"Loading {tokenizer_class.__class__.__name__} {checkpoint}" ) # Load tokenizer _lowerCAmelCase : Optional[int] = tokenizer_class.from_pretrained(UpperCamelCase_ , force_download=UpperCamelCase_ ) # Save fast tokenizer logger.info(F"Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}" ) # For organization names we create sub-directories if "/" in checkpoint: _lowerCAmelCase , _lowerCAmelCase : int = checkpoint.split("""/""" ) _lowerCAmelCase : Tuple = os.path.join(UpperCamelCase_ , UpperCamelCase_ ) elif add_prefix: _lowerCAmelCase : List[str] = checkpoint _lowerCAmelCase : int = dump_path else: _lowerCAmelCase : Dict = None _lowerCAmelCase : str = dump_path logger.info(F"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}" ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: _lowerCAmelCase : Optional[int] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] _lowerCAmelCase : Tuple = file_path.split(UpperCamelCase_ )[-1][0] if next_char == "/": _lowerCAmelCase : Union[str, Any] = os.path.join(UpperCamelCase_ , UpperCamelCase_ ) _lowerCAmelCase : Optional[Any] = None logger.info(F"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}" ) _lowerCAmelCase : List[str] = tokenizer.save_pretrained( UpperCamelCase_ , legacy_format=UpperCamelCase_ , filename_prefix=UpperCamelCase_ ) logger.info(F"=> File names {file_names}" ) for file_name in file_names: if not file_name.endswith("""tokenizer.json""" ): os.remove(UpperCamelCase_ ) logger.info(F"=> removing {file_name}" ) if __name__ == "__main__": _lowerCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--dump_path", default=None, type=str, required=True, help="Path to output generated fast tokenizer files." ) parser.add_argument( "--tokenizer_name", default=None, type=str, help=( F'''Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will ''' "download and convert all the checkpoints from AWS." ), ) parser.add_argument( "--checkpoint_name", default=None, type=str, help="Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.", ) parser.add_argument( "--force_download", action="store_true", help="Re-download checkpoints.", ) _lowerCamelCase : Optional[Any] = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
429
1
import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def A__ ( __A ): '''simple docstring''' def wrapper(*__A , **__A ): _lowerCamelCase : int = timeit.default_timer() _lowerCamelCase : Optional[int] = func(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _lowerCamelCase : List[Any] = timeit.default_timer() - starttime return delta _lowerCamelCase : Optional[Any] = func.__name__ return wrapper def A__ ( __A , __A=100 , __A=None ): '''simple docstring''' _lowerCamelCase : str = [] _lowerCamelCase : Dict = seq_shapes or {} for i in range(_SCREAMING_SNAKE_CASE ): _lowerCamelCase : Optional[int] = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(_SCREAMING_SNAKE_CASE , _ArrayXD ): _lowerCamelCase : Optional[int] = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(_SCREAMING_SNAKE_CASE , datasets.Value ): if v.dtype == "string": _lowerCamelCase : Optional[Any] = """The small grey turtle was surprisingly fast when challenged.""" else: _lowerCamelCase : List[str] = np.random.randint(10 , size=1 ).astype(v.dtype ).item() elif isinstance(_SCREAMING_SNAKE_CASE , datasets.Sequence ): while isinstance(_SCREAMING_SNAKE_CASE , datasets.Sequence ): _lowerCamelCase : Dict = v.feature _lowerCamelCase : Dict = seq_shapes[k] _lowerCamelCase : List[Any] = np.random.rand(*_SCREAMING_SNAKE_CASE ).astype(v.dtype ) _lowerCamelCase : Tuple = data dummy_data.append((i, example) ) return dummy_data def A__ ( __A , __A , __A=100 , __A=None ): '''simple docstring''' _lowerCamelCase : str = generate_examples(_SCREAMING_SNAKE_CASE , num_examples=_SCREAMING_SNAKE_CASE , seq_shapes=_SCREAMING_SNAKE_CASE ) with ArrowWriter(features=_SCREAMING_SNAKE_CASE , path=_SCREAMING_SNAKE_CASE ) as writer: for key, record in dummy_data: _lowerCamelCase : Tuple = features.encode_example(_SCREAMING_SNAKE_CASE ) writer.write(_SCREAMING_SNAKE_CASE ) _lowerCamelCase , _lowerCamelCase : Dict = 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}.""" ) _lowerCamelCase : List[Any] = datasets.Dataset.from_file(filename=_SCREAMING_SNAKE_CASE , info=datasets.DatasetInfo(features=_SCREAMING_SNAKE_CASE ) ) return dataset
706
import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging lowerCAmelCase : int ={ "cola": 2, "mnli": 3, "mrpc": 2, "sst-2": 2, "sts-b": 1, "qqp": 2, "qnli": 2, "rte": 2, "wnli": 2, } logging.set_verbosity_info() def A__ ( __A , __A , __A , __A=None ): '''simple docstring''' # Initialise PyTorch model _lowerCamelCase : Tuple = XLNetConfig.from_json_file(__A ) _lowerCamelCase : List[Any] = finetuning_task.lower() if finetuning_task is not None else """""" if finetuning_task in GLUE_TASKS_NUM_LABELS: print(F"""Building PyTorch XLNetForSequenceClassification model from configuration: {config}""" ) _lowerCamelCase : int = finetuning_task _lowerCamelCase : Union[str, Any] = GLUE_TASKS_NUM_LABELS[finetuning_task] _lowerCamelCase : int = XLNetForSequenceClassification(__A ) elif "squad" in finetuning_task: _lowerCamelCase : Dict = finetuning_task _lowerCamelCase : Optional[Any] = XLNetForQuestionAnswering(__A ) else: _lowerCamelCase : Any = XLNetLMHeadModel(__A ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(__A , __A , __A ) # Save pytorch-model _lowerCamelCase : Optional[Any] = os.path.join(__A , __A ) _lowerCamelCase : Any = os.path.join(__A , __A ) print(F"""Save PyTorch model to {os.path.abspath(__A )}""" ) torch.save(model.state_dict() , __A ) print(F"""Save configuration file to {os.path.abspath(__A )}""" ) with open(__A , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": lowerCAmelCase : Dict =argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--xlnet_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained XLNet model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--finetuning_task", default=None, type=str, help="Name of a task on which the XLNet TensorFlow model was fine-tuned", ) lowerCAmelCase : Union[str, Any] =parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
15
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import is_flaky, require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DonutImageProcessor class a ( unittest.TestCase ): def __init__( self , _snake_case , _snake_case=7 , _snake_case=3 , _snake_case=18 , _snake_case=30 , _snake_case=4_00 , _snake_case=True , _snake_case=None , _snake_case=True , _snake_case=False , _snake_case=True , _snake_case=True , _snake_case=[0.5, 0.5, 0.5] , _snake_case=[0.5, 0.5, 0.5] , ): """simple docstring""" lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = num_channels lowerCAmelCase = image_size lowerCAmelCase = min_resolution lowerCAmelCase = max_resolution lowerCAmelCase = do_resize lowerCAmelCase = size if size is not None else {'height': 18, 'width': 20} lowerCAmelCase = do_thumbnail lowerCAmelCase = do_align_axis lowerCAmelCase = do_pad lowerCAmelCase = do_normalize lowerCAmelCase = image_mean lowerCAmelCase = image_std def UpperCamelCase__ ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class a ( _a , unittest.TestCase ): snake_case__ = DonutImageProcessor if is_vision_available() else None def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = DonutImageProcessingTester(self ) @property def UpperCamelCase__ ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCAmelCase , 'do_resize' ) ) self.assertTrue(hasattr(__lowerCAmelCase , 'size' ) ) self.assertTrue(hasattr(__lowerCAmelCase , 'do_thumbnail' ) ) self.assertTrue(hasattr(__lowerCAmelCase , 'do_align_long_axis' ) ) self.assertTrue(hasattr(__lowerCAmelCase , 'do_pad' ) ) self.assertTrue(hasattr(__lowerCAmelCase , 'do_normalize' ) ) self.assertTrue(hasattr(__lowerCAmelCase , 'image_mean' ) ) self.assertTrue(hasattr(__lowerCAmelCase , 'image_std' ) ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 20} ) lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) # Previous config had dimensions in (width, height) order lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) ) self.assertEqual(image_processor.size , {'height': 84, 'width': 42} ) def UpperCamelCase__ ( self ): """simple docstring""" pass @is_flaky() def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase = 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 = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase = 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.size['height'], self.image_processor_tester.size['width'], ) , ) @is_flaky() def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase = 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 = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase = 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.size['height'], self.image_processor_tester.size['width'], ) , ) @is_flaky() def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase = 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 = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowerCAmelCase = 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.size['height'], self.image_processor_tester.size['width'], ) , )
4
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case : List[str] = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): UpperCamelCase__ = hf_hub_download( repo_id="""nateraw/video-demo""" , filename="""archery.mp4""" , repo_type="""dataset""" ) UpperCamelCase__ = VideoClassificationPipeline(model=__lowerCAmelCase , image_processor=__lowerCAmelCase , top_k=2 ) UpperCamelCase__ = [ example_video_filepath, """https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4""", ] return video_classifier, examples def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase ): for example in examples: UpperCamelCase__ = video_classifier(__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ {"""score""": ANY(__lowerCAmelCase ), """label""": ANY(__lowerCAmelCase )}, {"""score""": ANY(__lowerCAmelCase ), """label""": ANY(__lowerCAmelCase )}, ] , ) @require_torch def _lowerCamelCase ( self ): UpperCamelCase__ = """hf-internal-testing/tiny-random-VideoMAEForVideoClassification""" UpperCamelCase__ = VideoMAEFeatureExtractor( size={"""shortest_edge""": 10} , crop_size={"""height""": 10, """width""": 10} ) UpperCamelCase__ = pipeline( """video-classification""" , model=__lowerCAmelCase , feature_extractor=__lowerCAmelCase , frame_sampling_rate=4 ) UpperCamelCase__ = hf_hub_download(repo_id="""nateraw/video-demo""" , filename="""archery.mp4""" , repo_type="""dataset""" ) UpperCamelCase__ = video_classifier(__lowerCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [{"""score""": 0.5199, """label""": """LABEL_0"""}, {"""score""": 0.4801, """label""": """LABEL_1"""}] , ) UpperCamelCase__ = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ [{"""score""": 0.5199, """label""": """LABEL_0"""}, {"""score""": 0.4801, """label""": """LABEL_1"""}], [{"""score""": 0.5199, """label""": """LABEL_0"""}, {"""score""": 0.4801, """label""": """LABEL_1"""}], ] , ) @require_tf def _lowerCamelCase ( self ): pass
619
0
"""simple docstring""" import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP _a = False try: _a = _is_package_available("""google.colab""") except ModuleNotFoundError: pass @input.register class _UpperCAmelCase: def __init__( self , __a = None , __a = []) -> Optional[int]: '''simple docstring''' _UpperCamelCase = 0 _UpperCamelCase = choices _UpperCamelCase = prompt if sys.platform == "win32": _UpperCamelCase = '''*''' else: _UpperCamelCase = '''➔ ''' def UpperCAmelCase ( self , __a , __a = "") -> Tuple: '''simple docstring''' if sys.platform != "win32": writeColor(self.choices[index] , 32 , __a) else: forceWrite(self.choices[index] , __a) def UpperCAmelCase ( self , __a) -> str: '''simple docstring''' if index == self.position: forceWrite(F''' {self.arrow_char} ''') self.write_choice(__a) else: forceWrite(F''' {self.choices[index]}''') reset_cursor() def UpperCAmelCase ( self , __a , __a = 1) -> List[str]: '''simple docstring''' _UpperCamelCase = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(__a) move_cursor(__a , direction.name) self.print_choice(self.position) @input.mark(KEYMAP['''up''']) def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' self.move_direction(Direction.UP) @input.mark(KEYMAP['''down''']) def UpperCAmelCase ( self) -> Any: '''simple docstring''' self.move_direction(Direction.DOWN) @input.mark(KEYMAP['''newline''']) def UpperCAmelCase ( self) -> Optional[Any]: '''simple docstring''' move_cursor(len(self.choices) - self.position , '''DOWN''') return self.position @input.mark(KEYMAP['''interrupt''']) def UpperCAmelCase ( self) -> str: '''simple docstring''' move_cursor(len(self.choices) - self.position , '''DOWN''') raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(__a)] for number in range(10)]) def UpperCAmelCase ( self) -> List[str]: '''simple docstring''' _UpperCamelCase = int(chr(self.current_selection)) _UpperCamelCase = index - self.position if index == self.position: return if index < len(self.choices): if self.position > index: self.move_direction(Direction.UP , -movement) elif self.position < index: self.move_direction(Direction.DOWN , __a) else: return else: return def UpperCAmelCase ( self , __a = 0) -> Optional[Any]: '''simple docstring''' if self.prompt: linebreak() forceWrite(self.prompt , '''\n''') if in_colab: forceWrite('''Please input a choice index (starting from 0), and press enter''' , '''\n''') else: forceWrite('''Please select a choice using the arrow or number keys, and selecting with enter''' , '''\n''') _UpperCamelCase = default_choice for i in range(len(self.choices)): self.print_choice(__a) forceWrite('''\n''') move_cursor(len(self.choices) - self.position , '''UP''') with cursor.hide(): while True: if in_colab: try: _UpperCamelCase = int(builtins.input()) except ValueError: _UpperCamelCase = default_choice else: _UpperCamelCase = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices) + 1): move_cursor(1 , '''UP''') clear_line() self.write_choice(__a , '''\n''') return choice
78
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) _a = { """configuration_perceiver""": ["""PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PerceiverConfig""", """PerceiverOnnxConfig"""], """tokenization_perceiver""": ["""PerceiverTokenizer"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = ["""PerceiverFeatureExtractor"""] _a = ["""PerceiverImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ """PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST""", """PerceiverForImageClassificationConvProcessing""", """PerceiverForImageClassificationFourier""", """PerceiverForImageClassificationLearned""", """PerceiverForMaskedLM""", """PerceiverForMultimodalAutoencoding""", """PerceiverForOpticalFlow""", """PerceiverForSequenceClassification""", """PerceiverLayer""", """PerceiverModel""", """PerceiverPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys _a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
78
1
from __future__ import annotations def a ( snake_case__: Tuple ): '''simple docstring''' lowercase_ = 2 lowercase_ = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCamelCase ) if n > 1: factors.append(_UpperCamelCase ) return factors if __name__ == "__main__": import doctest doctest.testmod()
97
def __lowercase ( _UpperCamelCase ) ->list[int]: """simple docstring""" lowercase : Optional[Any] = len(_UpperCamelCase ) for i in range(_UpperCamelCase ): for j in range(i + 1, _UpperCamelCase ): if numbers[j] < numbers[i]: lowercase , lowercase : Optional[int] = numbers[j], numbers[i] return numbers if __name__ == "__main__": __a = input('''Enter numbers separated by a comma:\n''').strip() __a = [int(item) for item in user_input.split(''',''')] print(exchange_sort(unsorted))
319
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[str] = { '''task_specific_params''': { '''summarization''': {'''length_penalty''': 1.0, '''max_length''': 1_2_8, '''min_length''': 1_2, '''num_beams''': 4}, '''summarization_cnn''': {'''length_penalty''': 2.0, '''max_length''': 1_4_2, '''min_length''': 5_6, '''num_beams''': 4}, '''summarization_xsum''': {'''length_penalty''': 1.0, '''max_length''': 6_2, '''min_length''': 1_1, '''num_beams''': 6}, } } __SCREAMING_SNAKE_CASE : List[Any] = { '''task_specific_params.summarization.length_penalty''': 1.0, '''task_specific_params.summarization.max_length''': 1_2_8, '''task_specific_params.summarization.min_length''': 1_2, '''task_specific_params.summarization.num_beams''': 4, '''task_specific_params.summarization_cnn.length_penalty''': 2.0, '''task_specific_params.summarization_cnn.max_length''': 1_4_2, '''task_specific_params.summarization_cnn.min_length''': 5_6, '''task_specific_params.summarization_cnn.num_beams''': 4, '''task_specific_params.summarization_xsum.length_penalty''': 1.0, '''task_specific_params.summarization_xsum.max_length''': 6_2, '''task_specific_params.summarization_xsum.min_length''': 1_1, '''task_specific_params.summarization_xsum.num_beams''': 6, } self.assertEqual(flatten_dict(_lowerCamelCase ) , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(_lowerCamelCase ) , x.transpose() ) ) __SCREAMING_SNAKE_CASE : Tuple = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(_lowerCamelCase , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[int] = np.random.randn(3 , 4 ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(_lowerCamelCase ) self.assertTrue(np.allclose(transpose(_lowerCamelCase ) , transpose(_lowerCamelCase ).numpy() ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.random.randn(3 , 4 , 5 ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(_lowerCamelCase ) self.assertTrue(np.allclose(transpose(_lowerCamelCase , axes=(1, 2, 0) ) , transpose(_lowerCamelCase , axes=(1, 2, 0) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : List[Any] = np.random.randn(3 , 4 ) __SCREAMING_SNAKE_CASE : str = tf.constant(_lowerCamelCase ) self.assertTrue(np.allclose(transpose(_lowerCamelCase ) , transpose(_lowerCamelCase ).numpy() ) ) __SCREAMING_SNAKE_CASE : List[str] = np.random.randn(3 , 4 , 5 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tf.constant(_lowerCamelCase ) self.assertTrue(np.allclose(transpose(_lowerCamelCase , axes=(1, 2, 0) ) , transpose(_lowerCamelCase , axes=(1, 2, 0) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : int = np.random.randn(3 , 4 ) __SCREAMING_SNAKE_CASE : str = jnp.array(_lowerCamelCase ) self.assertTrue(np.allclose(transpose(_lowerCamelCase ) , np.asarray(transpose(_lowerCamelCase ) ) ) ) __SCREAMING_SNAKE_CASE : Any = np.random.randn(3 , 4 , 5 ) __SCREAMING_SNAKE_CASE : List[Any] = jnp.array(_lowerCamelCase ) self.assertTrue(np.allclose(transpose(_lowerCamelCase , axes=(1, 2, 0) ) , np.asarray(transpose(_lowerCamelCase , axes=(1, 2, 0) ) ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : List[str] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(_lowerCamelCase , (4, 3) ) , np.reshape(_lowerCamelCase , (4, 3) ) ) ) __SCREAMING_SNAKE_CASE : List[Any] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(_lowerCamelCase , (1_2, 5) ) , np.reshape(_lowerCamelCase , (1_2, 5) ) ) ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = np.random.randn(3 , 4 ) __SCREAMING_SNAKE_CASE : str = torch.tensor(_lowerCamelCase ) self.assertTrue(np.allclose(reshape(_lowerCamelCase , (4, 3) ) , reshape(_lowerCamelCase , (4, 3) ).numpy() ) ) __SCREAMING_SNAKE_CASE : Dict = np.random.randn(3 , 4 , 5 ) __SCREAMING_SNAKE_CASE : Tuple = torch.tensor(_lowerCamelCase ) self.assertTrue(np.allclose(reshape(_lowerCamelCase , (1_2, 5) ) , reshape(_lowerCamelCase , (1_2, 5) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = np.random.randn(3 , 4 ) __SCREAMING_SNAKE_CASE : Optional[Any] = tf.constant(_lowerCamelCase ) self.assertTrue(np.allclose(reshape(_lowerCamelCase , (4, 3) ) , reshape(_lowerCamelCase , (4, 3) ).numpy() ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.random.randn(3 , 4 , 5 ) __SCREAMING_SNAKE_CASE : int = tf.constant(_lowerCamelCase ) self.assertTrue(np.allclose(reshape(_lowerCamelCase , (1_2, 5) ) , reshape(_lowerCamelCase , (1_2, 5) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Tuple = np.random.randn(3 , 4 ) __SCREAMING_SNAKE_CASE : Tuple = jnp.array(_lowerCamelCase ) self.assertTrue(np.allclose(reshape(_lowerCamelCase , (4, 3) ) , np.asarray(reshape(_lowerCamelCase , (4, 3) ) ) ) ) __SCREAMING_SNAKE_CASE : List[str] = np.random.randn(3 , 4 , 5 ) __SCREAMING_SNAKE_CASE : List[Any] = jnp.array(_lowerCamelCase ) self.assertTrue(np.allclose(reshape(_lowerCamelCase , (1_2, 5) ) , np.asarray(reshape(_lowerCamelCase , (1_2, 5) ) ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(_lowerCamelCase ) , np.squeeze(_lowerCamelCase ) ) ) __SCREAMING_SNAKE_CASE : Tuple = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(_lowerCamelCase , axis=2 ) , np.squeeze(_lowerCamelCase , axis=2 ) ) ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = np.random.randn(1 , 3 , 4 ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(_lowerCamelCase ) self.assertTrue(np.allclose(squeeze(_lowerCamelCase ) , squeeze(_lowerCamelCase ).numpy() ) ) __SCREAMING_SNAKE_CASE : int = np.random.randn(1 , 4 , 1 , 5 ) __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(_lowerCamelCase ) self.assertTrue(np.allclose(squeeze(_lowerCamelCase , axis=2 ) , squeeze(_lowerCamelCase , axis=2 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = np.random.randn(1 , 3 , 4 ) __SCREAMING_SNAKE_CASE : List[Any] = tf.constant(_lowerCamelCase ) self.assertTrue(np.allclose(squeeze(_lowerCamelCase ) , squeeze(_lowerCamelCase ).numpy() ) ) __SCREAMING_SNAKE_CASE : Dict = np.random.randn(1 , 4 , 1 , 5 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tf.constant(_lowerCamelCase ) self.assertTrue(np.allclose(squeeze(_lowerCamelCase , axis=2 ) , squeeze(_lowerCamelCase , axis=2 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[int] = np.random.randn(1 , 3 , 4 ) __SCREAMING_SNAKE_CASE : Optional[int] = jnp.array(_lowerCamelCase ) self.assertTrue(np.allclose(squeeze(_lowerCamelCase ) , np.asarray(squeeze(_lowerCamelCase ) ) ) ) __SCREAMING_SNAKE_CASE : Any = np.random.randn(1 , 4 , 1 , 5 ) __SCREAMING_SNAKE_CASE : List[Any] = jnp.array(_lowerCamelCase ) self.assertTrue(np.allclose(squeeze(_lowerCamelCase , axis=2 ) , np.asarray(squeeze(_lowerCamelCase , axis=2 ) ) ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(_lowerCamelCase , axis=1 ) , np.expand_dims(_lowerCamelCase , axis=1 ) ) ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = np.random.randn(3 , 4 ) __SCREAMING_SNAKE_CASE : Tuple = torch.tensor(_lowerCamelCase ) self.assertTrue(np.allclose(expand_dims(_lowerCamelCase , axis=1 ) , expand_dims(_lowerCamelCase , axis=1 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : List[str] = np.random.randn(3 , 4 ) __SCREAMING_SNAKE_CASE : str = tf.constant(_lowerCamelCase ) self.assertTrue(np.allclose(expand_dims(_lowerCamelCase , axis=1 ) , expand_dims(_lowerCamelCase , axis=1 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : List[str] = np.random.randn(3 , 4 ) __SCREAMING_SNAKE_CASE : List[Any] = jnp.array(_lowerCamelCase ) self.assertTrue(np.allclose(expand_dims(_lowerCamelCase , axis=1 ) , np.asarray(expand_dims(_lowerCamelCase , axis=1 ) ) ) )
401
"""simple docstring""" import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch _lowerCamelCase = True except ImportError: _lowerCamelCase = False try: from torch.hub import _get_torch_home _lowerCamelCase = _get_torch_home() except ImportError: _lowerCamelCase = os.path.expanduser( os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch''')) ) _lowerCamelCase = os.path.join(torch_cache_home, '''transformers''') _lowerCamelCase = '''https://cdn.huggingface.co''' _lowerCamelCase = '''https://s3.amazonaws.com/models.huggingface.co/bert''' _lowerCamelCase = '''/'''.join(str(Path(__file__).resolve()).split('''/''')[:-1]) _lowerCamelCase = os.path.join(PATH, '''config.yaml''') _lowerCamelCase = os.path.join(PATH, '''attributes.txt''') _lowerCamelCase = os.path.join(PATH, '''objects.txt''') _lowerCamelCase = os.getenv('''PYTORCH_PRETRAINED_BERT_CACHE''', default_cache_path) _lowerCamelCase = os.getenv('''PYTORCH_TRANSFORMERS_CACHE''', PYTORCH_PRETRAINED_BERT_CACHE) _lowerCamelCase = os.getenv('''TRANSFORMERS_CACHE''', PYTORCH_TRANSFORMERS_CACHE) _lowerCamelCase = '''pytorch_model.bin''' _lowerCamelCase = '''config.yaml''' def lowerCAmelCase_ ( lowercase_ : Optional[Any]=OBJECTS , lowercase_ : Optional[int]=ATTRIBUTES ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = [] with open(lowercase_ ) as f: for object in f.readlines(): vg_classes.append(object.split(''',''' )[0].lower().strip() ) __SCREAMING_SNAKE_CASE : str = [] with open(lowercase_ ) as f: for object in f.readlines(): vg_attrs.append(object.split(''',''' )[0].lower().strip() ) return vg_classes, vg_attrs def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = OrderedDict() with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : Optional[Any] = pkl.load(lowercase_ )['''model'''] for k in copy.deepcopy(list(ckp.keys() ) ): __SCREAMING_SNAKE_CASE : Dict = ckp.pop(lowercase_ ) if isinstance(lowercase_ , np.ndarray ): __SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowercase_ ) else: assert isinstance(lowercase_ , torch.tensor ), type(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = v return r class snake_case : lowerCamelCase__ = {} def __init__( self :Dict , _lowerCamelCase :dict , _lowerCamelCase :str = "root" , _lowerCamelCase :Any=0 ): __SCREAMING_SNAKE_CASE : int = name __SCREAMING_SNAKE_CASE : Tuple = level __SCREAMING_SNAKE_CASE : List[str] = {} for k, v in dictionary.items(): if v is None: raise ValueError() __SCREAMING_SNAKE_CASE : Union[str, Any] = copy.deepcopy(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = copy.deepcopy(_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE : str = Config(_lowerCamelCase , name=_lowerCamelCase , level=level + 1 ) __SCREAMING_SNAKE_CASE : Tuple = v setattr(self , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = d def __repr__( self :List[str] ): return str(list((self._pointer.keys()) ) ) def __setattr__( self :Dict , _lowerCamelCase :int , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Any = val __SCREAMING_SNAKE_CASE : List[str] = val __SCREAMING_SNAKE_CASE : Optional[Any] = key.split('''.''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = len(_lowerCamelCase ) - 1 __SCREAMING_SNAKE_CASE : int = self._pointer if len(_lowerCamelCase ) > 1: for i, l in enumerate(_lowerCamelCase ): if hasattr(self , _lowerCamelCase ) and isinstance(getattr(self , _lowerCamelCase ) , _lowerCamelCase ): setattr(getattr(self , _lowerCamelCase ) , '''.'''.join(levels[i:] ) , _lowerCamelCase ) if l == last_level: __SCREAMING_SNAKE_CASE : Optional[Any] = val else: __SCREAMING_SNAKE_CASE : Union[str, Any] = pointer[l] def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return self._pointer def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Union[str, Any] ): with open(f'''{file_name}''' , '''w''' ) as stream: dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :List[str] ): with open(f'''{file_name}''' , '''w''' ) as stream: json.dump(_lowerCamelCase , _lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Optional[int] ): with open(_lowerCamelCase ) as stream: __SCREAMING_SNAKE_CASE : Dict = load(_lowerCamelCase , Loader=_lowerCamelCase ) return data def __str__( self :int ): __SCREAMING_SNAKE_CASE : Dict = ''' ''' if self._name != "root": __SCREAMING_SNAKE_CASE : int = f'''{t * (self._level-1)}{self._name}:\n''' else: __SCREAMING_SNAKE_CASE : Any = '''''' __SCREAMING_SNAKE_CASE : Union[str, Any] = self._level for i, (k, v) in enumerate(self._pointer.items() ): if isinstance(_lowerCamelCase , _lowerCamelCase ): r += f'''{t * (self._level)}{v}\n''' self._level += 1 else: r += f'''{t * (self._level)}{k}: {v} ({type(_lowerCamelCase ).__name__})\n''' __SCREAMING_SNAKE_CASE : List[Any] = level return r[:-1] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :int , _lowerCamelCase :str , **_lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = cls.get_config_dict(_lowerCamelCase , **_lowerCamelCase ) return cls(_lowerCamelCase ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Optional[Any] , _lowerCamelCase :str , **_lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : List[Any] = kwargs.pop('''cache_dir''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = kwargs.pop('''force_download''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = kwargs.pop('''resume_download''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = kwargs.pop('''proxies''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = kwargs.pop('''local_files_only''' , _lowerCamelCase ) if os.path.isdir(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : str = os.path.join(_lowerCamelCase , _lowerCamelCase ) elif os.path.isfile(_lowerCamelCase ) or is_remote_url(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Tuple = pretrained_model_name_or_path else: __SCREAMING_SNAKE_CASE : str = hf_bucket_url(_lowerCamelCase , filename=_lowerCamelCase , use_cdn=_lowerCamelCase ) try: # Load from URL or cache if already cached __SCREAMING_SNAKE_CASE : Optional[Any] = cached_path( _lowerCamelCase , cache_dir=_lowerCamelCase , force_download=_lowerCamelCase , proxies=_lowerCamelCase , resume_download=_lowerCamelCase , local_files_only=_lowerCamelCase , ) # Load config dict if resolved_config_file is None: raise EnvironmentError __SCREAMING_SNAKE_CASE : Optional[int] = Config.load_yaml(_lowerCamelCase ) except EnvironmentError: __SCREAMING_SNAKE_CASE : Optional[Any] = '''Can\'t load config for''' raise EnvironmentError(_lowerCamelCase ) if resolved_config_file == config_file: print('''loading configuration file from path''' ) else: print('''loading configuration file cache''' ) return Config.load_yaml(_lowerCamelCase ), kwargs def lowerCAmelCase_ ( lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load('''dump.pt''' , map_location=in_tensor.device ) __SCREAMING_SNAKE_CASE : List[str] = in_tensor.numpy() __SCREAMING_SNAKE_CASE : List[str] = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(lowercase_ , lowercase_ , rtol=0.01 , atol=0.1 ), ( F'''{sum([1 for x in np.isclose(lowercase_ , lowercase_ , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %''' " element-wise mismatch" ) raise Exception('''tensors are all good''' ) # Hugging face functions below def lowerCAmelCase_ ( lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = urlparse(lowercase_ ) return parsed.scheme in ("http", "https") def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : str , lowercase_ : Optional[Any]=True ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX __SCREAMING_SNAKE_CASE : Any = '''/''' not in model_id if legacy_format: return F'''{endpoint}/{model_id}-{filename}''' else: return F'''{endpoint}/{model_id}/{filename}''' def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str]=None , lowercase_ : int=0 , lowercase_ : Union[str, Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = '''python/{}'''.format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(lowercase_ , lowercase_ ): ua += "; " + "; ".join('''{}/{}'''.format(lowercase_ , lowercase_ ) for k, v in user_agent.items() ) elif isinstance(lowercase_ , lowercase_ ): ua += "; " + user_agent __SCREAMING_SNAKE_CASE : int = {'''user-agent''': ua} if resume_size > 0: __SCREAMING_SNAKE_CASE : Any = '''bytes=%d-''' % (resume_size,) __SCREAMING_SNAKE_CASE : Any = requests.get(lowercase_ , stream=lowercase_ , proxies=lowercase_ , headers=lowercase_ ) if response.status_code == 416: # Range not satisfiable return __SCREAMING_SNAKE_CASE : int = response.headers.get('''Content-Length''' ) __SCREAMING_SNAKE_CASE : int = resume_size + int(lowercase_ ) if content_length is not None else None __SCREAMING_SNAKE_CASE : str = tqdm( unit='''B''' , unit_scale=lowercase_ , total=lowercase_ , initial=lowercase_ , desc='''Downloading''' , ) for chunk in response.iter_content(chunk_size=1024 ): if chunk: # filter out keep-alive new chunks progress.update(len(lowercase_ ) ) temp_file.write(lowercase_ ) progress.close() def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : int=None , lowercase_ : str=False , lowercase_ : Union[str, Any]=None , lowercase_ : List[Any]=10 , lowercase_ : Optional[Any]=False , lowercase_ : Tuple=None , lowercase_ : int=False , ): '''simple docstring''' if cache_dir is None: __SCREAMING_SNAKE_CASE : Tuple = TRANSFORMERS_CACHE if isinstance(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) os.makedirs(lowercase_ , exist_ok=lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = None if not local_files_only: try: __SCREAMING_SNAKE_CASE : Tuple = requests.head(lowercase_ , allow_redirects=lowercase_ , proxies=lowercase_ , timeout=lowercase_ ) if response.status_code == 200: __SCREAMING_SNAKE_CASE : Union[str, Any] = response.headers.get('''ETag''' ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass __SCREAMING_SNAKE_CASE : Optional[Any] = url_to_filename(lowercase_ , lowercase_ ) # get cache path to put the file __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(lowercase_ , lowercase_ ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(lowercase_ ): return cache_path else: __SCREAMING_SNAKE_CASE : int = [ file for file in fnmatch.filter(os.listdir(lowercase_ ) , filename + '''.*''' ) if not file.endswith('''.json''' ) and not file.endswith('''.lock''' ) ] if len(lowercase_ ) > 0: return os.path.join(lowercase_ , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( '''Cannot find the requested files in the cached path and outgoing traffic has been''' ''' disabled. To enable model look-ups and downloads online, set \'local_files_only\'''' ''' to False.''' ) return None # From now on, etag is not None. if os.path.exists(lowercase_ ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. __SCREAMING_SNAKE_CASE : str = cache_path + '''.lock''' with FileLock(lowercase_ ): # If the download just completed while the lock was activated. if os.path.exists(lowercase_ ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: __SCREAMING_SNAKE_CASE : Any = cache_path + '''.incomplete''' @contextmanager def _resumable_file_manager(): with open(lowercase_ , '''a+b''' ) as f: yield f __SCREAMING_SNAKE_CASE : Any = _resumable_file_manager if os.path.exists(lowercase_ ): __SCREAMING_SNAKE_CASE : Optional[int] = os.stat(lowercase_ ).st_size else: __SCREAMING_SNAKE_CASE : Dict = 0 else: __SCREAMING_SNAKE_CASE : Optional[int] = partial(tempfile.NamedTemporaryFile , dir=lowercase_ , delete=lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( '''%s not found in cache or force_download set to True, downloading to %s''' , lowercase_ , temp_file.name , ) http_get( lowercase_ , lowercase_ , proxies=lowercase_ , resume_size=lowercase_ , user_agent=lowercase_ , ) os.replace(temp_file.name , lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = {'''url''': url, '''etag''': etag} __SCREAMING_SNAKE_CASE : int = cache_path + '''.json''' with open(lowercase_ , '''w''' ) as meta_file: json.dump(lowercase_ , lowercase_ ) return cache_path def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[Any]=None ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = url.encode('''utf-8''' ) __SCREAMING_SNAKE_CASE : Dict = shaaaa(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = url_hash.hexdigest() if etag: __SCREAMING_SNAKE_CASE : Tuple = etag.encode('''utf-8''' ) __SCREAMING_SNAKE_CASE : str = shaaaa(lowercase_ ) filename += "." + etag_hash.hexdigest() if url.endswith('''.h5''' ): filename += ".h5" return filename def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : List[str]=None , lowercase_ : str=False , lowercase_ : List[str]=None , lowercase_ : Any=False , lowercase_ : str=None , lowercase_ : int=False , lowercase_ : Any=False , lowercase_ : Union[str, Any]=False , ): '''simple docstring''' if cache_dir is None: __SCREAMING_SNAKE_CASE : List[str] = TRANSFORMERS_CACHE if isinstance(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) if isinstance(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) if is_remote_url(lowercase_ ): # URL, so get it from the cache (downloading if necessary) __SCREAMING_SNAKE_CASE : Any = get_from_cache( lowercase_ , cache_dir=lowercase_ , force_download=lowercase_ , proxies=lowercase_ , resume_download=lowercase_ , user_agent=lowercase_ , local_files_only=lowercase_ , ) elif os.path.exists(lowercase_ ): # File, and it exists. __SCREAMING_SNAKE_CASE : List[Any] = url_or_filename elif urlparse(lowercase_ ).scheme == "": # File, but it doesn't exist. raise EnvironmentError('''file {} not found'''.format(lowercase_ ) ) else: # Something unknown raise ValueError('''unable to parse {} as a URL or as a local path'''.format(lowercase_ ) ) if extract_compressed_file: if not is_zipfile(lowercase_ ) and not tarfile.is_tarfile(lowercase_ ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = os.path.split(lowercase_ ) __SCREAMING_SNAKE_CASE : str = output_file.replace('''.''' , '''-''' ) + '''-extracted''' __SCREAMING_SNAKE_CASE : int = os.path.join(lowercase_ , lowercase_ ) if os.path.isdir(lowercase_ ) and os.listdir(lowercase_ ) and not force_extract: return output_path_extracted # Prevent parallel extractions __SCREAMING_SNAKE_CASE : Union[str, Any] = output_path + '''.lock''' with FileLock(lowercase_ ): shutil.rmtree(lowercase_ , ignore_errors=lowercase_ ) os.makedirs(lowercase_ ) if is_zipfile(lowercase_ ): with ZipFile(lowercase_ , '''r''' ) as zip_file: zip_file.extractall(lowercase_ ) zip_file.close() elif tarfile.is_tarfile(lowercase_ ): __SCREAMING_SNAKE_CASE : int = tarfile.open(lowercase_ ) tar_file.extractall(lowercase_ ) tar_file.close() else: raise EnvironmentError('''Archive format of {} could not be identified'''.format(lowercase_ ) ) return output_path_extracted return output_path def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : str="," ): '''simple docstring''' assert isinstance(lowercase_ , lowercase_ ) if os.path.isfile(lowercase_ ): with open(lowercase_ ) as f: __SCREAMING_SNAKE_CASE : Any = eval(f.read() ) else: __SCREAMING_SNAKE_CASE : Optional[int] = requests.get(lowercase_ ) try: __SCREAMING_SNAKE_CASE : Union[str, Any] = requests.json() except Exception: __SCREAMING_SNAKE_CASE : List[Any] = req.content.decode() assert data is not None, "could not connect" try: __SCREAMING_SNAKE_CASE : List[Any] = eval(lowercase_ ) except Exception: __SCREAMING_SNAKE_CASE : List[str] = data.split('''\n''' ) req.close() return data def lowerCAmelCase_ ( lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = requests.get(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.array(Image.open(BytesIO(response.content ) ) ) return img def lowerCAmelCase_ ( lowercase_ : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = url.split('''/''' )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(lowercase_ ) with open(lowercase_ , '''rb''' ) as stream: __SCREAMING_SNAKE_CASE : List[Any] = pkl.load(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = weights.pop('''model''' ) __SCREAMING_SNAKE_CASE : Dict = {} for k, v in model.items(): __SCREAMING_SNAKE_CASE : List[str] = torch.from_numpy(lowercase_ ) if "running_var" in k: __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = k.replace('''running_var''' , '''num_batches_tracked''' ) __SCREAMING_SNAKE_CASE : Optional[int] = zero return new def lowerCAmelCase_ ( ): '''simple docstring''' print(F'''{os.path.abspath(os.path.join(lowercase_ , os.pardir ) )}/demo.ipynb''' ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : int="RGB" ): '''simple docstring''' assert isinstance(lowercase_ , lowercase_ ) if os.path.isfile(lowercase_ ): __SCREAMING_SNAKE_CASE : List[Any] = cva.imread(lowercase_ ) else: __SCREAMING_SNAKE_CASE : Dict = get_image_from_url(lowercase_ ) assert img is not None, F'''could not connect to: {im}''' __SCREAMING_SNAKE_CASE : Dict = cva.cvtColor(lowercase_ , cva.COLOR_BGR2RGB ) if input_format == "RGB": __SCREAMING_SNAKE_CASE : List[Any] = img[:, :, ::-1] return img def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Tuple=1 ): '''simple docstring''' return (images[i : i + batch] for i in range(0 , len(lowercase_ ) , lowercase_ ))
401
1
"""simple docstring""" import pytest import datasets # Import fixture modules as plugins _snake_case = ['''tests.fixtures.files''', '''tests.fixtures.hub''', '''tests.fixtures.fsspec'''] def __snake_case ( SCREAMING_SNAKE_CASE: Optional[Any] , SCREAMING_SNAKE_CASE: Optional[int] ): """simple docstring""" for item in items: if any(marker in item.keywords for marker in ['integration', 'unit'] ): continue item.add_marker(pytest.mark.unit ) def __snake_case ( SCREAMING_SNAKE_CASE: Optional[Any] ): """simple docstring""" config.addinivalue_line('markers' , 'torchaudio_latest: mark test to run with torchaudio>=0.12' ) @pytest.fixture(autouse=lowercase__ ) def __snake_case ( SCREAMING_SNAKE_CASE: Tuple , SCREAMING_SNAKE_CASE: int ): """simple docstring""" _lowerCAmelCase = tmp_path_factory.getbasetemp() / 'cache' _lowerCAmelCase = test_hf_cache_home / 'datasets' _lowerCAmelCase = test_hf_cache_home / 'metrics' _lowerCAmelCase = test_hf_cache_home / 'modules' monkeypatch.setattr('datasets.config.HF_DATASETS_CACHE' , str(lowercase__ ) ) monkeypatch.setattr('datasets.config.HF_METRICS_CACHE' , str(lowercase__ ) ) monkeypatch.setattr('datasets.config.HF_MODULES_CACHE' , str(lowercase__ ) ) _lowerCAmelCase = test_hf_datasets_cache / 'downloads' monkeypatch.setattr('datasets.config.DOWNLOADED_DATASETS_PATH' , str(lowercase__ ) ) _lowerCAmelCase = test_hf_datasets_cache / 'downloads' / 'extracted' monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(lowercase__ ) ) @pytest.fixture(autouse=lowercase__ , scope='session' ) def __snake_case ( ): """simple docstring""" datasets.disable_progress_bar() @pytest.fixture(autouse=lowercase__ ) def __snake_case ( SCREAMING_SNAKE_CASE: Optional[int] ): """simple docstring""" monkeypatch.setattr('datasets.config.HF_UPDATE_DOWNLOAD_COUNTS' , lowercase__ ) @pytest.fixture def __snake_case ( SCREAMING_SNAKE_CASE: Any ): """simple docstring""" monkeypatch.setattr('sqlalchemy.util.deprecations.SILENCE_UBER_WARNING' , lowercase__ )
580
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def A_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def A_ ( self ): torch.manual_seed(0 ) _lowerCamelCase : Union[str, Any] = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def A_ ( self ): torch.manual_seed(0 ) _lowerCamelCase : Dict = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=10 , ) return model @property def A_ ( self ): torch.manual_seed(0 ) _lowerCamelCase : List[str] = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) _lowerCamelCase : int = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def A_ ( self ): _lowerCamelCase : str = 'cpu' # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : Optional[int] = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) _lowerCamelCase : List[str] = DDPMScheduler() _lowerCamelCase : List[Any] = AudioDiffusionPipeline(vqvae=lowercase , unet=self.dummy_unet , mel=lowercase , scheduler=lowercase ) _lowerCamelCase : List[Any] = pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) _lowerCamelCase : Union[str, Any] = torch.Generator(device=lowercase ).manual_seed(42 ) _lowerCamelCase : Union[str, Any] = pipe(generator=lowercase , steps=4 ) _lowerCamelCase : Optional[Any] = output.audios[0] _lowerCamelCase : int = output.images[0] _lowerCamelCase : Dict = torch.Generator(device=lowercase ).manual_seed(42 ) _lowerCamelCase : Dict = pipe(generator=lowercase , steps=4 , return_dict=lowercase ) _lowerCamelCase : List[str] = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) _lowerCamelCase : Optional[Any] = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] _lowerCamelCase : Dict = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:10] _lowerCamelCase : List[str] = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 _lowerCamelCase : List[Any] = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) _lowerCamelCase : Dict = DDIMScheduler() _lowerCamelCase : Tuple = self.dummy_vqvae_and_unet _lowerCamelCase : List[str] = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=lowercase , scheduler=lowercase ) _lowerCamelCase : Tuple = pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) np.random.seed(0 ) _lowerCamelCase : Any = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) _lowerCamelCase : Optional[int] = torch.Generator(device=lowercase ).manual_seed(42 ) _lowerCamelCase : Dict = pipe(raw_audio=lowercase , generator=lowercase , start_step=5 , steps=10 ) _lowerCamelCase : str = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) _lowerCamelCase : Dict = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] _lowerCamelCase : Union[str, Any] = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 _lowerCamelCase : Dict = self.dummy_unet_condition _lowerCamelCase : Optional[int] = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=lowercase , mel=lowercase , scheduler=lowercase ) _lowerCamelCase : Dict = pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) np.random.seed(0 ) _lowerCamelCase : Optional[int] = torch.rand((1, 1, 10) ) _lowerCamelCase : Optional[Any] = pipe(generator=lowercase , encoding=lowercase ) _lowerCamelCase : Dict = output.images[0] _lowerCamelCase : Tuple = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] _lowerCamelCase : List[str] = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def A_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self ): _lowerCamelCase : Optional[Any] = torch_device _lowerCamelCase : Dict = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) _lowerCamelCase : List[str] = pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) _lowerCamelCase : int = torch.Generator(device=lowercase ).manual_seed(42 ) _lowerCamelCase : Tuple = pipe(generator=lowercase ) _lowerCamelCase : Dict = output.audios[0] _lowerCamelCase : Dict = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] _lowerCamelCase : Optional[int] = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] _lowerCamelCase : int = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
630
0
'''simple docstring''' def a ( UpperCamelCase_ : int ) -> Dict: for i in range(0 , UpperCamelCase_ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def a ( UpperCamelCase_ : Optional[int] ) -> Dict: for i in range(UpperCamelCase_ , 0 , -1 ): for _ in range(UpperCamelCase_ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def a ( UpperCamelCase_ : Optional[int] ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(UpperCamelCase_ ) # upper half reverse_floyd(UpperCamelCase_ ) # lower half if __name__ == "__main__": print(r'''| /\ | |- | |- |--| |\ /| |-''') print(r'''|/ \| |- |_ |_ |__| | \/ | |_''') SCREAMING_SNAKE_CASE__ : Optional[int] = 1 while K: SCREAMING_SNAKE_CASE__ : Any = int(input('''enter the number and , and see the magic : ''')) print() pretty_print(user_number) SCREAMING_SNAKE_CASE__ : Any = int(input('''press 0 to exit... and 1 to continue...''')) print('''Good Bye...''')
701
'''simple docstring''' # Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def a ( UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict ) -> List[str]: snake_case__ ={ 'en': 'Machine learning is great, isn\'t it?', 'ru': 'Машинное обучение - это здорово, не так ли?', 'de': 'Maschinelles Lernen ist großartig, nicht wahr?', } # BLUE scores as follows: # "pair": [fairseq, transformers] snake_case__ ={ 'wmt16-en-de-dist-12-1': [2_8.3, 2_7.5_2], 'wmt16-en-de-dist-6-1': [2_7.4, 2_7.1_1], 'wmt16-en-de-12-1': [2_6.9, 2_5.7_5], } snake_case__ =f"""{src_lang}-{tgt_lang}""" snake_case__ =f""" --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt16 - allenai license: apache-2.0 datasets: - wmt16 metrics: - bleu --- # FSMT ## Model description This is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}. For more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369). All 3 models are available: * [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1) * [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1) * [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = \"allenai/{model_name}\" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = \"{texts[src_lang]}\" input_ids = tokenizer.encode(input, return_tensors=\"pt\") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias ## Training data Pretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369). ## Eval results Here are the BLEU scores: model | fairseq | transformers -------|---------|---------- {model_name} | {scores[model_name][0]} | {scores[model_name][1]} The score is slightly below the score reported in the paper, as the researchers don't use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs. The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=5 mkdir -p $DATA_DIR sacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` ## Data Sources - [training, etc.](http://www.statmt.org/wmt16/) - [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372) ### BibTeX entry and citation info ``` @misc{{kasai2020deep, title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}}, author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}}, year={{2020}}, eprint={{2006.10369}}, archivePrefix={{arXiv}}, primaryClass={{cs.CL}} }} ``` """ model_card_dir.mkdir(parents=UpperCamelCase_ , exist_ok=UpperCamelCase_ ) snake_case__ =os.path.join(UpperCamelCase_ , 'README.md' ) print(f"""Generating {path}""" ) with open(UpperCamelCase_ , 'w' , encoding='utf-8' ) as f: f.write(UpperCamelCase_ ) # make sure we are under the root of the project SCREAMING_SNAKE_CASE__ : List[str] = Path(__file__).resolve().parent.parent.parent SCREAMING_SNAKE_CASE__ : Any = repo_dir / '''model_cards''' for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: SCREAMING_SNAKE_CASE__ : Optional[int] = model_cards_dir / '''allenai''' / model_name write_model_card(model_card_dir, src_lang='''en''', tgt_lang='''de''', model_name=model_name)
581
0
from collections import defaultdict from math import gcd def UpperCamelCase_ ( __a = 1_500_000 ) -> int: a__ : defaultdict = defaultdict(__a ) a__ : Optional[int] = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , __a , 2 ): if gcd(__a , __a ) > 1: continue a__ : Any = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(__a , limit + 1 , __a ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(f"""{solution() = }""")
37
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer snake_case_ : Tuple = logging.get_logger(__name__) snake_case_ : str = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} snake_case_ : List[Any] = { 'vocab_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt' ), 'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt', 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli': ( 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json' ), }, } snake_case_ : Optional[int] = { 'squeezebert/squeezebert-uncased': 512, 'squeezebert/squeezebert-mnli': 512, 'squeezebert/squeezebert-mnli-headless': 512, } snake_case_ : Tuple = { 'squeezebert/squeezebert-uncased': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True}, } class lowercase__ ( snake_case_ ): '''simple docstring''' _snake_case = VOCAB_FILES_NAMES _snake_case = PRETRAINED_VOCAB_FILES_MAP _snake_case = PRETRAINED_INIT_CONFIGURATION _snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case = SqueezeBertTokenizer def __init__( self , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=True , lowerCamelCase__="[UNK]" , lowerCamelCase__="[SEP]" , lowerCamelCase__="[PAD]" , lowerCamelCase__="[CLS]" , lowerCamelCase__="[MASK]" , lowerCamelCase__=True , lowerCamelCase__=None , **lowerCamelCase__ , ): '''simple docstring''' super().__init__( lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , do_lower_case=lowerCamelCase__ , unk_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , cls_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , tokenize_chinese_chars=lowerCamelCase__ , strip_accents=lowerCamelCase__ , **lowerCamelCase__ , ) UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , lowerCamelCase__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , lowerCamelCase__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , lowerCamelCase__ ) != tokenize_chinese_chars ): UpperCamelCase = getattr(lowerCamelCase__ , normalizer_state.pop('''type''' ) ) UpperCamelCase = do_lower_case UpperCamelCase = strip_accents UpperCamelCase = tokenize_chinese_chars UpperCamelCase = normalizer_class(**lowerCamelCase__ ) UpperCamelCase = do_lower_case def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__=None ): '''simple docstring''' UpperCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ = None ): '''simple docstring''' UpperCamelCase = [self.sep_token_id] UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ = None ): '''simple docstring''' UpperCamelCase = self._tokenizer.model.save(lowerCamelCase__ , name=lowerCamelCase__ ) return tuple(lowerCamelCase__ )
212
0
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class A__ ( __UpperCAmelCase ): """simple docstring""" def __lowercase ( self) -> Tuple: '''simple docstring''' a__ : Any = tempfile.mkdtemp() a__ : Tuple = 5 # Realm tok a__ : List[Any] = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'test', 'question', 'this', 'is', 'the', 'first', 'second', 'third', 'fourth', 'fifth', 'record', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] a__ : Any = os.path.join(self.tmpdirname , 'realm_tokenizer') os.makedirs(lowercase , exist_ok=lowercase) a__ : int = os.path.join(lowercase , VOCAB_FILES_NAMES['vocab_file']) with open(self.vocab_file , 'w' , encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens])) a__ : List[str] = os.path.join(self.tmpdirname , 'realm_block_records') os.makedirs(lowercase , exist_ok=lowercase) def __lowercase ( self) -> RealmTokenizer: '''simple docstring''' return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'realm_tokenizer')) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : int = RealmConfig(num_block_records=self.num_block_records) return config def __lowercase ( self) -> Dict: '''simple docstring''' a__ : Tuple = Dataset.from_dict( { 'id': ['0', '1'], 'question': ['foo', 'bar'], 'answers': [['Foo', 'Bar'], ['Bar']], }) return dataset def __lowercase ( self) -> List[Any]: '''simple docstring''' a__ : Optional[int] = np.array( [ b'This is the first record', b'This is the second record', b'This is the third record', b'This is the fourth record', b'This is the fifth record', b'This is a longer longer longer record', ] , dtype=lowercase , ) return block_records def __lowercase ( self) -> str: '''simple docstring''' a__ : Dict = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def __lowercase ( self) -> int: '''simple docstring''' a__ : List[Any] = self.get_config() a__ : Tuple = self.get_dummy_retriever() a__ : Tuple = retriever.tokenizer a__ : str = np.array([0, 3] , dtype='long') a__ : Optional[int] = tokenizer(['Test question']).input_ids a__ : List[str] = tokenizer( ['the fourth'] , add_special_tokens=lowercase , return_token_type_ids=lowercase , return_attention_mask=lowercase , ).input_ids a__ : str = config.reader_seq_len a__ , a__ , a__ , a__ : int = retriever( lowercase , lowercase , answer_ids=lowercase , max_length=lowercase , return_tensors='np') self.assertEqual(len(lowercase) , 2) self.assertEqual(len(lowercase) , 2) self.assertEqual(len(lowercase) , 2) self.assertEqual(concat_inputs.input_ids.shape , (2, 10)) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10)) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10)) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10)) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0]) , ['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'first', 'record', '[SEP]'] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1]) , ['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'fourth', 'record', '[SEP]'] , ) def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : List[str] = self.get_config() a__ : Union[str, Any] = self.get_dummy_retriever() a__ : List[Any] = retriever.tokenizer a__ : Any = np.array([0, 3, 5] , dtype='long') a__ : Tuple = tokenizer(['Test question']).input_ids a__ : Optional[Any] = tokenizer( ['the fourth', 'longer longer'] , add_special_tokens=lowercase , return_token_type_ids=lowercase , return_attention_mask=lowercase , ).input_ids a__ : Dict = config.reader_seq_len a__ , a__ , a__ , a__ : Dict = retriever( lowercase , lowercase , answer_ids=lowercase , max_length=lowercase , return_tensors='np') self.assertEqual([False, True, True] , lowercase) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , lowercase) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , lowercase) def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : Union[str, Any] = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , 'realm_block_records')) # Test local path a__ : Optional[int] = retriever.from_pretrained(os.path.join(self.tmpdirname , 'realm_block_records')) self.assertEqual(retriever.block_records[0] , b'This is the first record') # Test mocked remote path with patch('transformers.models.realm.retrieval_realm.hf_hub_download') as mock_hf_hub_download: a__ : str = os.path.join( os.path.join(self.tmpdirname , 'realm_block_records') , _REALM_BLOCK_RECORDS_FILENAME) a__ : str = RealmRetriever.from_pretrained('google/realm-cc-news-pretrained-openqa') self.assertEqual(retriever.block_records[0] , b'This is the first record')
392
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging lowercase : Any = logging.get_logger(__name__) def A_ ( A__ , A__ ) -> List[Any]: a__ : List[str] = set() a__ : Union[str, Any] = [] def parse_line(A__ ): for line in fp: if isinstance(A__ , A__ ): a__ : str = line.decode('UTF-8' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(' ' ): # process a single warning and move it to `selected_warnings`. if len(A__ ) > 0: a__ : Dict = '\n'.join(A__ ) # Only keep the warnings specified in `targets` if any(F': {x}: ' in warning for x in targets ): selected_warnings.add(A__ ) buffer.clear() continue else: a__ : int = line.strip() buffer.append(A__ ) if from_gh: for filename in os.listdir(A__ ): a__ : List[Any] = os.path.join(A__ , A__ ) if not os.path.isdir(A__ ): # read the file if filename != "warnings.txt": continue with open(A__ ) as fp: parse_line(A__ ) else: try: with zipfile.ZipFile(A__ ) as z: for filename in z.namelist(): if not os.path.isdir(A__ ): # read the file if filename != "warnings.txt": continue with z.open(A__ ) as fp: parse_line(A__ ) except Exception: logger.warning( F'{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.' ) return selected_warnings def A_ ( A__ , A__ ) -> Dict: a__ : List[str] = set() a__ : Tuple = [os.path.join(A__ , A__ ) for p in os.listdir(A__ ) if (p.endswith('.zip' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(A__ , A__ ) ) return selected_warnings if __name__ == "__main__": def A_ ( A__ ) -> Tuple: return values.split(',' ) lowercase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") parser.add_argument( """--output_dir""", type=str, required=True, help="""Where to store the downloaded artifacts and other result files.""", ) parser.add_argument("""--token""", default=None, type=str, help="""A token that has actions:read permission.""") # optional parameters parser.add_argument( """--targets""", default="""DeprecationWarning,UserWarning,FutureWarning""", type=list_str, help="""Comma-separated list of target warning(s) which we want to extract.""", ) parser.add_argument( """--from_gh""", action="""store_true""", help="""If running from a GitHub action workflow and collecting warnings from its artifacts.""", ) lowercase : List[Any] = parser.parse_args() lowercase : Union[str, Any] = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links lowercase : Any = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, """artifacts.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("""=""" * 8_0) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts lowercase : Dict = extract_warnings(args.output_dir, args.targets) lowercase : Any = sorted(selected_warnings) with open(os.path.join(args.output_dir, """selected_warnings.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
392
1
"""simple docstring""" import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class __lowerCAmelCase : '''simple docstring''' def __init__( self , a , a=1_00 , a=13 , a=30 , a=2 , a=3 , a=True , a=True , a=32 , a=4 , a=4 , a=37 , a="gelu" , a=0.1 , a=0.1 , a=10 , a=0.02 , a=3 , a=None , a=[0, 1, 2, 3] , ): """simple docstring""" snake_case_ :Tuple = parent snake_case_ :Dict = 1_00 snake_case_ :Optional[int] = batch_size snake_case_ :str = image_size snake_case_ :Union[str, Any] = patch_size snake_case_ :Any = num_channels snake_case_ :List[Any] = is_training snake_case_ :Union[str, Any] = use_labels snake_case_ :List[Any] = hidden_size snake_case_ :int = num_hidden_layers snake_case_ :List[str] = num_attention_heads snake_case_ :Any = intermediate_size snake_case_ :List[str] = hidden_act snake_case_ :int = hidden_dropout_prob snake_case_ :Optional[int] = attention_probs_dropout_prob snake_case_ :Dict = type_sequence_label_size snake_case_ :int = initializer_range snake_case_ :Tuple = scope snake_case_ :Optional[int] = out_indices snake_case_ :Union[str, Any] = num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) snake_case_ :Optional[Any] = (image_size // patch_size) ** 2 snake_case_ :Any = num_patches + 1 def _a ( self ): """simple docstring""" snake_case_ :int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ :int = None snake_case_ :Any = None if self.use_labels: snake_case_ :str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ :Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case_ :List[str] = self.get_config() return config, pixel_values, labels, pixel_labels def _a ( self ): """simple docstring""" return BeitConfig( vocab_size=self.vocab_size , 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=_lowerCamelCase , initializer_range=self.initializer_range , out_indices=self.out_indices , ) def _a ( self , a , a , a , a ): """simple docstring""" snake_case_ :Any = BeitModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() snake_case_ :Tuple = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , a , a , a , a ): """simple docstring""" snake_case_ :str = BeitForMaskedImageModeling(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() snake_case_ :Dict = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def _a ( self , a , a , a , a ): """simple docstring""" snake_case_ :List[Any] = self.type_sequence_label_size snake_case_ :Optional[Any] = BeitForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() snake_case_ :List[Any] = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images snake_case_ :List[str] = 1 snake_case_ :Union[str, Any] = BeitForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() snake_case_ :List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ :List[str] = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self , a , a , a , a ): """simple docstring""" snake_case_ :Tuple = self.num_labels snake_case_ :Union[str, Any] = BeitForSemanticSegmentation(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() snake_case_ :List[str] = model(_lowerCamelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) snake_case_ :Optional[Any] = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _a ( self ): """simple docstring""" snake_case_ :int = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ , snake_case_ :Union[str, Any] = config_and_inputs snake_case_ :Union[str, Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase (__UpperCAmelCase ,__UpperCAmelCase ,unittest.TestCase ): '''simple docstring''' a__ = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) a__ = ( { "feature-extraction": BeitModel, "image-classification": BeitForImageClassification, "image-segmentation": BeitForSemanticSegmentation, } if is_torch_available() else {} ) a__ = False a__ = False a__ = False def _a ( self ): """simple docstring""" snake_case_ :Any = BeitModelTester(self ) snake_case_ :Union[str, Any] = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 ) def _a ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="BEiT does not use inputs_embeds" ) def _a ( self ): """simple docstring""" pass @require_torch_multi_gpu @unittest.skip(reason="BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`" ) def _a ( self ): """simple docstring""" pass def _a ( self ): """simple docstring""" snake_case_ , snake_case_ :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ :Optional[Any] = model_class(_lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ :List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear ) ) def _a ( self ): """simple docstring""" snake_case_ , snake_case_ :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ :List[Any] = model_class(_lowerCamelCase ) snake_case_ :List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ :Optional[int] = [*signature.parameters.keys()] snake_case_ :str = ["pixel_values"] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def _a ( self ): """simple docstring""" snake_case_ :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def _a ( self ): """simple docstring""" snake_case_ :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase ) def _a ( self ): """simple docstring""" snake_case_ :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) def _a ( self ): """simple docstring""" snake_case_ :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCamelCase ) def _a ( self ): """simple docstring""" if not self.model_tester.is_training: return snake_case_ , snake_case_ :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ :Tuple = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(_lowerCamelCase ), BeitForMaskedImageModeling]: continue snake_case_ :Optional[int] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() snake_case_ :int = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) snake_case_ :List[Any] = model(**_lowerCamelCase ).loss loss.backward() def _a ( self ): """simple docstring""" snake_case_ , snake_case_ :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return snake_case_ :Tuple = False snake_case_ :List[str] = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(_lowerCamelCase ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue snake_case_ :int = model_class(_lowerCamelCase ) model.gradient_checkpointing_enable() model.to(_lowerCamelCase ) model.train() snake_case_ :Optional[int] = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) snake_case_ :int = model(**_lowerCamelCase ).loss loss.backward() def _a ( self ): """simple docstring""" snake_case_ , snake_case_ :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ :Union[str, Any] = _config_zero_init(_lowerCamelCase ) for model_class in self.all_model_classes: snake_case_ :List[Any] = model_class(config=_lowerCamelCase ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @slow def _a ( self ): """simple docstring""" for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ :str = BeitModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def A ( ): """simple docstring""" snake_case_ :Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' @cached_property def _a ( self ): """simple docstring""" return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224" ) if is_vision_available() else None @slow def _a ( self ): """simple docstring""" snake_case_ :Union[str, Any] = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k" ).to(_lowerCamelCase ) snake_case_ :str = self.default_image_processor snake_case_ :str = prepare_img() snake_case_ :Dict = image_processor(images=_lowerCamelCase , return_tensors="pt" ).pixel_values.to(_lowerCamelCase ) # prepare bool_masked_pos snake_case_ :List[Any] = torch.ones((1, 1_96) , dtype=torch.bool ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): snake_case_ :str = model(pixel_values=_lowerCamelCase , bool_masked_pos=_lowerCamelCase ) snake_case_ :Any = outputs.logits # verify the logits snake_case_ :Optional[Any] = torch.Size((1, 1_96, 81_92) ) self.assertEqual(logits.shape , _lowerCamelCase ) snake_case_ :List[str] = torch.tensor( [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , _lowerCamelCase , atol=1e-2 ) ) @slow def _a ( self ): """simple docstring""" snake_case_ :List[Any] = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224" ).to(_lowerCamelCase ) snake_case_ :int = self.default_image_processor snake_case_ :List[str] = prepare_img() snake_case_ :Dict = image_processor(images=_lowerCamelCase , return_tensors="pt" ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): snake_case_ :List[str] = model(**_lowerCamelCase ) snake_case_ :str = outputs.logits # verify the logits snake_case_ :Tuple = torch.Size((1, 10_00) ) self.assertEqual(logits.shape , _lowerCamelCase ) snake_case_ :Optional[int] = torch.tensor([-1.2385, -1.0987, -1.0108] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(logits[0, :3] , _lowerCamelCase , atol=1e-4 ) ) snake_case_ :Optional[Any] = 2_81 self.assertEqual(logits.argmax(-1 ).item() , _lowerCamelCase ) @slow def _a ( self ): """simple docstring""" snake_case_ :Union[str, Any] = BeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k" ).to( _lowerCamelCase ) snake_case_ :Union[str, Any] = self.default_image_processor snake_case_ :Optional[Any] = prepare_img() snake_case_ :str = image_processor(images=_lowerCamelCase , return_tensors="pt" ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): snake_case_ :Tuple = model(**_lowerCamelCase ) snake_case_ :int = outputs.logits # verify the logits snake_case_ :str = torch.Size((1, 2_18_41) ) self.assertEqual(logits.shape , _lowerCamelCase ) snake_case_ :Optional[Any] = torch.tensor([1.6881, -0.2787, 0.5901] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(logits[0, :3] , _lowerCamelCase , atol=1e-4 ) ) snake_case_ :str = 23_96 self.assertEqual(logits.argmax(-1 ).item() , _lowerCamelCase ) @slow def _a ( self ): """simple docstring""" snake_case_ :Optional[int] = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640" ) snake_case_ :Optional[int] = model.to(_lowerCamelCase ) snake_case_ :Tuple = BeitImageProcessor(do_resize=_lowerCamelCase , size=6_40 , do_center_crop=_lowerCamelCase ) snake_case_ :Optional[Any] = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) snake_case_ :List[Any] = Image.open(ds[0]["file"] ) snake_case_ :List[Any] = image_processor(images=_lowerCamelCase , return_tensors="pt" ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): snake_case_ :Union[str, Any] = model(**_lowerCamelCase ) snake_case_ :Optional[Any] = outputs.logits # verify the logits snake_case_ :List[Any] = torch.Size((1, 1_50, 1_60, 1_60) ) self.assertEqual(logits.shape , _lowerCamelCase ) snake_case_ :Tuple = version.parse(PIL.__version__ ) < version.parse("9.0.0" ) if is_pillow_less_than_a: snake_case_ :Optional[int] = torch.tensor( [ [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]], [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]], [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]], ] , device=_lowerCamelCase , ) else: snake_case_ :Dict = torch.tensor( [ [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]], [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]], [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]], ] , device=_lowerCamelCase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _lowerCamelCase , atol=1e-4 ) ) @slow def _a ( self ): """simple docstring""" snake_case_ :Tuple = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640" ) snake_case_ :List[Any] = model.to(_lowerCamelCase ) snake_case_ :Optional[int] = BeitImageProcessor(do_resize=_lowerCamelCase , size=6_40 , do_center_crop=_lowerCamelCase ) snake_case_ :List[Any] = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) snake_case_ :List[Any] = Image.open(ds[0]["file"] ) snake_case_ :Optional[int] = image_processor(images=_lowerCamelCase , return_tensors="pt" ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): snake_case_ :str = model(**_lowerCamelCase ) snake_case_ :Optional[int] = outputs.logits.detach().cpu() snake_case_ :Optional[Any] = image_processor.post_process_semantic_segmentation(outputs=_lowerCamelCase , target_sizes=[(5_00, 3_00)] ) snake_case_ :List[str] = torch.Size((5_00, 3_00) ) self.assertEqual(segmentation[0].shape , _lowerCamelCase ) snake_case_ :int = image_processor.post_process_semantic_segmentation(outputs=_lowerCamelCase ) snake_case_ :Optional[Any] = torch.Size((1_60, 1_60) ) self.assertEqual(segmentation[0].shape , _lowerCamelCase )
584
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class __magic_name__ ( __UpperCAmelCase): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = "Speech2TextFeatureExtractor" SCREAMING_SNAKE_CASE__ : List[str] = "Speech2TextTokenizer" def __init__( self: List[str] , _lowerCamelCase: str , _lowerCamelCase: Optional[Any] ): super().__init__(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE_ = self.feature_extractor SCREAMING_SNAKE_CASE_ = False def __call__( self: List[str] , *_lowerCamelCase: Dict , **_lowerCamelCase: List[str] ): # For backward compatibility 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.''' ) SCREAMING_SNAKE_CASE_ = kwargs.pop('''raw_speech''' ) else: SCREAMING_SNAKE_CASE_ = kwargs.pop('''audio''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE_ = kwargs.pop('''sampling_rate''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE_ = kwargs.pop('''text''' , _lowerCamelCase ) if len(_lowerCamelCase ) > 0: SCREAMING_SNAKE_CASE_ = args[0] SCREAMING_SNAKE_CASE_ = 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: SCREAMING_SNAKE_CASE_ = self.feature_extractor(_lowerCamelCase , *_lowerCamelCase , sampling_rate=_lowerCamelCase , **_lowerCamelCase ) if text is not None: SCREAMING_SNAKE_CASE_ = self.tokenizer(_lowerCamelCase , **_lowerCamelCase ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE_ = encodings['''input_ids'''] return inputs def _A ( self: List[str] , *_lowerCamelCase: List[Any] , **_lowerCamelCase: Union[str, Any] ): return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase ) def _A ( self: Union[str, Any] , *_lowerCamelCase: str , **_lowerCamelCase: Optional[Any] ): return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase ) @contextmanager def _A ( self: List[Any] ): 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.''' ) SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = self.tokenizer yield SCREAMING_SNAKE_CASE_ = self.feature_extractor SCREAMING_SNAKE_CASE_ = False
234
0
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass __UpperCAmelCase = (3, 9, -1_1, 0, 7, 5, 1, -1) __UpperCAmelCase = (4, 6, 2, 0, 8, 1_0, 3, -2) @dataclass class a_: """simple docstring""" __snake_case : int __snake_case : Node | None class a_: """simple docstring""" def __init__( self : Union[str, Any] , lowerCAmelCase__ : Iterable[int]) -> None: """simple docstring""" SCREAMING_SNAKE_CASE = None for i in sorted(lowerCAmelCase__ , reverse=lowerCAmelCase__): SCREAMING_SNAKE_CASE = Node(lowerCAmelCase__ , self.head) def __iter__( self : Optional[int]) -> Iterator[int]: """simple docstring""" SCREAMING_SNAKE_CASE = self.head while node: yield node.data SCREAMING_SNAKE_CASE = node.next_node def __len__( self : Tuple) -> int: """simple docstring""" return sum(1 for _ in self) def __str__( self : int) -> str: """simple docstring""" return " -> ".join([str(lowerCAmelCase__) for node in self]) def A_ ( lowercase_ , lowercase_ ) ->SortedLinkedList: """simple docstring""" return SortedLinkedList(list(lowercase_ ) + list(lowercase_ ) ) if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
259
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. __UpperCAmelCase = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class a_( unittest.TestCase ): """simple docstring""" __snake_case : Union[str, Any] =MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __snake_case : Dict =TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: __snake_case : Optional[Any] ={config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: __snake_case : Any ={ config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def __UpperCamelCase ( self : List[Any]) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt') SCREAMING_SNAKE_CASE = text_classifier('This is great !') self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': 'LABEL_0', 'score': 0.5_04}]) SCREAMING_SNAKE_CASE = text_classifier('This is great !' , top_k=2) self.assertEqual( nested_simplify(lowerCAmelCase__) , [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}]) SCREAMING_SNAKE_CASE = text_classifier(['This is great !', 'This is bad'] , top_k=2) self.assertEqual( nested_simplify(lowerCAmelCase__) , [ [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}], [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}], ] , ) SCREAMING_SNAKE_CASE = text_classifier('This is great !' , top_k=1) self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': 'LABEL_0', 'score': 0.5_04}]) # Legacy behavior SCREAMING_SNAKE_CASE = text_classifier('This is great !' , return_all_scores=lowerCAmelCase__) self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': 'LABEL_0', 'score': 0.5_04}]) SCREAMING_SNAKE_CASE = text_classifier('This is great !' , return_all_scores=lowerCAmelCase__) self.assertEqual( nested_simplify(lowerCAmelCase__) , [[{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}]]) SCREAMING_SNAKE_CASE = text_classifier(['This is great !', 'Something else'] , return_all_scores=lowerCAmelCase__) self.assertEqual( nested_simplify(lowerCAmelCase__) , [ [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}], [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}], ] , ) SCREAMING_SNAKE_CASE = text_classifier(['This is great !', 'Something else'] , return_all_scores=lowerCAmelCase__) self.assertEqual( nested_simplify(lowerCAmelCase__) , [ {'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_0', 'score': 0.5_04}, ] , ) @require_torch def __UpperCamelCase ( self : str) -> Dict: """simple docstring""" import torch SCREAMING_SNAKE_CASE = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' , device=torch.device('cpu') , ) SCREAMING_SNAKE_CASE = text_classifier('This is great !') self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': 'LABEL_0', 'score': 0.5_04}]) @require_tf def __UpperCamelCase ( self : int) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='tf') SCREAMING_SNAKE_CASE = text_classifier('This is great !') self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': 'LABEL_0', 'score': 0.5_04}]) @slow @require_torch def __UpperCamelCase ( self : List[Any]) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE = pipeline('text-classification') SCREAMING_SNAKE_CASE = text_classifier('This is great !') self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': 'POSITIVE', 'score': 1.0}]) SCREAMING_SNAKE_CASE = text_classifier('This is bad !') self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': 'NEGATIVE', 'score': 1.0}]) SCREAMING_SNAKE_CASE = text_classifier('Birds are a type of animal') self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': 'POSITIVE', 'score': 0.9_88}]) @slow @require_tf def __UpperCamelCase ( self : Optional[Any]) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE = pipeline('text-classification' , framework='tf') SCREAMING_SNAKE_CASE = text_classifier('This is great !') self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': 'POSITIVE', 'score': 1.0}]) SCREAMING_SNAKE_CASE = text_classifier('This is bad !') self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': 'NEGATIVE', 'score': 1.0}]) SCREAMING_SNAKE_CASE = text_classifier('Birds are a type of animal') self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': 'POSITIVE', 'score': 0.9_88}]) def __UpperCamelCase ( self : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : str) -> str: """simple docstring""" SCREAMING_SNAKE_CASE = TextClassificationPipeline(model=lowerCAmelCase__ , tokenizer=lowerCAmelCase__) return text_classifier, ["HuggingFace is in", "This is another test"] def __UpperCamelCase ( self : str , lowerCAmelCase__ : int , lowerCAmelCase__ : List[Any]) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 SCREAMING_SNAKE_CASE = 'HuggingFace is in' SCREAMING_SNAKE_CASE = text_classifier(lowerCAmelCase__) self.assertEqual(nested_simplify(lowerCAmelCase__) , [{'label': ANY(lowerCAmelCase__), 'score': ANY(lowerCAmelCase__)}]) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values()) SCREAMING_SNAKE_CASE = ['HuggingFace is in ', 'Paris is in France'] SCREAMING_SNAKE_CASE = text_classifier(lowerCAmelCase__) self.assertEqual( nested_simplify(lowerCAmelCase__) , [{'label': ANY(lowerCAmelCase__), 'score': ANY(lowerCAmelCase__)}, {'label': ANY(lowerCAmelCase__), 'score': ANY(lowerCAmelCase__)}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values()) self.assertTrue(outputs[1]['label'] in model.config.idalabel.values()) # Forcing to get all results with `top_k=None` # This is NOT the legacy format SCREAMING_SNAKE_CASE = text_classifier(lowerCAmelCase__ , top_k=lowerCAmelCase__) SCREAMING_SNAKE_CASE = len(model.config.idalabel.values()) self.assertEqual( nested_simplify(lowerCAmelCase__) , [[{'label': ANY(lowerCAmelCase__), 'score': ANY(lowerCAmelCase__)}] * N, [{'label': ANY(lowerCAmelCase__), 'score': ANY(lowerCAmelCase__)}] * N] , ) SCREAMING_SNAKE_CASE = {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'} SCREAMING_SNAKE_CASE = text_classifier(lowerCAmelCase__) self.assertEqual( nested_simplify(lowerCAmelCase__) , {'label': ANY(lowerCAmelCase__), 'score': ANY(lowerCAmelCase__)} , ) self.assertTrue(outputs['label'] in model.config.idalabel.values()) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. SCREAMING_SNAKE_CASE = [['HuggingFace is in ', 'Paris is in France']] with self.assertRaises(lowerCAmelCase__): text_classifier(lowerCAmelCase__) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility SCREAMING_SNAKE_CASE = text_classifier([[['HuggingFace is in ', 'Paris is in France']]]) self.assertEqual( nested_simplify(lowerCAmelCase__) , [{'label': ANY(lowerCAmelCase__), 'score': ANY(lowerCAmelCase__)}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values())
259
1
'''simple docstring''' import string import numpy def UpperCAmelCase ( UpperCAmelCase__ : int , UpperCAmelCase__ : int): return b if a == 0 else greatest_common_divisor(b % a , UpperCAmelCase__) class __snake_case : _lowerCAmelCase = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) _lowerCAmelCase = numpy.vectorize(lambda a__: x % 36) _lowerCAmelCase = numpy.vectorize(a__) def __init__( self, A ): """simple docstring""" lowerCamelCase : Optional[int] = self.modulus(A ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key lowerCamelCase : Union[str, Any] = encrypt_key.shape[0] def UpperCAmelCase_ ( self, A ): """simple docstring""" return self.key_string.index(A ) def UpperCAmelCase_ ( self, A ): """simple docstring""" return self.key_string[round(A )] def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Dict = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: lowerCamelCase : List[str] = det % len(self.key_string ) lowerCamelCase : Optional[int] = len(self.key_string ) if greatest_common_divisor(A, len(self.key_string ) ) != 1: lowerCamelCase : Optional[int] = ( F'''determinant modular {req_l} of encryption key({det}) ''' F'''is not co prime w.r.t {req_l}.\nTry another key.''' ) raise ValueError(A ) def UpperCAmelCase_ ( self, A ): """simple docstring""" lowerCamelCase : Dict = [char for char in text.upper() if char in self.key_string] lowerCamelCase : List[Any] = chars[-1] while len(A ) % self.break_key != 0: chars.append(A ) return "".join(A ) def UpperCAmelCase_ ( self, A ): """simple docstring""" lowerCamelCase : Union[str, Any] = self.process_text(text.upper() ) lowerCamelCase : Optional[Any] = '' for i in range(0, len(A ) - self.break_key + 1, self.break_key ): lowerCamelCase : Any = text[i : i + self.break_key] lowerCamelCase : List[str] = [self.replace_letters(A ) for char in batch] lowerCamelCase : Union[str, Any] = numpy.array([vec] ).T lowerCamelCase : Optional[Any] = self.modulus(self.encrypt_key.dot(A ) ).T.tolist()[ 0 ] lowerCamelCase : Union[str, Any] = ''.join( self.replace_digits(A ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : List[Any] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: lowerCamelCase : int = det % len(self.key_string ) lowerCamelCase : List[str] = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: lowerCamelCase : str = i break lowerCamelCase : int = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(A ) ) def UpperCAmelCase_ ( self, A ): """simple docstring""" lowerCamelCase : str = self.make_decrypt_key() lowerCamelCase : Any = self.process_text(text.upper() ) lowerCamelCase : Union[str, Any] = '' for i in range(0, len(A ) - self.break_key + 1, self.break_key ): lowerCamelCase : List[Any] = text[i : i + self.break_key] lowerCamelCase : List[str] = [self.replace_letters(A ) for char in batch] lowerCamelCase : int = numpy.array([vec] ).T lowerCamelCase : Optional[Any] = self.modulus(decrypt_key.dot(A ) ).T.tolist()[0] lowerCamelCase : Optional[Any] = ''.join( self.replace_digits(A ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def UpperCAmelCase ( ): lowerCamelCase : Union[str, Any] = int(input('Enter the order of the encryption key: ')) lowerCamelCase : Tuple = [] print('Enter each row of the encryption key with space separated integers') for _ in range(UpperCAmelCase__): lowerCamelCase : Optional[int] = [int(UpperCAmelCase__) for x in input().split()] hill_matrix.append(UpperCAmelCase__) lowerCamelCase : int = HillCipher(numpy.array(UpperCAmelCase__)) print('Would you like to encrypt or decrypt some text? (1 or 2)') lowerCamelCase : Dict = input('\n1. Encrypt\n2. Decrypt\n') if option == "1": lowerCamelCase : Union[str, Any] = input('What text would you like to encrypt?: ') print('Your encrypted text is:') print(hc.encrypt(UpperCAmelCase__)) elif option == "2": lowerCamelCase : Any = input('What text would you like to decrypt?: ') print('Your decrypted text is:') print(hc.decrypt(UpperCAmelCase__)) if __name__ == "__main__": import doctest doctest.testmod() main()
320
'''simple docstring''' def UpperCAmelCase ( UpperCAmelCase__ : str , UpperCAmelCase__ : int): return [sentence[i : i + ngram_size] for i in range(len(UpperCAmelCase__) - ngram_size + 1)] if __name__ == "__main__": from doctest import testmod testmod()
320
1
"""simple docstring""" import argparse import json import subprocess def __snake_case ( SCREAMING_SNAKE_CASE: Any , SCREAMING_SNAKE_CASE: Tuple ): """simple docstring""" _lowerCAmelCase = [] _lowerCAmelCase = ( f"""curl -H \"Accept: application/vnd.github+json\" -H \"Authorization: Bearer {token}\"""" ' https://api.github.com/repos/huggingface/transformers/actions/runners' ) _lowerCAmelCase = subprocess.run(a__ , shell=a__ , stdout=subprocess.PIPE ) _lowerCAmelCase = output.stdout.decode('utf-8' ) _lowerCAmelCase = json.loads(a__ ) _lowerCAmelCase = status['runners'] for runner in runners: if runner["name"] in target_runners: if runner["status"] == "offline": offline_runners.append(a__ ) # save the result so we can report them on Slack with open('offline_runners.txt' , 'w' ) as fp: fp.write(json.dumps(a__ ) ) if len(a__ ) > 0: _lowerCAmelCase = '\n'.join([x['name'] for x in offline_runners] ) raise ValueError(f"""The following runners are offline:\n{failed}""" ) if __name__ == "__main__": def __snake_case ( SCREAMING_SNAKE_CASE: str ): """simple docstring""" return values.split(',' ) _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--target_runners''', default=None, type=list_str, required=True, help='''Comma-separated list of runners to check status.''', ) parser.add_argument( '''--token''', default=None, type=str, required=True, help='''A token that has actions:read permission.''' ) _snake_case = parser.parse_args() get_runner_status(args.target_runners, args.token)
714
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy 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 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _snake_case = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( enum.Enum ): '''simple docstring''' SCREAMING_SNAKE_CASE_: Any = 0 SCREAMING_SNAKE_CASE_: str = 1 @add_end_docstrings(UpperCAmelCase ) class _SCREAMING_SNAKE_CASE ( UpperCAmelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_: int = "generated" def __init__( self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Union[str, Any] ) -> Optional[Any]: """simple docstring""" super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def __lowerCamelCase ( self : List[str] , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Union[str, Any] , ) -> int: """simple docstring""" _lowerCAmelCase = {} if truncation is not None: _lowerCAmelCase = truncation _lowerCAmelCase = generate_kwargs _lowerCAmelCase = {} if return_tensors is not None and return_type is None: _lowerCAmelCase = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: _lowerCAmelCase = return_type if clean_up_tokenization_spaces is not None: _lowerCAmelCase = clean_up_tokenization_spaces if stop_sequence is not None: _lowerCAmelCase = self.tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ) if len(UpperCAmelCase_ ) > 1: warnings.warn( 'Stopping on a multiple token sequence is not yet supported on transformers. The first token of' ' the stop sequence will be used as the stop sequence string in the interim.' ) _lowerCAmelCase = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __lowerCamelCase ( self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> Optional[Any]: """simple docstring""" return True def __lowerCamelCase ( self : Union[str, Any] , *UpperCAmelCase_ : str , UpperCAmelCase_ : int ) -> str: """simple docstring""" _lowerCAmelCase = self.model.config.prefix if self.model.config.prefix is not None else '' if isinstance(args[0] , UpperCAmelCase_ ): if self.tokenizer.pad_token_id is None: raise ValueError('Please make sure that the tokenizer has a pad_token_id when using a batch input' ) _lowerCAmelCase = ([prefix + arg for arg in args[0]],) _lowerCAmelCase = True elif isinstance(args[0] , UpperCAmelCase_ ): _lowerCAmelCase = (prefix + args[0],) _lowerCAmelCase = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) _lowerCAmelCase = self.tokenizer(*UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Tuple ) -> str: """simple docstring""" _lowerCAmelCase = super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_ ) if ( isinstance(args[0] , UpperCAmelCase_ ) and all(isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) for el in args[0] ) and all(len(UpperCAmelCase_ ) == 1 for res in result ) ): return [res[0] for res in result] return result def __lowerCamelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase_ : Tuple ) -> Tuple: """simple docstring""" _lowerCAmelCase = self._parse_and_tokenize(UpperCAmelCase_ , truncation=UpperCAmelCase_ , **UpperCAmelCase_ ) return inputs def __lowerCamelCase ( self : Optional[Any] , UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : List[str] ) -> Any: """simple docstring""" if self.framework == "pt": _lowerCAmelCase , _lowerCAmelCase = model_inputs['input_ids'].shape elif self.framework == "tf": _lowerCAmelCase , _lowerCAmelCase = tf.shape(model_inputs['input_ids'] ).numpy() _lowerCAmelCase = generate_kwargs.get('min_length' , self.model.config.min_length ) _lowerCAmelCase = generate_kwargs.get('max_length' , self.model.config.max_length ) self.check_inputs(UpperCAmelCase_ , generate_kwargs['min_length'] , generate_kwargs['max_length'] ) _lowerCAmelCase = self.model.generate(**UpperCAmelCase_ , **UpperCAmelCase_ ) _lowerCAmelCase = output_ids.shape[0] if self.framework == "pt": _lowerCAmelCase = output_ids.reshape(UpperCAmelCase_ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": _lowerCAmelCase = tf.reshape(UpperCAmelCase_ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def __lowerCamelCase ( self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any]=ReturnType.TEXT , UpperCAmelCase_ : Optional[Any]=False ) -> str: """simple docstring""" _lowerCAmelCase = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: _lowerCAmelCase = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: _lowerCAmelCase = { F"""{self.return_name}_text""": self.tokenizer.decode( UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ , ) } records.append(UpperCAmelCase_ ) return records @add_end_docstrings(UpperCAmelCase ) class _SCREAMING_SNAKE_CASE ( UpperCAmelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] = "summary" def __call__( self : Optional[int] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Dict ) -> int: """simple docstring""" return super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_ ) def __lowerCamelCase ( self : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> bool: """simple docstring""" if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ 'a summarization task, where outputs shorter than the input are typically wanted, you might ' F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCAmelCase ) class _SCREAMING_SNAKE_CASE ( UpperCAmelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] = "translation" def __lowerCamelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> Any: """simple docstring""" if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ 'increasing your max_length manually, e.g. translator(\'...\', max_length=400)' ) return True def __lowerCamelCase ( self : Optional[Any] , *UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Dict=None ) -> Optional[int]: """simple docstring""" if getattr(self.tokenizer , '_build_translation_inputs' , UpperCAmelCase_ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase_ , return_tensors=self.framework , truncation=UpperCAmelCase_ , src_lang=UpperCAmelCase_ , tgt_lang=UpperCAmelCase_ ) else: return super()._parse_and_tokenize(*UpperCAmelCase_ , truncation=UpperCAmelCase_ ) def __lowerCamelCase ( self : Union[str, Any] , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : Optional[int] ) -> Union[str, Any]: """simple docstring""" _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = super()._sanitize_parameters(**UpperCAmelCase_ ) if src_lang is not None: _lowerCAmelCase = src_lang if tgt_lang is not None: _lowerCAmelCase = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. _lowerCAmelCase = kwargs.get('task' , self.task ) _lowerCAmelCase = task.split('_' ) if task and len(UpperCAmelCase_ ) == 4: # translation, XX, to YY _lowerCAmelCase = items[1] _lowerCAmelCase = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Optional[int] ) -> Union[str, Any]: """simple docstring""" return super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_ )
491
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__ : Dict = logging.get_logger(__name__) A__ : Tuple = { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json', 'google/bigbird-roberta-large': 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json', 'google/bigbird-base-trivia-itc': 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class _UpperCAmelCase ( A__ ): """simple docstring""" lowercase__ = """big_bird""" def __init__( self : Any, lowerCamelCase : int=50_358, lowerCamelCase : Dict=768, lowerCamelCase : int=12, lowerCamelCase : List[str]=12, lowerCamelCase : Optional[Any]=3_072, lowerCamelCase : Optional[int]="gelu_new", lowerCamelCase : Optional[int]=0.1, lowerCamelCase : str=0.1, lowerCamelCase : Tuple=4_096, lowerCamelCase : List[str]=2, lowerCamelCase : Any=0.02, lowerCamelCase : List[Any]=1E-12, lowerCamelCase : List[str]=True, lowerCamelCase : str=0, lowerCamelCase : str=1, lowerCamelCase : List[Any]=2, lowerCamelCase : int=66, lowerCamelCase : List[str]="block_sparse", lowerCamelCase : Any=True, lowerCamelCase : Tuple=False, lowerCamelCase : int=64, lowerCamelCase : Optional[int]=3, lowerCamelCase : Tuple=None, **lowerCamelCase : str, ): '''simple docstring''' super().__init__( pad_token_id=lowerCamelCase, bos_token_id=lowerCamelCase, eos_token_id=lowerCamelCase, sep_token_id=lowerCamelCase, **lowerCamelCase, ) lowercase__ = vocab_size lowercase__ = max_position_embeddings lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = initializer_range lowercase__ = type_vocab_size lowercase__ = layer_norm_eps lowercase__ = use_cache lowercase__ = rescale_embeddings lowercase__ = attention_type lowercase__ = use_bias lowercase__ = block_size lowercase__ = num_random_blocks lowercase__ = classifier_dropout class _UpperCAmelCase ( A__ ): """simple docstring""" @property def lowercase__ ( self : Dict ): '''simple docstring''' if self.task == "multiple-choice": lowercase__ = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowercase__ = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
183
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING A__ : Tuple = logging.get_logger(__name__) class _UpperCAmelCase ( A__ ): """simple docstring""" lowercase__ = """upernet""" def __init__( self : Dict, lowerCamelCase : Union[str, Any]=None, lowerCamelCase : str=512, lowerCamelCase : Optional[Any]=0.02, lowerCamelCase : Optional[Any]=[1, 2, 3, 6], lowerCamelCase : Optional[int]=True, lowerCamelCase : Tuple=0.4, lowerCamelCase : Optional[int]=384, lowerCamelCase : Optional[int]=256, lowerCamelCase : Dict=1, lowerCamelCase : str=False, lowerCamelCase : List[str]=255, **lowerCamelCase : List[Any], ): '''simple docstring''' super().__init__(**lowerCamelCase ) if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) lowercase__ = CONFIG_MAPPING['''resnet'''](out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ) elif isinstance(lowerCamelCase, lowerCamelCase ): lowercase__ = backbone_config.get('''model_type''' ) lowercase__ = CONFIG_MAPPING[backbone_model_type] lowercase__ = config_class.from_dict(lowerCamelCase ) lowercase__ = backbone_config lowercase__ = hidden_size lowercase__ = initializer_range lowercase__ = pool_scales lowercase__ = use_auxiliary_head lowercase__ = auxiliary_loss_weight lowercase__ = auxiliary_in_channels lowercase__ = auxiliary_channels lowercase__ = auxiliary_num_convs lowercase__ = auxiliary_concat_input lowercase__ = loss_ignore_index def lowercase__ ( self : str ): '''simple docstring''' lowercase__ = copy.deepcopy(self.__dict__ ) lowercase__ = self.backbone_config.to_dict() lowercase__ = self.__class__.model_type return output
183
1
from typing import TYPE_CHECKING from ...utils import _LazyModule __UpperCamelCase : str = {"processing_wav2vec2_with_lm": ["Wav2Vec2ProcessorWithLM"]} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys __UpperCamelCase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
106
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCamelCase : Any = logging.get_logger(__name__) __UpperCamelCase : Any = { "andreasmadsen/efficient_mlm_m0.40": ( "https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json" ), } class __magic_name__ ( __lowerCAmelCase): A: List[Any] = "roberta-prelayernorm" def __init__( self : Tuple , lowerCamelCase__ : List[Any]=50265 , lowerCamelCase__ : Optional[Any]=768 , lowerCamelCase__ : str=12 , lowerCamelCase__ : Union[str, Any]=12 , lowerCamelCase__ : Dict=3072 , lowerCamelCase__ : int="gelu" , lowerCamelCase__ : Tuple=0.1 , lowerCamelCase__ : Tuple=0.1 , lowerCamelCase__ : List[str]=512 , lowerCamelCase__ : int=2 , lowerCamelCase__ : Tuple=0.02 , lowerCamelCase__ : List[Any]=1E-1_2 , lowerCamelCase__ : str=1 , lowerCamelCase__ : int=0 , lowerCamelCase__ : int=2 , lowerCamelCase__ : Union[str, Any]="absolute" , lowerCamelCase__ : Optional[Any]=True , lowerCamelCase__ : Dict=None , **lowerCamelCase__ : Any , ) -> Optional[int]: '''simple docstring''' super().__init__(pad_token_id=lowerCamelCase__ , bos_token_id=lowerCamelCase__ , eos_token_id=lowerCamelCase__ , **lowerCamelCase__ ) UpperCamelCase__ : Optional[int] = vocab_size UpperCamelCase__ : Union[str, Any] = hidden_size UpperCamelCase__ : List[str] = num_hidden_layers UpperCamelCase__ : Optional[int] = num_attention_heads UpperCamelCase__ : List[str] = hidden_act UpperCamelCase__ : Optional[int] = intermediate_size UpperCamelCase__ : Optional[int] = hidden_dropout_prob UpperCamelCase__ : List[str] = attention_probs_dropout_prob UpperCamelCase__ : Optional[int] = max_position_embeddings UpperCamelCase__ : Optional[Any] = type_vocab_size UpperCamelCase__ : Union[str, Any] = initializer_range UpperCamelCase__ : Dict = layer_norm_eps UpperCamelCase__ : Union[str, Any] = position_embedding_type UpperCamelCase__ : Optional[int] = use_cache UpperCamelCase__ : int = classifier_dropout class __magic_name__ ( __lowerCAmelCase): @property def UpperCAmelCase__ ( self : int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": UpperCamelCase__ : Dict = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: UpperCamelCase__ : Any = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
106
1
from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class SCREAMING_SNAKE_CASE_ : '''simple docstring''' lowercase : int lowercase : Node | None = None lowercase : Node | None = None def A__ ( ) -> Node | None: A : Optional[Any] =Node(1 ) A : Tuple =Node(2 ) A : Dict =Node(3 ) A : List[str] =Node(4 ) A : Optional[int] =Node(5 ) return tree def A__ ( lowercase: Node | None ) -> list[int]: return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def A__ ( lowercase: Node | None ) -> list[int]: return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def A__ ( lowercase: Node | None ) -> list[int]: return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def A__ ( lowercase: Node | None ) -> int: return (max(height(root.left ), height(root.right ) ) + 1) if root else 0 def A__ ( lowercase: Node | None ) -> Sequence[Node | None]: A : list[Any] =[] if root is None: return output A : str =deque([root] ) while process_queue: A : Tuple =process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def A__ ( lowercase: Node | None, lowercase: int ) -> Sequence[Node | None]: A : list[Any] =[] def populate_output(lowercase: Node | None, lowercase: int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left, level - 1 ) populate_output(root.right, level - 1 ) populate_output(lowercase, lowercase ) return output def A__ ( lowercase: Node | None, lowercase: int ) -> Sequence[Node | None]: A : list[Any] =[] def populate_output(lowercase: Node | None, lowercase: int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right, level - 1 ) populate_output(root.left, level - 1 ) populate_output(lowercase, lowercase ) return output def A__ ( lowercase: Node | None ) -> Sequence[Node | None] | list[Any]: if root is None: return [] A : list[Sequence[Node | None]] =[] A : Dict =0 A : Dict =height(lowercase ) for h in range(1, height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(lowercase, lowercase ) ) A : Tuple =1 else: output.append(get_nodes_from_right_to_left(lowercase, lowercase ) ) A : List[str] =0 return output def A__ ( ) -> None: # Main function for testing. A : Any =make_tree() print(F'In-order Traversal: {inorder(lowercase )}' ) print(F'Pre-order Traversal: {preorder(lowercase )}' ) print(F'Post-order Traversal: {postorder(lowercase )}', '\n' ) print(F'Height of Tree: {height(lowercase )}', '\n' ) print('Complete Level Order Traversal: ' ) print(level_order(lowercase ), '\n' ) print('Level-wise order Traversal: ' ) for level in range(1, height(lowercase ) + 1 ): print(F'Level {level}:', get_nodes_from_left_to_right(lowercase, level=lowercase ) ) print('\nZigZag order Traversal: ' ) print(zigzag(lowercase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
305
from __future__ import annotations def A__ ( lowercase: int | str ) -> bool: A : int =str(lowercase ) return n == n[::-1] def A__ ( lowercase: int = 1_000_000 ) -> Any: A : str =0 for i in range(1, lowercase ): if is_palindrome(lowercase ) and is_palindrome(bin(lowercase ).split('b' )[1] ): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
305
1
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _snake_case ( _a , unittest.TestCase ): _A : int = ShapEPipeline _A : str = ['''prompt'''] _A : List[Any] = ['''prompt'''] _A : Union[str, Any] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] _A : Any = False @property def __UpperCamelCase ( self : Optional[Any] ): return 32 @property def __UpperCamelCase ( self : List[str] ): return 32 @property def __UpperCamelCase ( self : Dict ): return self.time_input_dim * 4 @property def __UpperCamelCase ( self : List[Any] ): return 8 @property def __UpperCamelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE:Any = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def __UpperCamelCase ( self : Optional[int] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE:Any = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=self.text_embedder_hidden_size ,projection_dim=self.text_embedder_hidden_size ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_000 ,) return CLIPTextModelWithProjection(SCREAMING_SNAKE_CASE__ ) @property def __UpperCamelCase ( self : str ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE:Union[str, Any] = { "num_attention_heads": 2, "attention_head_dim": 16, "embedding_dim": self.time_input_dim, "num_embeddings": 32, "embedding_proj_dim": self.text_embedder_hidden_size, "time_embed_dim": self.time_embed_dim, "num_layers": 1, "clip_embed_dim": self.time_input_dim * 2, "additional_embeddings": 0, "time_embed_act_fn": "gelu", "norm_in_type": "layer", "encoder_hid_proj_type": None, "added_emb_type": None, } SCREAMING_SNAKE_CASE:Optional[int] = PriorTransformer(**SCREAMING_SNAKE_CASE__ ) return model @property def __UpperCamelCase ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE:int = { "param_shapes": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), "d_latent": self.time_input_dim, "d_hidden": self.renderer_dim, "n_output": 12, "background": ( 0.1, 0.1, 0.1, ), } SCREAMING_SNAKE_CASE:Any = ShapERenderer(**SCREAMING_SNAKE_CASE__ ) return model def __UpperCamelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE:List[Any] = self.dummy_prior SCREAMING_SNAKE_CASE:List[Any] = self.dummy_text_encoder SCREAMING_SNAKE_CASE:List[Any] = self.dummy_tokenizer SCREAMING_SNAKE_CASE:int = self.dummy_renderer SCREAMING_SNAKE_CASE:Optional[Any] = HeunDiscreteScheduler( beta_schedule="exp" ,num_train_timesteps=1_024 ,prediction_type="sample" ,use_karras_sigmas=SCREAMING_SNAKE_CASE__ ,clip_sample=SCREAMING_SNAKE_CASE__ ,clip_sample_range=1.0 ,) SCREAMING_SNAKE_CASE:Optional[Any] = { "prior": prior, "text_encoder": text_encoder, "tokenizer": tokenizer, "renderer": renderer, "scheduler": scheduler, } return components def __UpperCamelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : List[str]=0 ): if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): SCREAMING_SNAKE_CASE:int = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE:Dict = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Dict = { "prompt": "horse", "generator": generator, "num_inference_steps": 1, "frame_size": 32, "output_type": "np", } return inputs def __UpperCamelCase ( self : str ): SCREAMING_SNAKE_CASE:Optional[int] = "cpu" SCREAMING_SNAKE_CASE:Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE:Optional[Any] = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:List[Any] = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Optional[Any] = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE:Union[str, Any] = output.images[0] SCREAMING_SNAKE_CASE:Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) SCREAMING_SNAKE_CASE:Any = np.array( [ 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCamelCase ( self : Tuple ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __UpperCamelCase ( self : Any ): SCREAMING_SNAKE_CASE:List[str] = torch_device == "cpu" SCREAMING_SNAKE_CASE:Tuple = True self._test_inference_batch_single_identical( batch_size=2 ,test_max_difference=SCREAMING_SNAKE_CASE__ ,relax_max_difference=SCREAMING_SNAKE_CASE__ ,) def __UpperCamelCase ( self : Dict ): SCREAMING_SNAKE_CASE:int = self.get_dummy_components() SCREAMING_SNAKE_CASE:List[Any] = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Dict = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:int = 1 SCREAMING_SNAKE_CASE:Dict = 2 SCREAMING_SNAKE_CASE:Any = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) for key in inputs.keys(): if key in self.batch_params: SCREAMING_SNAKE_CASE:List[str] = batch_size * [inputs[key]] SCREAMING_SNAKE_CASE:Optional[Any] = pipe(**SCREAMING_SNAKE_CASE__ ,num_images_per_prompt=SCREAMING_SNAKE_CASE__ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def __UpperCamelCase ( self : str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self : int ): SCREAMING_SNAKE_CASE:Union[str, Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/shap_e/test_shap_e_np_out.npy" ) SCREAMING_SNAKE_CASE:Optional[int] = ShapEPipeline.from_pretrained("openai/shap-e" ) SCREAMING_SNAKE_CASE:int = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Tuple = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(0 ) SCREAMING_SNAKE_CASE:Any = pipe( "a shark" ,generator=SCREAMING_SNAKE_CASE__ ,guidance_scale=15.0 ,num_inference_steps=64 ,frame_size=64 ,output_type="np" ,).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ )
708
'''simple docstring''' import warnings from functools import wraps from typing import Callable def A_ ( snake_case ): @wraps(snake_case ) def _inner_fn(*snake_case , **snake_case ): warnings.warn( (F'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , snake_case , ) return fn(*snake_case , **snake_case ) return _inner_fn
465
0
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class UpperCAmelCase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): '''simple docstring''' @register_to_config def __init__( self , lowercase__ = 768 , ) -> List[Any]: super().__init__() SCREAMING_SNAKE_CASE : List[str] = nn.Parameter(torch.zeros(1 , lowercase__ ) ) SCREAMING_SNAKE_CASE : Any = nn.Parameter(torch.ones(1 , lowercase__ ) ) def _UpperCamelCase ( self , lowercase__ = None , lowercase__ = None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(lowercase__ ).to(lowercase__ ) ) SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.std.to(lowercase__ ).to(lowercase__ ) ) return self def _UpperCamelCase ( self , lowercase__ ) -> Optional[int]: SCREAMING_SNAKE_CASE : List[str] = (embeds - self.mean) * 1.0 / self.std return embeds def _UpperCamelCase ( self , lowercase__ ) -> List[str]: SCREAMING_SNAKE_CASE : List[str] = (embeds * self.std) + self.mean return embeds
251
'''simple docstring''' def __lowerCAmelCase ( a_ = 1 , a_ = 1000 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : Optional[int] = 0 for divide_by_number in range(a_ , digit + 1 ): SCREAMING_SNAKE_CASE : list[int] = [] SCREAMING_SNAKE_CASE : Any = numerator for _ in range(1 , digit + 1 ): if now_divide in has_been_divided: if longest_list_length < len(a_ ): SCREAMING_SNAKE_CASE : List[Any] = len(a_ ) SCREAMING_SNAKE_CASE : Optional[int] = divide_by_number else: has_been_divided.append(a_ ) SCREAMING_SNAKE_CASE : Optional[int] = now_divide * 10 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
251
1
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class __lowerCamelCase ( pl.LightningModule ): """simple docstring""" def __init__( self , UpperCAmelCase ) -> Optional[int]: '''simple docstring''' super().__init__() lowercase_ = model lowercase_ = 2 lowercase_ = nn.Linear(self.model.config.hidden_size , self.num_labels ) def A__ ( self ) -> List[Any]: '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: str , __lowerCamelCase: str , __lowerCamelCase: str ): '''simple docstring''' lowercase_ = LongformerModel.from_pretrained(__lowerCamelCase ) lowercase_ = LightningModel(__lowerCamelCase ) lowercase_ = torch.load(__lowerCamelCase , map_location=torch.device("cpu" ) ) lightning_model.load_state_dict(ckpt["state_dict"] ) # init longformer question answering model lowercase_ = LongformerForQuestionAnswering.from_pretrained(__lowerCamelCase ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(__lowerCamelCase ) print(F'Conversion successful. Model saved under {pytorch_dump_folder_path}' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--longformer_model""", default=None, type=str, required=True, help="""model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.""", ) parser.add_argument( """--longformer_question_answering_ckpt_path""", default=None, type=str, required=True, help="""Path the official PyTorch Lightning Checkpoint.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
601
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class __lowerCamelCase ( pl.LightningModule ): """simple docstring""" def __init__( self , UpperCAmelCase ) -> Optional[int]: '''simple docstring''' super().__init__() lowercase_ = model lowercase_ = 2 lowercase_ = nn.Linear(self.model.config.hidden_size , self.num_labels ) def A__ ( self ) -> List[Any]: '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: str , __lowerCamelCase: str , __lowerCamelCase: str ): '''simple docstring''' lowercase_ = LongformerModel.from_pretrained(__lowerCamelCase ) lowercase_ = LightningModel(__lowerCamelCase ) lowercase_ = torch.load(__lowerCamelCase , map_location=torch.device("cpu" ) ) lightning_model.load_state_dict(ckpt["state_dict"] ) # init longformer question answering model lowercase_ = LongformerForQuestionAnswering.from_pretrained(__lowerCamelCase ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(__lowerCamelCase ) print(F'Conversion successful. Model saved under {pytorch_dump_folder_path}' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--longformer_model""", default=None, type=str, required=True, help="""model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.""", ) parser.add_argument( """--longformer_question_answering_ckpt_path""", default=None, type=str, required=True, help="""Path the official PyTorch Lightning Checkpoint.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
601
1
import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex UpperCamelCase = logging.getLogger(__name__) class _A : def __init__( self : Optional[int] ): """simple docstring""" __UpperCamelCase : List[str] = False def a ( self : Dict , lowerCamelCase__ : Any , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : str ): """simple docstring""" if not self.initialized: __UpperCamelCase : Dict = RagRetriever( lowerCamelCase__ , question_encoder_tokenizer=lowerCamelCase__ , generator_tokenizer=lowerCamelCase__ , index=lowerCamelCase__ , init_retrieval=lowerCamelCase__ , ) __UpperCamelCase : str = True def a ( self : Union[str, Any] ): """simple docstring""" self.retriever.index.init_index() def a ( self : List[str] , lowerCamelCase__ : Tuple , lowerCamelCase__ : Any ): """simple docstring""" __UpperCamelCase , __UpperCamelCase : Union[str, Any] = self.retriever._main_retrieve(lowerCamelCase__ , lowerCamelCase__ ) return doc_ids, retrieved_doc_embeds class _A ( UpperCAmelCase_ ): def __init__( self : Any , lowerCamelCase__ : Tuple , lowerCamelCase__ : str , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[str] , lowerCamelCase__ : List[Any]=None ): """simple docstring""" if index is not None and index.is_initialized() and len(lowerCamelCase__ ) > 0: raise ValueError( """When using Ray for distributed fine-tuning, """ """you'll need to provide the paths instead, """ """as the dataset and the index are loaded """ """separately. More info in examples/rag/use_own_knowledge_dataset.py """ ) super().__init__( lowerCamelCase__ , question_encoder_tokenizer=lowerCamelCase__ , generator_tokenizer=lowerCamelCase__ , index=lowerCamelCase__ , init_retrieval=lowerCamelCase__ , ) __UpperCamelCase : List[str] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) for worker in self.retrieval_workers ] ) def a ( self : List[Any] ): """simple docstring""" logger.info("""initializing retrieval""" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def a ( self : Optional[int] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : Optional[Any] ): """simple docstring""" if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. __UpperCamelCase : Optional[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] __UpperCamelCase , __UpperCamelCase : List[Any] = ray.get(random_worker.retrieve.remote(lowerCamelCase__ , lowerCamelCase__ ) ) else: __UpperCamelCase , __UpperCamelCase : Dict = self._main_retrieve(lowerCamelCase__ , lowerCamelCase__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowerCamelCase__ ) @classmethod def a ( cls : Optional[Any] , lowerCamelCase__ : int , lowerCamelCase__ : int=None , **lowerCamelCase__ : Optional[int] ): """simple docstring""" return super(lowerCamelCase__ , cls ).get_tokenizers(lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ) @classmethod def a ( cls : int , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[str]=None , **lowerCamelCase__ : Dict ): """simple docstring""" __UpperCamelCase : Dict = kwargs.pop("""config""" , lowerCamelCase__ ) or RagConfig.from_pretrained(lowerCamelCase__ , **lowerCamelCase__ ) __UpperCamelCase : Optional[Any] = RagTokenizer.from_pretrained(lowerCamelCase__ , config=lowerCamelCase__ ) __UpperCamelCase : Tuple = rag_tokenizer.question_encoder __UpperCamelCase : Optional[int] = rag_tokenizer.generator if indexed_dataset is not None: __UpperCamelCase : Union[str, Any] = """custom""" __UpperCamelCase : Optional[Any] = CustomHFIndex(config.retrieval_vector_size , lowerCamelCase__ ) else: __UpperCamelCase : Union[str, Any] = cls._build_index(lowerCamelCase__ ) return cls( lowerCamelCase__ , question_encoder_tokenizer=lowerCamelCase__ , generator_tokenizer=lowerCamelCase__ , retrieval_workers=lowerCamelCase__ , index=lowerCamelCase__ , )
269
from __future__ import annotations from typing import Any class _A : def __init__( self : List[Any] , lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : float = 0 ): """simple docstring""" __UpperCamelCase , __UpperCamelCase : Tuple = row, column __UpperCamelCase : Tuple = [[default_value for c in range(lowerCamelCase__ )] for r in range(lowerCamelCase__ )] def __str__( self : List[Any] ): """simple docstring""" __UpperCamelCase : Dict = f'Matrix consist of {self.row} rows and {self.column} columns\n' # Make string identifier __UpperCamelCase : Optional[int] = 0 for row_vector in self.array: for obj in row_vector: __UpperCamelCase : int = max(lowerCamelCase__ , len(str(lowerCamelCase__ ) ) ) __UpperCamelCase : Union[str, Any] = f'%{max_element_length}s' # Make string and return def single_line(lowerCamelCase__ : list[float] ) -> str: nonlocal string_format_identifier __UpperCamelCase : List[Any] = """[""" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(lowerCamelCase__ ) for row_vector in self.array ) return s def __repr__( self : Any ): """simple docstring""" return str(self ) def a ( self : str , lowerCamelCase__ : tuple[int, int] ): """simple docstring""" if not (isinstance(lowerCamelCase__ , (list, tuple) ) and len(lowerCamelCase__ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Union[str, Any] , lowerCamelCase__ : tuple[int, int] ): """simple docstring""" assert self.validate_indicies(lowerCamelCase__ ) return self.array[loc[0]][loc[1]] def __setitem__( self : Union[str, Any] , lowerCamelCase__ : tuple[int, int] , lowerCamelCase__ : float ): """simple docstring""" assert self.validate_indicies(lowerCamelCase__ ) __UpperCamelCase : str = value def __add__( self : int , lowerCamelCase__ : Matrix ): """simple docstring""" assert isinstance(lowerCamelCase__ , lowerCamelCase__ ) assert self.row == another.row and self.column == another.column # Add __UpperCamelCase : Tuple = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCamelCase : Optional[int] = self[r, c] + another[r, c] return result def __neg__( self : Optional[int] ): """simple docstring""" __UpperCamelCase : str = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCamelCase : Any = -self[r, c] return result def __sub__( self : Tuple , lowerCamelCase__ : Matrix ): """simple docstring""" return self + (-another) def __mul__( self : Tuple , lowerCamelCase__ : int | float | Matrix ): """simple docstring""" if isinstance(lowerCamelCase__ , (int, float) ): # Scalar multiplication __UpperCamelCase : List[str] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __UpperCamelCase : Tuple = self[r, c] * another return result elif isinstance(lowerCamelCase__ , lowerCamelCase__ ): # Matrix multiplication assert self.column == another.row __UpperCamelCase : List[Any] = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: __UpperCamelCase : Any = f'Unsupported type given for another ({type(lowerCamelCase__ )})' raise TypeError(lowerCamelCase__ ) def a ( self : Union[str, Any] ): """simple docstring""" __UpperCamelCase : Dict = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): __UpperCamelCase : str = self[r, c] return result def a ( self : Any , lowerCamelCase__ : Matrix , lowerCamelCase__ : Matrix ): """simple docstring""" assert isinstance(lowerCamelCase__ , lowerCamelCase__ ) and isinstance(lowerCamelCase__ , lowerCamelCase__ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate __UpperCamelCase : Optional[int] = v.transpose() __UpperCamelCase : Tuple = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def __lowerCamelCase ( ) -> None: # a^(-1) __UpperCamelCase : str = Matrix(3 , 3 , 0 ) for i in range(3 ): __UpperCamelCase : List[str] = 1 print(f'a^(-1) is {ainv}' ) # u, v __UpperCamelCase : Any = Matrix(3 , 1 , 0 ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Any = 1, 2, -3 __UpperCamelCase : int = Matrix(3 , 1 , 0 ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Dict = 4, -2, 5 print(f'u is {u}' ) print(f'v is {v}' ) print(f'uv^T is {u * v.transpose()}' ) # Sherman Morrison print(f'(a + uv^T)^(-1) is {ainv.sherman_morrison(__lowerCAmelCase , __lowerCAmelCase )}' ) def __lowerCamelCase ( ) -> None: import doctest doctest.testmod() testa()
269
1
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def _lowerCAmelCase ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: List[str]=True , UpperCamelCase__: Union[str, Any]="pt" ) -> int: """simple docstring""" A = {"""add_prefix_space""": True} if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and not line.startswith(""" """ ) else {} A = padding_side return tokenizer( [line] , max_length=lowerCAmelCase__ , padding="""max_length""" if pad_to_max_length else None , truncation=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , **lowerCAmelCase__ , ) def _lowerCAmelCase ( UpperCamelCase__: Dict , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Any=None , ) -> int: """simple docstring""" A = input_ids.ne(lowerCAmelCase__ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class _UpperCamelCase ( __SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , a__ , a__ , a__ , a__ , a__="train" , a__=None , a__=None , a__=None , a__="" , ) -> Optional[Any]: super().__init__() A = Path(_a ).joinpath(type_path + """.source""" ) A = Path(_a ).joinpath(type_path + """.target""" ) A = self.get_char_lens(self.src_file ) A = max_source_length A = max_target_length assert min(self.src_lens ) > 0, f'found empty line in {self.src_file}' A = tokenizer A = prefix if n_obs is not None: A = self.src_lens[:n_obs] A = src_lang A = tgt_lang def __len__( self ) -> Any: return len(self.src_lens ) def __getitem__( self , a__ ) -> Any: A = index + 1 # linecache starts at 1 A = self.prefix + linecache.getline(str(self.src_file ) , _a ).rstrip("""\n""" ) A = linecache.getline(str(self.tgt_file ) , _a ).rstrip("""\n""" ) assert source_line, f'empty source line for index {index}' assert tgt_line, f'empty tgt line for index {index}' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _a ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right A = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _a ) else self.tokenizer ) A = self.tokenizer.generator if isinstance(self.tokenizer , _a ) else self.tokenizer A = encode_line(_a , _a , self.max_source_length , """right""" ) A = encode_line(_a , _a , self.max_target_length , """right""" ) A = source_inputs["""input_ids"""].squeeze() A = target_inputs["""input_ids"""].squeeze() A = source_inputs["""attention_mask"""].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def _UpperCAmelCase ( a__ ) -> Union[str, Any]: return [len(_a ) for x in Path(_a ).open().readlines()] def _UpperCAmelCase ( self , a__ ) -> List[str]: A = torch.stack([x["""input_ids"""] for x in batch] ) A = torch.stack([x["""attention_mask"""] for x in batch] ) A = torch.stack([x["""decoder_input_ids"""] for x in batch] ) A = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _a ) else self.tokenizer.pad_token_id ) A = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _a ) else self.tokenizer.pad_token_id ) A = trim_batch(_a , _a ) A , A = trim_batch(_a , _a , attention_mask=_a ) A = { """input_ids""": source_ids, """attention_mask""": source_mask, """decoder_input_ids""": y, } return batch _lowercase : List[str] = getLogger(__name__) def _lowerCAmelCase ( UpperCamelCase__: List[List] ) -> int: """simple docstring""" return list(itertools.chain.from_iterable(lowerCAmelCase__ ) ) def _lowerCAmelCase ( UpperCamelCase__: str ) -> None: """simple docstring""" A = get_git_info() save_json(lowerCAmelCase__ , os.path.join(lowerCAmelCase__ , """git_log.json""" ) ) def _lowerCAmelCase ( UpperCamelCase__: List[Any] , UpperCamelCase__: Dict , UpperCamelCase__: int=4 , **UpperCamelCase__: Optional[int] ) -> str: """simple docstring""" with open(lowerCAmelCase__ , """w""" ) as f: json.dump(lowerCAmelCase__ , lowerCAmelCase__ , indent=lowerCAmelCase__ , **lowerCAmelCase__ ) def _lowerCAmelCase ( UpperCamelCase__: Optional[Any] ) -> Dict: """simple docstring""" with open(lowerCAmelCase__ ) as f: return json.load(lowerCAmelCase__ ) def _lowerCAmelCase ( ) -> Optional[Any]: """simple docstring""" A = git.Repo(search_parent_directories=lowerCAmelCase__ ) A = { """repo_id""": str(lowerCAmelCase__ ), """repo_sha""": str(repo.head.object.hexsha ), """repo_branch""": str(repo.active_branch ), """hostname""": str(socket.gethostname() ), } return repo_infos def _lowerCAmelCase ( UpperCamelCase__: Callable , UpperCamelCase__: Iterable ) -> List: """simple docstring""" return list(map(lowerCAmelCase__ , lowerCAmelCase__ ) ) def _lowerCAmelCase ( UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ) -> Optional[int]: """simple docstring""" with open(lowerCAmelCase__ , """wb""" ) as f: return pickle.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowerCAmelCase ( UpperCamelCase__: List[str] ) -> str: """simple docstring""" def remove_articles(UpperCamelCase__: Any ): return re.sub(r"""\b(a|an|the)\b""" , """ """ , lowerCAmelCase__ ) def white_space_fix(UpperCamelCase__: List[Any] ): return " ".join(text.split() ) def remove_punc(UpperCamelCase__: int ): A = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(UpperCamelCase__: int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase__ ) ) ) ) def _lowerCAmelCase ( UpperCamelCase__: Dict , UpperCamelCase__: str ) -> Union[str, Any]: """simple docstring""" A = normalize_answer(lowerCAmelCase__ ).split() A = normalize_answer(lowerCAmelCase__ ).split() A = Counter(lowerCAmelCase__ ) & Counter(lowerCAmelCase__ ) A = sum(common.values() ) if num_same == 0: return 0 A = 1.0 * num_same / len(lowerCAmelCase__ ) A = 1.0 * num_same / len(lowerCAmelCase__ ) A = (2 * precision * recall) / (precision + recall) return fa def _lowerCAmelCase ( UpperCamelCase__: str , UpperCamelCase__: int ) -> int: """simple docstring""" return normalize_answer(lowerCAmelCase__ ) == normalize_answer(lowerCAmelCase__ ) def _lowerCAmelCase ( UpperCamelCase__: List[str] , UpperCamelCase__: List[str] ) -> Dict: """simple docstring""" assert len(lowerCAmelCase__ ) == len(lowerCAmelCase__ ) A = 0 for hypo, pred in zip(lowerCAmelCase__ , lowerCAmelCase__ ): em += exact_match_score(lowerCAmelCase__ , lowerCAmelCase__ ) if len(lowerCAmelCase__ ) > 0: em /= len(lowerCAmelCase__ ) return {"em": em} def _lowerCAmelCase ( UpperCamelCase__: Optional[int] ) -> Tuple: """simple docstring""" return model_prefix.startswith("""rag""" ) def _lowerCAmelCase ( UpperCamelCase__: Optional[int] , UpperCamelCase__: Dict , UpperCamelCase__: Tuple ) -> Optional[Any]: """simple docstring""" A = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead A = """dropout_rate""" for p in extra_params: if getattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): if not hasattr(lowerCAmelCase__ , lowerCAmelCase__ ) and not hasattr(lowerCAmelCase__ , equivalent_param[p] ): logger.info("""config doesn\'t have a `{}` attribute""".format(lowerCAmelCase__ ) ) delattr(lowerCAmelCase__ , lowerCAmelCase__ ) continue A = p if hasattr(lowerCAmelCase__ , lowerCAmelCase__ ) else equivalent_param[p] setattr(lowerCAmelCase__ , lowerCAmelCase__ , getattr(lowerCAmelCase__ , lowerCAmelCase__ ) ) delattr(lowerCAmelCase__ , lowerCAmelCase__ ) return hparams, config
721
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _UpperCamelCase ( __snake_case , unittest.TestCase ): """simple docstring""" lowerCAmelCase = ConsistencyModelPipeline lowerCAmelCase = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowerCAmelCase = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt lowerCAmelCase = frozenset( [ 'num_inference_steps', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) @property def _UpperCAmelCase ( self ) -> Any: A = UNetaDModel.from_pretrained( """diffusers/consistency-models-test""" , subfolder="""test_unet""" , ) return unet @property def _UpperCAmelCase ( self ) -> str: A = UNetaDModel.from_pretrained( """diffusers/consistency-models-test""" , subfolder="""test_unet_class_cond""" , ) return unet def _UpperCAmelCase ( self , a__=False ) -> Tuple: if class_cond: A = self.dummy_cond_unet else: A = self.dummy_uncond_unet # Default to CM multistep sampler A = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_02 , sigma_max=80.0 , ) A = { """unet""": unet, """scheduler""": scheduler, } return components def _UpperCAmelCase ( self , a__ , a__=0 ) -> Tuple: if str(a__ ).startswith("""mps""" ): A = torch.manual_seed(a__ ) else: A = torch.Generator(device=a__ ).manual_seed(a__ ) A = { """batch_size""": 1, """num_inference_steps""": None, """timesteps""": [22, 0], """generator""": generator, """output_type""": """np""", } return inputs def _UpperCAmelCase ( self ) -> str: A = """cpu""" # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = ConsistencyModelPipeline(**a__ ) A = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) A = self.get_dummy_inputs(a__ ) A = pipe(**a__ ).images assert image.shape == (1, 32, 32, 3) A = image[0, -3:, -3:, -1] A = np.array([0.35_72, 0.62_73, 0.40_31, 0.39_61, 0.43_21, 0.57_30, 0.52_66, 0.47_80, 0.50_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _UpperCAmelCase ( self ) -> Optional[int]: A = """cpu""" # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components(class_cond=a__ ) A = ConsistencyModelPipeline(**a__ ) A = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) A = self.get_dummy_inputs(a__ ) A = 0 A = pipe(**a__ ).images assert image.shape == (1, 32, 32, 3) A = image[0, -3:, -3:, -1] A = np.array([0.35_72, 0.62_73, 0.40_31, 0.39_61, 0.43_21, 0.57_30, 0.52_66, 0.47_80, 0.50_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _UpperCAmelCase ( self ) -> Optional[int]: A = """cpu""" # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = ConsistencyModelPipeline(**a__ ) A = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) A = self.get_dummy_inputs(a__ ) A = 1 A = None A = pipe(**a__ ).images assert image.shape == (1, 32, 32, 3) A = image[0, -3:, -3:, -1] A = np.array([0.50_04, 0.50_04, 0.49_94, 0.50_08, 0.49_76, 0.50_18, 0.49_90, 0.49_82, 0.49_87] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _UpperCAmelCase ( self ) -> str: A = """cpu""" # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components(class_cond=a__ ) A = ConsistencyModelPipeline(**a__ ) A = pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) A = self.get_dummy_inputs(a__ ) A = 1 A = None A = 0 A = pipe(**a__ ).images assert image.shape == (1, 32, 32, 3) A = image[0, -3:, -3:, -1] A = np.array([0.50_04, 0.50_04, 0.49_94, 0.50_08, 0.49_76, 0.50_18, 0.49_90, 0.49_82, 0.49_87] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class _UpperCamelCase ( unittest.TestCase ): """simple docstring""" def _UpperCAmelCase ( self ) -> Tuple: super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCAmelCase ( self , a__=0 , a__=False , a__="cpu" , a__=torch.floataa , a__=(1, 3, 64, 64) ) -> str: A = torch.manual_seed(a__ ) A = { """num_inference_steps""": None, """timesteps""": [22, 0], """class_labels""": 0, """generator""": generator, """output_type""": """np""", } if get_fixed_latents: A = self.get_fixed_latents(seed=a__ , device=a__ , dtype=a__ , shape=a__ ) A = latents return inputs def _UpperCAmelCase ( self , a__=0 , a__="cpu" , a__=torch.floataa , a__=(1, 3, 64, 64) ) -> Optional[Any]: if type(a__ ) == str: A = torch.device(a__ ) A = torch.Generator(device=a__ ).manual_seed(a__ ) A = randn_tensor(a__ , generator=a__ , device=a__ , dtype=a__ ) return latents def _UpperCAmelCase ( self ) -> Tuple: A = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) A = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_02 , sigma_max=80.0 , ) A = ConsistencyModelPipeline(unet=a__ , scheduler=a__ ) pipe.to(torch_device=a__ ) pipe.set_progress_bar_config(disable=a__ ) A = self.get_inputs() A = pipe(**a__ ).images assert image.shape == (1, 64, 64, 3) A = image[0, -3:, -3:, -1] A = np.array([0.08_88, 0.08_81, 0.06_66, 0.04_79, 0.02_92, 0.01_95, 0.02_01, 0.01_63, 0.02_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _UpperCAmelCase ( self ) -> Dict: A = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) A = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_02 , sigma_max=80.0 , ) A = ConsistencyModelPipeline(unet=a__ , scheduler=a__ ) pipe.to(torch_device=a__ ) pipe.set_progress_bar_config(disable=a__ ) A = self.get_inputs() A = 1 A = None A = pipe(**a__ ).images assert image.shape == (1, 64, 64, 3) A = image[0, -3:, -3:, -1] A = np.array([0.03_40, 0.01_52, 0.00_63, 0.02_67, 0.02_21, 0.01_07, 0.04_16, 0.01_86, 0.02_17] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def _UpperCAmelCase ( self ) -> Union[str, Any]: A = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) A = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_02 , sigma_max=80.0 , ) A = ConsistencyModelPipeline(unet=a__ , scheduler=a__ ) pipe.to(torch_device=a__ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a__ ) A = self.get_inputs(get_fixed_latents=a__ , device=a__ ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a__ , enable_math=a__ , enable_mem_efficient=a__ ): A = pipe(**a__ ).images assert image.shape == (1, 64, 64, 3) A = image[0, -3:, -3:, -1] A = np.array([0.18_75, 0.14_28, 0.12_89, 0.21_51, 0.20_92, 0.14_77, 0.18_77, 0.16_41, 0.13_53] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def _UpperCAmelCase ( self ) -> List[Any]: A = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) A = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_02 , sigma_max=80.0 , ) A = ConsistencyModelPipeline(unet=a__ , scheduler=a__ ) pipe.to(torch_device=a__ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a__ ) A = self.get_inputs(get_fixed_latents=a__ , device=a__ ) A = 1 A = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a__ , enable_math=a__ , enable_mem_efficient=a__ ): A = pipe(**a__ ).images assert image.shape == (1, 64, 64, 3) A = image[0, -3:, -3:, -1] A = np.array([0.16_63, 0.19_48, 0.22_75, 0.16_80, 0.12_04, 0.12_45, 0.18_58, 0.13_38, 0.20_95] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
546
0
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __UpperCamelCase ( unittest.TestCase ): def UpperCamelCase( self ): _UpperCAmelCase = '''ylacombe/bark-small''' _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = '''en_speaker_1''' _UpperCAmelCase = '''This is a test string''' _UpperCAmelCase = '''speaker_embeddings_path.json''' _UpperCAmelCase = '''speaker_embeddings''' def UpperCamelCase( self , **_UpperCamelCase ): return AutoTokenizer.from_pretrained(self.checkpoint , **_UpperCamelCase ) def UpperCamelCase( self ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase( self ): _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = BarkProcessor(tokenizer=_UpperCamelCase ) processor.save_pretrained(self.tmpdirname ) _UpperCAmelCase = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def UpperCamelCase( self ): _UpperCAmelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) _UpperCAmelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _UpperCAmelCase = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def UpperCamelCase( self ): _UpperCAmelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) _UpperCAmelCase = 35 _UpperCAmelCase = 2 _UpperCAmelCase = 8 _UpperCAmelCase = { '''semantic_prompt''': np.ones(_UpperCamelCase ), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len) ), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset _UpperCAmelCase = processor(text=self.input_string , voice_preset=_UpperCamelCase ) _UpperCAmelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_UpperCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from npz file _UpperCAmelCase = os.path.join(self.tmpdirname , '''file.npz''' ) np.savez(_UpperCamelCase , **_UpperCamelCase ) _UpperCAmelCase = processor(text=self.input_string , voice_preset=_UpperCamelCase ) _UpperCAmelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_UpperCamelCase , np.array([] ) ).tolist() ) # test loading voice preset from the hub _UpperCAmelCase = processor(text=self.input_string , voice_preset=self.voice_preset ) def UpperCamelCase( self ): _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = BarkProcessor(tokenizer=_UpperCamelCase ) _UpperCAmelCase = processor(text=self.input_string ) _UpperCAmelCase = tokenizer( self.input_string , padding='''max_length''' , max_length=256 , add_special_tokens=_UpperCamelCase , return_attention_mask=_UpperCamelCase , return_token_type_ids=_UpperCamelCase , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
32
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Tuple: if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__UpperCamelCase , n - 1 , __UpperCamelCase ) * a) % mod else: UpperCamelCase = binary_exponentiation(__UpperCamelCase , n / 2 , __UpperCamelCase ) return (b * b) % mod # a prime number SCREAMING_SNAKE_CASE__ = 7_0_1 SCREAMING_SNAKE_CASE__ = 1_0_0_0_0_0_0_0_0_0 SCREAMING_SNAKE_CASE__ = 1_0 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
301
0
"""simple docstring""" def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : list , SCREAMING_SNAKE_CASE : list , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' if index == number_of_items: return 0 lowerCAmelCase = 0 lowerCAmelCase = 0 lowerCAmelCase = knapsack(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if weights[index] <= max_weight: lowerCAmelCase = values[index] + knapsack( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 ) return max(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
393
"""simple docstring""" import warnings from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase ( _UpperCAmelCase ): _SCREAMING_SNAKE_CASE = ['image_processor', 'tokenizer'] _SCREAMING_SNAKE_CASE = 'FlavaImageProcessor' _SCREAMING_SNAKE_CASE = ('BertTokenizer', 'BertTokenizerFast') def __init__( self , lowercase=None , lowercase=None , **lowercase ) -> int: lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , lowercase , ) lowerCAmelCase = kwargs.pop("""feature_extractor""" ) lowerCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(lowercase , lowercase ) lowerCAmelCase = self.image_processor def __call__( self , lowercase = None , lowercase = None , lowercase = True , lowercase = False , lowercase = False , lowercase = None , lowercase = 0 , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = False , lowercase = False , lowercase = False , lowercase = False , lowercase = True , lowercase = None , **lowercase , ) -> 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: lowerCAmelCase = self.tokenizer( text=lowercase , add_special_tokens=lowercase , padding=lowercase , truncation=lowercase , max_length=lowercase , stride=lowercase , pad_to_multiple_of=lowercase , return_token_type_ids=lowercase , return_attention_mask=lowercase , return_overflowing_tokens=lowercase , return_special_tokens_mask=lowercase , return_offsets_mapping=lowercase , return_length=lowercase , verbose=lowercase , return_tensors=lowercase , **lowercase , ) if images is not None: lowerCAmelCase = self.image_processor( lowercase , return_image_mask=lowercase , return_codebook_pixels=lowercase , return_tensors=lowercase , **lowercase , ) if text is not None and images is not None: encoding.update(lowercase ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**lowercase ) , tensor_type=lowercase ) def _snake_case ( self , *lowercase , **lowercase ) -> Optional[int]: return self.tokenizer.batch_decode(*lowercase , **lowercase ) def _snake_case ( self , *lowercase , **lowercase ) -> str: return self.tokenizer.decode(*lowercase , **lowercase ) @property def _snake_case ( self ) -> Optional[Any]: lowerCAmelCase = self.tokenizer.model_input_names lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def _snake_case ( self ) -> List[str]: warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , lowercase , ) return self.image_processor_class @property def _snake_case ( self ) -> List[str]: warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , lowercase , ) return self.image_processor
393
1
'''simple docstring''' from __future__ import annotations from math import pi def _snake_case ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] ) -> Union[str, Any]: """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if inductance < 0: raise ValueError("""Inductance cannot be negative""" ) if frequency < 0: raise ValueError("""Frequency cannot be negative""" ) if reactance < 0: raise ValueError("""Inductive reactance cannot be negative""" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
433
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { 'configuration_swinv2': ['SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Swinv2Config'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST', 'Swinv2ForImageClassification', 'Swinv2ForMaskedImageModeling', 'Swinv2Model', 'Swinv2PreTrainedModel', ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
25
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def snake_case__ ( _snake_case : Optional[Any] ): """simple docstring""" UpperCamelCase__ = SwinvaConfig() UpperCamelCase__ = swinva_name.split("_" ) UpperCamelCase__ = name_split[1] if "to" in name_split[3]: UpperCamelCase__ = int(name_split[3][-3:] ) else: UpperCamelCase__ = int(name_split[3] ) if "to" in name_split[2]: UpperCamelCase__ = int(name_split[2][-2:] ) else: UpperCamelCase__ = int(name_split[2][6:] ) if model_size == "tiny": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 6, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "small": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "base": UpperCamelCase__ = 1_28 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (4, 8, 16, 32) else: UpperCamelCase__ = 1_92 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (6, 12, 24, 48) if "to" in swinva_name: UpperCamelCase__ = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): UpperCamelCase__ = 2_18_41 UpperCamelCase__ = "huggingface/label-files" UpperCamelCase__ = "imagenet-22k-id2label.json" UpperCamelCase__ = json.load(open(hf_hub_download(_snake_case , _snake_case , repo_type="dataset" ) , "r" ) ) UpperCamelCase__ = {int(_snake_case ): v for k, v in idalabel.items()} UpperCamelCase__ = idalabel UpperCamelCase__ = {v: k for k, v in idalabel.items()} else: UpperCamelCase__ = 10_00 UpperCamelCase__ = "huggingface/label-files" UpperCamelCase__ = "imagenet-1k-id2label.json" UpperCamelCase__ = json.load(open(hf_hub_download(_snake_case , _snake_case , repo_type="dataset" ) , "r" ) ) UpperCamelCase__ = {int(_snake_case ): v for k, v in idalabel.items()} UpperCamelCase__ = idalabel UpperCamelCase__ = {v: k for k, v in idalabel.items()} UpperCamelCase__ = img_size UpperCamelCase__ = num_classes UpperCamelCase__ = embed_dim UpperCamelCase__ = depths UpperCamelCase__ = num_heads UpperCamelCase__ = window_size return config def snake_case__ ( _snake_case : str ): """simple docstring""" if "patch_embed.proj" in name: UpperCamelCase__ = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: UpperCamelCase__ = name.replace("patch_embed.norm" , "embeddings.norm" ) if "layers" in name: UpperCamelCase__ = "encoder." + name if "attn.proj" in name: UpperCamelCase__ = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: UpperCamelCase__ = name.replace("attn" , "attention.self" ) if "norm1" in name: UpperCamelCase__ = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: UpperCamelCase__ = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: UpperCamelCase__ = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: UpperCamelCase__ = name.replace("mlp.fc2" , "output.dense" ) if "q_bias" in name: UpperCamelCase__ = name.replace("q_bias" , "query.bias" ) if "k_bias" in name: UpperCamelCase__ = name.replace("k_bias" , "key.bias" ) if "v_bias" in name: UpperCamelCase__ = name.replace("v_bias" , "value.bias" ) if "cpb_mlp" in name: UpperCamelCase__ = name.replace("cpb_mlp" , "continuous_position_bias_mlp" ) if name == "norm.weight": UpperCamelCase__ = "layernorm.weight" if name == "norm.bias": UpperCamelCase__ = "layernorm.bias" if "head" in name: UpperCamelCase__ = name.replace("head" , "classifier" ) else: UpperCamelCase__ = "swinv2." + name return name def snake_case__ ( _snake_case : List[Any] , _snake_case : Dict ): """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCamelCase__ = orig_state_dict.pop(_snake_case ) if "mask" in key: continue elif "qkv" in key: UpperCamelCase__ = key.split("." ) UpperCamelCase__ = int(key_split[1] ) UpperCamelCase__ = int(key_split[3] ) UpperCamelCase__ = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: UpperCamelCase__ = val[:dim, :] UpperCamelCase__ = val[dim : dim * 2, :] UpperCamelCase__ = val[-dim:, :] else: UpperCamelCase__ = val[:dim] UpperCamelCase__ = val[ dim : dim * 2 ] UpperCamelCase__ = val[-dim:] else: UpperCamelCase__ = val return orig_state_dict def snake_case__ ( _snake_case : Optional[Any] , _snake_case : Union[str, Any] ): """simple docstring""" UpperCamelCase__ = timm.create_model(_snake_case , pretrained=_snake_case ) timm_model.eval() UpperCamelCase__ = get_swinva_config(_snake_case ) UpperCamelCase__ = SwinvaForImageClassification(_snake_case ) model.eval() UpperCamelCase__ = convert_state_dict(timm_model.state_dict() , _snake_case ) model.load_state_dict(_snake_case ) UpperCamelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCamelCase__ = AutoImageProcessor.from_pretrained("microsoft/{}".format(swinva_name.replace("_" , "-" ) ) ) UpperCamelCase__ = Image.open(requests.get(_snake_case , stream=_snake_case ).raw ) UpperCamelCase__ = image_processor(images=_snake_case , return_tensors="pt" ) UpperCamelCase__ = timm_model(inputs["pixel_values"] ) UpperCamelCase__ = model(**_snake_case ).logits assert torch.allclose(_snake_case , _snake_case , atol=1E-3 ) print(F'Saving model {swinva_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(_snake_case ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(_snake_case ) model.push_to_hub( repo_path_or_name=Path(_snake_case , _snake_case ) , organization="nandwalritik" , commit_message="Add model" , ) if __name__ == "__main__": A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swinv2_name', default='swinv2_tiny_patch4_window8_256', type=str, help='Name of the Swinv2 timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) A : Tuple = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
304
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase__ ( self :Optional[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCamelCase__ ( self :List[Any] ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase__ = UNetaDModel( sample_size=(3_2, 6_4) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return model @property def lowerCamelCase__ ( self :Tuple ) -> Any: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase__ = UNetaDConditionModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , cross_attention_dim=1_0 , ) return model @property def lowerCamelCase__ ( self :Optional[Any] ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase__ = AutoencoderKL( sample_size=(1_2_8, 6_4) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("DownEncoderBlock2D", "DownEncoderBlock2D") , up_block_types=("UpDecoderBlock2D", "UpDecoderBlock2D") , ) UpperCamelCase__ = UNetaDModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return vqvae, unet @slow def lowerCamelCase__ ( self :List[str] ) -> List[str]: """simple docstring""" UpperCamelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCamelCase__ = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) UpperCamelCase__ = DDPMScheduler() UpperCamelCase__ = AudioDiffusionPipeline(vqvae=lowerCamelCase_ , unet=self.dummy_unet , mel=lowerCamelCase_ , scheduler=lowerCamelCase_ ) UpperCamelCase__ = pipe.to(lowerCamelCase_ ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) UpperCamelCase__ = torch.Generator(device=lowerCamelCase_ ).manual_seed(4_2 ) UpperCamelCase__ = pipe(generator=lowerCamelCase_ , steps=4 ) UpperCamelCase__ = output.audios[0] UpperCamelCase__ = output.images[0] UpperCamelCase__ = torch.Generator(device=lowerCamelCase_ ).manual_seed(4_2 ) UpperCamelCase__ = pipe(generator=lowerCamelCase_ , steps=4 , return_dict=lowerCamelCase_ ) UpperCamelCase__ = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) UpperCamelCase__ = np.frombuffer(image.tobytes() , dtype="uint8" )[:1_0] UpperCamelCase__ = np.frombuffer(image_from_tuple.tobytes() , dtype="uint8" )[:1_0] UpperCamelCase__ = np.array([6_9, 2_5_5, 2_5_5, 2_5_5, 0, 0, 7_7, 1_8_1, 1_2, 1_2_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 UpperCamelCase__ = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) UpperCamelCase__ = DDIMScheduler() UpperCamelCase__ = self.dummy_vqvae_and_unet UpperCamelCase__ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=lowerCamelCase_ , scheduler=lowerCamelCase_ ) UpperCamelCase__ = pipe.to(lowerCamelCase_ ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) np.random.seed(0 ) UpperCamelCase__ = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) UpperCamelCase__ = torch.Generator(device=lowerCamelCase_ ).manual_seed(4_2 ) UpperCamelCase__ = pipe(raw_audio=lowerCamelCase_ , generator=lowerCamelCase_ , start_step=5 , steps=1_0 ) UpperCamelCase__ = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) UpperCamelCase__ = np.frombuffer(image.tobytes() , dtype="uint8" )[:1_0] UpperCamelCase__ = np.array([1_2_0, 1_1_7, 1_1_0, 1_0_9, 1_3_8, 1_6_7, 1_3_8, 1_4_8, 1_3_2, 1_2_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 UpperCamelCase__ = self.dummy_unet_condition UpperCamelCase__ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=lowerCamelCase_ , mel=lowerCamelCase_ , scheduler=lowerCamelCase_ ) UpperCamelCase__ = pipe.to(lowerCamelCase_ ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) np.random.seed(0 ) UpperCamelCase__ = torch.rand((1, 1, 1_0) ) UpperCamelCase__ = pipe(generator=lowerCamelCase_ , encoding=lowerCamelCase_ ) UpperCamelCase__ = output.images[0] UpperCamelCase__ = np.frombuffer(image.tobytes() , dtype="uint8" )[:1_0] UpperCamelCase__ = np.array([1_0_7, 1_0_3, 1_2_0, 1_2_7, 1_4_2, 1_2_2, 1_1_3, 1_2_2, 9_7, 1_1_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase__ ( self :Optional[Any] ) -> List[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self :Any ) -> str: """simple docstring""" UpperCamelCase__ = torch_device UpperCamelCase__ = DiffusionPipeline.from_pretrained("teticio/audio-diffusion-ddim-256" ) UpperCamelCase__ = pipe.to(lowerCamelCase_ ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) UpperCamelCase__ = torch.Generator(device=lowerCamelCase_ ).manual_seed(4_2 ) UpperCamelCase__ = pipe(generator=lowerCamelCase_ ) UpperCamelCase__ = output.audios[0] UpperCamelCase__ = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] UpperCamelCase__ = np.frombuffer(image.tobytes() , dtype="uint8" )[:1_0] UpperCamelCase__ = np.array([1_5_1, 1_6_7, 1_5_4, 1_4_4, 1_2_2, 1_3_4, 1_2_1, 1_0_5, 7_0, 2_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
304
1
import requests UpperCAmelCase_ : List[str] = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def lowerCAmelCase_ ( lowerCamelCase ): # fetching a list of articles in json format __magic_name__ : List[Any] =requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["""articles"""] , 1 ): print(F"{i}.) {article['title']}" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
21
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class SCREAMING_SNAKE_CASE_ ( snake_case__ ): """simple docstring""" __snake_case : int = """philschmid/bart-large-cnn-samsum""" __snake_case : Optional[int] = ( """This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, """ """and returns a summary of the text.""" ) __snake_case : Dict = """summarizer""" __snake_case : str = AutoTokenizer __snake_case : List[str] = AutoModelForSeqaSeqLM __snake_case : List[Any] = ["""text"""] __snake_case : Dict = ["""text"""] def __lowercase ( self :int , __lowercase :List[Any] ): return self.pre_processor(__lowercase , return_tensors='''pt''' , truncation=__lowercase ) def __lowercase ( self :Optional[int] , __lowercase :Optional[int] ): return self.model.generate(**__lowercase )[0] def __lowercase ( self :List[Any] , __lowercase :str ): return self.pre_processor.decode(__lowercase , skip_special_tokens=__lowercase , clean_up_tokenization_spaces=__lowercase )
179
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available A = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
701
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self , __UpperCamelCase , __UpperCamelCase=13 , __UpperCamelCase=32 , __UpperCamelCase=2 , __UpperCamelCase=3 , __UpperCamelCase=16 , __UpperCamelCase=[1, 2, 1] , __UpperCamelCase=[2, 2, 4] , __UpperCamelCase=2 , __UpperCamelCase=2.0 , __UpperCamelCase=True , __UpperCamelCase=0.0 , __UpperCamelCase=0.0 , __UpperCamelCase=0.1 , __UpperCamelCase="gelu" , __UpperCamelCase=False , __UpperCamelCase=True , __UpperCamelCase=0.02 , __UpperCamelCase=1E-5 , __UpperCamelCase=True , __UpperCamelCase=None , __UpperCamelCase=True , __UpperCamelCase=10 , __UpperCamelCase=8 , ): """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = embed_dim snake_case_ = depths snake_case_ = num_heads snake_case_ = window_size snake_case_ = mlp_ratio snake_case_ = qkv_bias snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = drop_path_rate snake_case_ = hidden_act snake_case_ = use_absolute_embeddings snake_case_ = patch_norm snake_case_ = layer_norm_eps snake_case_ = initializer_range snake_case_ = is_training snake_case_ = scope snake_case_ = use_labels snake_case_ = type_sequence_label_size snake_case_ = encoder_stride def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ): """simple docstring""" return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowerCAmelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" snake_case_ = SwinvaModel(config=__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() snake_case_ = model(__UpperCamelCase ) snake_case_ = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) snake_case_ = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def __lowerCAmelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" snake_case_ = SwinvaForMaskedImageModeling(config=__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() snake_case_ = model(__UpperCamelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images snake_case_ = 1 snake_case_ = SwinvaForMaskedImageModeling(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() snake_case_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ = model(__UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowerCAmelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" snake_case_ = self.type_sequence_label_size snake_case_ = SwinvaForImageClassification(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() snake_case_ = model(__UpperCamelCase , labels=__UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): """simple docstring""" __A = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) __A = ( {"""feature-extraction""": SwinvaModel, """image-classification""": SwinvaForImageClassification} if is_torch_available() else {} ) __A = False __A = False __A = False __A = False def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ = SwinvaModelTester(self ) snake_case_ = ConfigTester(self , config_class=__UpperCamelCase , embed_dim=37 ) def __lowerCAmelCase ( self ): """simple docstring""" 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 ): """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCamelCase ) @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.' ) def __lowerCAmelCase ( self ): """simple docstring""" pass @unittest.skip(reason='Swinv2 does not use inputs_embeds' ) def __lowerCAmelCase ( self ): """simple docstring""" pass def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(__UpperCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__UpperCamelCase , nn.Linear ) ) def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(__UpperCamelCase ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ['pixel_values'] self.assertListEqual(arg_names[:1] , __UpperCamelCase ) def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = True for model_class in self.all_model_classes: snake_case_ = True snake_case_ = False snake_case_ = True snake_case_ = model_class(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) snake_case_ = outputs.attentions snake_case_ = len(self.model_tester.depths ) self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase ) # check that output_attentions also work using config del inputs_dict["output_attentions"] snake_case_ = True snake_case_ = config.window_size**2 snake_case_ = model_class(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) snake_case_ = outputs.attentions self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) snake_case_ = len(__UpperCamelCase ) # Check attention is always last and order is fine snake_case_ = True snake_case_ = True snake_case_ = model_class(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) if hasattr(self.model_tester , 'num_hidden_states_types' ): snake_case_ = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states snake_case_ = 2 self.assertEqual(out_len + added_hidden_states , len(__UpperCamelCase ) ) snake_case_ = outputs.attentions self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def __lowerCAmelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" snake_case_ = model_class(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) snake_case_ = outputs.hidden_states snake_case_ = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase ) # Swinv2 has a different seq_length snake_case_ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case_ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) snake_case_ = outputs.reshaped_hidden_states self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase ) snake_case_ , snake_case_ , snake_case_ , snake_case_ = reshaped_hidden_states[0].shape snake_case_ = ( reshaped_hidden_states[0].view(__UpperCamelCase , __UpperCamelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: snake_case_ = True self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = 3 snake_case_ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) snake_case_ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case_ = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) snake_case_ = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: snake_case_ = True self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , (padded_height, padded_width) ) def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__UpperCamelCase ) def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase ) @slow def __lowerCAmelCase ( self ): """simple docstring""" for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = SwinvaModel.from_pretrained(__UpperCamelCase ) self.assertIsNotNone(__UpperCamelCase ) def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = _config_zero_init(__UpperCamelCase ) for model_class in self.all_model_classes: snake_case_ = model_class(config=__UpperCamelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @require_vision @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" @cached_property def __lowerCAmelCase ( self ): """simple docstring""" return ( AutoImageProcessor.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ = SwinvaForImageClassification.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ).to( __UpperCamelCase ) snake_case_ = self.default_image_processor snake_case_ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) snake_case_ = image_processor(images=__UpperCamelCase , return_tensors='pt' ).to(__UpperCamelCase ) # forward pass with torch.no_grad(): snake_case_ = model(**__UpperCamelCase ) # verify the logits snake_case_ = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , __UpperCamelCase ) snake_case_ = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(__UpperCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCamelCase , atol=1E-4 ) )
46
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a_ = logging.get_logger(__name__) def __lowercase ( snake_case_ : List[str] ) ->Optional[int]: '''simple docstring''' if isinstance(UpperCamelCase_ ,(list, tuple) ) and isinstance(videos[0] ,(list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(UpperCamelCase_ ,(list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(UpperCamelCase_ ): return [[videos]] raise ValueError(F"""Could not make batched video from {videos}""" ) class __snake_case ( _a ): """simple docstring""" _lowerCamelCase = ["""pixel_values"""] def __init__( self , __lowerCamelCase = True , __lowerCamelCase = None , __lowerCamelCase = PILImageResampling.BILINEAR , __lowerCamelCase = True , __lowerCamelCase = None , __lowerCamelCase = True , __lowerCamelCase = 1 / 255 , __lowerCamelCase = True , __lowerCamelCase = True , __lowerCamelCase = None , __lowerCamelCase = None , **__lowerCamelCase , ): '''simple docstring''' super().__init__(**_UpperCAmelCase ) __A : int = size if size is not None else {"""shortest_edge""": 256} __A : Any = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase ) __A : Dict = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __A : List[Any] = get_size_dict(_UpperCAmelCase , param_name='''crop_size''' ) __A : Dict = do_resize __A : Optional[int] = size __A : List[Any] = do_center_crop __A : int = crop_size __A : Union[str, Any] = resample __A : str = do_rescale __A : Any = rescale_factor __A : Any = offset __A : int = do_normalize __A : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __A : List[Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = PILImageResampling.BILINEAR , __lowerCamelCase = None , **__lowerCamelCase , ): '''simple docstring''' __A : int = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase ) if "shortest_edge" in size: __A : Any = get_resize_output_image_size(_UpperCAmelCase , size['''shortest_edge'''] , default_to_square=_UpperCAmelCase ) elif "height" in size and "width" in size: __A : List[Any] = (size["""height"""], size["""width"""]) else: raise ValueError(F"""Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) return resize(_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , **__lowerCamelCase , ): '''simple docstring''' __A : List[str] = get_size_dict(_UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(F"""Size must have 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(_UpperCAmelCase , size=(size['''height'''], size['''width''']) , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = True , __lowerCamelCase = None , **__lowerCamelCase , ): '''simple docstring''' __A : Dict = image.astype(np.floataa ) if offset: __A : Any = image - (scale / 2) return rescale(_UpperCAmelCase , scale=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , **__lowerCamelCase , ): '''simple docstring''' return normalize(_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = ChannelDimension.FIRST , ): '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''' ) # All transformations expect numpy arrays. __A : int = to_numpy_array(_UpperCAmelCase ) if do_resize: __A : Optional[int] = self.resize(image=_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase ) if do_center_crop: __A : Tuple = self.center_crop(_UpperCAmelCase , size=_UpperCAmelCase ) if do_rescale: __A : List[str] = self.rescale(image=_UpperCAmelCase , scale=_UpperCAmelCase , offset=_UpperCAmelCase ) if do_normalize: __A : List[str] = self.normalize(image=_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase ) __A : Optional[int] = to_channel_dimension_format(_UpperCAmelCase , _UpperCAmelCase ) return image def UpperCamelCase__( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = ChannelDimension.FIRST , **__lowerCamelCase , ): '''simple docstring''' __A : Tuple = do_resize if do_resize is not None else self.do_resize __A : Tuple = resample if resample is not None else self.resample __A : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop __A : Dict = do_rescale if do_rescale is not None else self.do_rescale __A : str = rescale_factor if rescale_factor is not None else self.rescale_factor __A : str = offset if offset is not None else self.offset __A : List[Any] = do_normalize if do_normalize is not None else self.do_normalize __A : Union[str, Any] = image_mean if image_mean is not None else self.image_mean __A : Optional[int] = image_std if image_std is not None else self.image_std __A : Optional[Any] = size if size is not None else self.size __A : str = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase ) __A : Dict = crop_size if crop_size is not None else self.crop_size __A : Any = get_size_dict(_UpperCAmelCase , param_name='''crop_size''' ) 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.''' ) __A : Optional[int] = make_batched(_UpperCAmelCase ) __A : str = [ [ self._preprocess_image( image=_UpperCAmelCase , do_resize=_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase , do_center_crop=_UpperCAmelCase , crop_size=_UpperCAmelCase , do_rescale=_UpperCAmelCase , rescale_factor=_UpperCAmelCase , offset=_UpperCAmelCase , do_normalize=_UpperCAmelCase , image_mean=_UpperCAmelCase , image_std=_UpperCAmelCase , data_format=_UpperCAmelCase , ) for img in video ] for video in videos ] __A : Dict = {"""pixel_values""": videos} return BatchFeature(data=_UpperCAmelCase , tensor_type=_UpperCAmelCase )
177
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : List[str] = logging.get_logger(__name__) _lowerCamelCase : Optional[int] = {} class __snake_case (_a ): lowerCAmelCase__ = "llama" lowerCAmelCase__ = ["past_key_values"] def __init__( self : str , _UpperCAmelCase : Optional[int]=3_2000 , _UpperCAmelCase : Union[str, Any]=4096 , _UpperCAmelCase : Union[str, Any]=1_1008 , _UpperCAmelCase : str=32 , _UpperCAmelCase : List[str]=32 , _UpperCAmelCase : List[str]=None , _UpperCAmelCase : Optional[Any]="silu" , _UpperCAmelCase : Union[str, Any]=2048 , _UpperCAmelCase : Optional[Any]=0.02 , _UpperCAmelCase : Tuple=1E-6 , _UpperCAmelCase : Optional[int]=True , _UpperCAmelCase : Tuple=0 , _UpperCAmelCase : List[Any]=1 , _UpperCAmelCase : Dict=2 , _UpperCAmelCase : Optional[int]=1 , _UpperCAmelCase : Union[str, Any]=False , _UpperCAmelCase : Tuple=None , **_UpperCAmelCase : Dict , ) -> Union[str, Any]: '''simple docstring''' _lowerCAmelCase : int = vocab_size _lowerCAmelCase : Optional[int] = max_position_embeddings _lowerCAmelCase : str = hidden_size _lowerCAmelCase : Optional[Any] = intermediate_size _lowerCAmelCase : int = num_hidden_layers _lowerCAmelCase : int = num_attention_heads # for backward compatibility if num_key_value_heads is None: _lowerCAmelCase : Union[str, Any] = num_attention_heads _lowerCAmelCase : List[str] = num_key_value_heads _lowerCAmelCase : int = hidden_act _lowerCAmelCase : int = initializer_range _lowerCAmelCase : Union[str, Any] = rms_norm_eps _lowerCAmelCase : Optional[int] = pretraining_tp _lowerCAmelCase : int = use_cache _lowerCAmelCase : str = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_UpperCAmelCase , bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , tie_word_embeddings=_UpperCAmelCase , **_UpperCAmelCase , ) def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _UpperCAmelCase ) or len(self.rope_scaling ) != 2: raise ValueError( """`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, """ f"got {self.rope_scaling}" ) _lowerCAmelCase : Union[str, Any] = self.rope_scaling.get("""type""" , _UpperCAmelCase ) _lowerCAmelCase : Optional[int] = self.rope_scaling.get("""factor""" , _UpperCAmelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(_UpperCAmelCase , _UpperCAmelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
429
0
"""simple docstring""" import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def UpperCAmelCase ( a_ ): '''simple docstring''' lowerCamelCase : Dict = botoa.client('iam' ) lowerCamelCase : Dict = { 'Version': '2012-10-17', 'Statement': [ {'Effect': 'Allow', 'Principal': {'Service': 'sagemaker.amazonaws.com'}, 'Action': 'sts:AssumeRole'} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=a_, AssumeRolePolicyDocument=json.dumps(a_, indent=2 ) ) lowerCamelCase : Tuple = { 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': [ 'sagemaker:*', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage', 'ecr:BatchCheckLayerAvailability', 'ecr:GetAuthorizationToken', 'cloudwatch:PutMetricData', 'cloudwatch:GetMetricData', 'cloudwatch:GetMetricStatistics', 'cloudwatch:ListMetrics', 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:DescribeLogStreams', 'logs:PutLogEvents', 'logs:GetLogEvents', 's3:CreateBucket', 's3:ListBucket', 's3:GetBucketLocation', 's3:GetObject', 's3:PutObject', ], 'Resource': '*', } ], } # attach policy to role iam_client.put_role_policy( RoleName=a_, PolicyName=F"""{role_name}_policy_permission""", PolicyDocument=json.dumps(a_, indent=2 ), ) except iam_client.exceptions.EntityAlreadyExistsException: print(F"""role {role_name} already exists. Using existing one""" ) def UpperCAmelCase ( a_ ): '''simple docstring''' lowerCamelCase : List[str] = botoa.client('iam' ) return iam_client.get_role(RoleName=a_ )["Role"]["Arn"] def UpperCAmelCase ( ): '''simple docstring''' lowerCamelCase : int = _ask_options( 'How do you want to authorize?', ['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) '], a_, ) lowerCamelCase : Any = None if credentials_configuration == 0: lowerCamelCase : List[Any] = _ask_field('Enter your AWS Profile name: [default] ', default='default' ) lowerCamelCase : Any = aws_profile else: print( 'Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,' '`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`' ) lowerCamelCase : Any = _ask_field('AWS Access Key ID: ' ) lowerCamelCase : Any = aws_access_key_id lowerCamelCase : Optional[Any] = _ask_field('AWS Secret Access Key: ' ) lowerCamelCase : Any = aws_secret_access_key lowerCamelCase : Optional[int] = _ask_field('Enter your AWS Region: [us-east-1]', default='us-east-1' ) lowerCamelCase : str = aws_region lowerCamelCase : List[Any] = _ask_options( 'Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?', ['Provide IAM Role name', 'Create new IAM role using credentials'], a_, ) if role_management == 0: lowerCamelCase : Union[str, Any] = _ask_field('Enter your IAM role name: ' ) else: lowerCamelCase : Union[str, Any] = 'accelerate_sagemaker_execution_role' print(F"""Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials""" ) _create_iam_role_for_sagemaker(a_ ) lowerCamelCase : Optional[Any] = _ask_field( 'Do you want to use custom Docker image? [yes/NO]: ', _convert_yes_no_to_bool, default=a_, error_message='Please enter yes or no.', ) lowerCamelCase : List[str] = None if is_custom_docker_image: lowerCamelCase : List[Any] = _ask_field('Enter your Docker image: ', lambda a_ : str(a_ ).lower() ) lowerCamelCase : List[Any] = _ask_field( 'Do you want to provide SageMaker input channels with data locations? [yes/NO]: ', _convert_yes_no_to_bool, default=a_, error_message='Please enter yes or no.', ) lowerCamelCase : Optional[int] = None if is_sagemaker_inputs_enabled: lowerCamelCase : Optional[int] = _ask_field( 'Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ', lambda a_ : str(a_ ).lower(), ) lowerCamelCase : Optional[Any] = _ask_field( 'Do you want to enable SageMaker metrics? [yes/NO]: ', _convert_yes_no_to_bool, default=a_, error_message='Please enter yes or no.', ) lowerCamelCase : str = None if is_sagemaker_metrics_enabled: lowerCamelCase : List[Any] = _ask_field( 'Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ', lambda a_ : str(a_ ).lower(), ) lowerCamelCase : Optional[Any] = _ask_options( 'What is the distributed mode?', ['No distributed training', 'Data parallelism'], _convert_sagemaker_distributed_mode, ) lowerCamelCase : Tuple = {} lowerCamelCase : List[Any] = _ask_field( 'Do you wish to optimize your script with torch dynamo?[yes/NO]:', _convert_yes_no_to_bool, default=a_, error_message='Please enter yes or no.', ) if use_dynamo: lowerCamelCase : List[str] = 'dynamo_' lowerCamelCase : int = _ask_options( 'Which dynamo backend would you like to use?', [x.lower() for x in DYNAMO_BACKENDS], _convert_dynamo_backend, default=2, ) lowerCamelCase : Dict = _ask_field( 'Do you want to customize the defaults sent to torch.compile? [yes/NO]: ', _convert_yes_no_to_bool, default=a_, error_message='Please enter yes or no.', ) if use_custom_options: lowerCamelCase : Dict = _ask_options( 'Which mode do you want to use?', a_, lambda a_ : TORCH_DYNAMO_MODES[int(a_ )], default='default', ) lowerCamelCase : Optional[Any] = _ask_field( 'Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ', _convert_yes_no_to_bool, default=a_, error_message='Please enter yes or no.', ) lowerCamelCase : Optional[Any] = _ask_field( 'Do you want to enable dynamic shape tracing? [yes/NO]: ', _convert_yes_no_to_bool, default=a_, error_message='Please enter yes or no.', ) lowerCamelCase : int = 'Which EC2 instance type you want to use for your training?' if distributed_type != SageMakerDistributedType.NO: lowerCamelCase : str = _ask_options( a_, a_, lambda a_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(a_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" lowerCamelCase : Union[str, Any] = _ask_field(a_, lambda a_ : str(a_ ).lower(), default='ml.p3.2xlarge' ) lowerCamelCase : Dict = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): lowerCamelCase : str = _ask_field( 'How many machines do you want use? [1]: ', a_, default=1, ) lowerCamelCase : Union[str, Any] = _ask_options( 'Do you wish to use FP16 or BF16 (mixed precision)?', ['no', 'fp16', 'bf16', 'fp8'], _convert_mixed_precision, ) if use_dynamo and mixed_precision == "no": print( 'Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.' ) return SageMakerConfig( image_uri=a_, compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER, distributed_type=a_, use_cpu=a_, dynamo_config=a_, eca_instance_type=a_, profile=a_, region=a_, iam_role_name=a_, mixed_precision=a_, num_machines=a_, sagemaker_inputs_file=a_, sagemaker_metrics_file=a_, )
720
"""simple docstring""" from math import ceil def UpperCAmelCase ( a_ = 1001 ): '''simple docstring''' lowerCamelCase : Optional[Any] = 1 for i in range(1, int(ceil(n / 2.0 ) ) ): lowerCamelCase : int = 2 * i + 1 lowerCamelCase : int = 2 * i lowerCamelCase : Optional[Any] = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: _A = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number')
133
0
import argparse import copy def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = {} with open(lowercase ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: SCREAMING_SNAKE_CASE : List[str] = [] _list.append([line.split()[1], line.split()[2]] ) SCREAMING_SNAKE_CASE : Optional[int] = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: SCREAMING_SNAKE_CASE : List[str] = [] _list.append([line.split()[0], line.split()[2]] ) SCREAMING_SNAKE_CASE : List[Any] = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" with open(lowercase ) as f: SCREAMING_SNAKE_CASE : str = f.read(1 ) SCREAMING_SNAKE_CASE : List[Any] = start_node SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : Optional[Any] = start_node SCREAMING_SNAKE_CASE : Optional[Any] = 0 while visiting not in first_solution: SCREAMING_SNAKE_CASE : Dict = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(lowercase ) and k[0] not in first_solution: SCREAMING_SNAKE_CASE : Union[str, Any] = k[1] SCREAMING_SNAKE_CASE : List[str] = k[0] first_solution.append(lowercase ) SCREAMING_SNAKE_CASE : int = distance_of_first_solution + int(lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = best_node first_solution.append(lowercase ) SCREAMING_SNAKE_CASE : List[Any] = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 SCREAMING_SNAKE_CASE : Any = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = [] for n in solution[1:-1]: SCREAMING_SNAKE_CASE : Optional[Any] = solution.index(lowercase ) for kn in solution[1:-1]: SCREAMING_SNAKE_CASE : Optional[Any] = solution.index(lowercase ) if n == kn: continue SCREAMING_SNAKE_CASE : Optional[Any] = copy.deepcopy(lowercase ) SCREAMING_SNAKE_CASE : Tuple = kn SCREAMING_SNAKE_CASE : List[Any] = n SCREAMING_SNAKE_CASE : str = 0 for k in _tmp[:-1]: SCREAMING_SNAKE_CASE : List[Any] = _tmp[_tmp.index(lowercase ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: SCREAMING_SNAKE_CASE : Tuple = distance + int(i[1] ) _tmp.append(lowercase ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) SCREAMING_SNAKE_CASE : Optional[int] = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda lowercase : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = 1 SCREAMING_SNAKE_CASE : Dict = first_solution SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Optional[int] = distance_of_first_solution SCREAMING_SNAKE_CASE : int = solution while count <= iters: SCREAMING_SNAKE_CASE : Optional[Any] = find_neighborhood(lowercase , lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : List[Any] = neighborhood[index_of_best_solution] SCREAMING_SNAKE_CASE : Optional[Any] = len(lowercase ) - 1 SCREAMING_SNAKE_CASE : Dict = False while not found: SCREAMING_SNAKE_CASE : Dict = 0 while i < len(lowercase ): if best_solution[i] != solution[i]: SCREAMING_SNAKE_CASE : int = best_solution[i] SCREAMING_SNAKE_CASE : str = solution[i] break SCREAMING_SNAKE_CASE : Tuple = 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] ) SCREAMING_SNAKE_CASE : Any = True SCREAMING_SNAKE_CASE : Dict = best_solution[:-1] SCREAMING_SNAKE_CASE : int = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: SCREAMING_SNAKE_CASE : Any = cost SCREAMING_SNAKE_CASE : int = solution else: SCREAMING_SNAKE_CASE : int = index_of_best_solution + 1 SCREAMING_SNAKE_CASE : Tuple = neighborhood[index_of_best_solution] if len(lowercase ) >= size: tabu_list.pop(0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = count + 1 return best_solution_ever, best_cost def lowerCamelCase__ ( lowercase=None ): """simple docstring""" SCREAMING_SNAKE_CASE : str = generate_neighbours(args.File ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = generate_first_solution( args.File , lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = tabu_search( lowercase , lowercase , lowercase , args.Iterations , args.Size , ) print(F'''Best solution: {best_sol}, with total distance: {best_cost}.''' ) if __name__ == "__main__": snake_case = 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())
62
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''xlm-prophetnet''' UpperCamelCase_ : Tuple = ['''past_key_values'''] UpperCamelCase_ : int = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : Dict , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[Union[str, Callable]] = "gelu" , UpperCAmelCase_ : Optional[int] = 3_0522 , UpperCAmelCase_ : Optional[int] = 1024 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[int] = 4096 , UpperCAmelCase_ : Optional[int] = 12 , UpperCAmelCase_ : Optional[int] = 16 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[float] = 0.1 , UpperCAmelCase_ : Optional[int] = 512 , UpperCAmelCase_ : Optional[float] = 0.02 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 2 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 128 , UpperCAmelCase_ : Optional[bool] = False , UpperCAmelCase_ : Optional[float] = 0.0 , UpperCAmelCase_ : Optional[bool] = True , UpperCAmelCase_ : Optional[int] = 0 , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : Optional[int] = 2 , **UpperCAmelCase_ : Dict , ): SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : Tuple = encoder_ffn_dim SCREAMING_SNAKE_CASE : List[Any] = num_encoder_layers SCREAMING_SNAKE_CASE : Any = num_encoder_attention_heads SCREAMING_SNAKE_CASE : Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE : List[str] = num_decoder_layers SCREAMING_SNAKE_CASE : List[Any] = num_decoder_attention_heads SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = init_std # Normal(0, this parameter) SCREAMING_SNAKE_CASE : Union[str, Any] = activation_function # parameters for xlmprophetnet SCREAMING_SNAKE_CASE : Dict = ngram SCREAMING_SNAKE_CASE : Any = num_buckets SCREAMING_SNAKE_CASE : str = relative_max_distance SCREAMING_SNAKE_CASE : str = disable_ngram_loss SCREAMING_SNAKE_CASE : Dict = eps # 3 Types of Dropout SCREAMING_SNAKE_CASE : Union[str, Any] = attention_dropout SCREAMING_SNAKE_CASE : Optional[int] = activation_dropout SCREAMING_SNAKE_CASE : List[Any] = dropout SCREAMING_SNAKE_CASE : int = use_cache super().__init__( pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , add_cross_attention=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) @property def _A ( self : int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`." )
62
1
import sys import turtle def _lowerCamelCase( lowerCAmelCase__ : tuple[float, float] , lowerCAmelCase__ : tuple[float, float] ): '''simple docstring''' return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def _lowerCamelCase( lowerCAmelCase__ : tuple[float, float] , lowerCAmelCase__ : tuple[float, float] , lowerCAmelCase__ : tuple[float, float] , lowerCAmelCase__ : int , ): '''simple docstring''' my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(lowerCAmelCase__ , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , depth - 1 ) triangle(lowerCAmelCase__ , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , depth - 1 ) triangle(lowerCAmelCase__ , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) A = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') A = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
97
from timeit import timeit def _lowerCamelCase( lowerCAmelCase__ : int ): '''simple docstring''' if number < 0: raise ValueError('the value of input must not be negative' ) SCREAMING_SNAKE_CASE_ : Tuple = 0 while number: number &= number - 1 result += 1 return result def _lowerCamelCase( lowerCAmelCase__ : int ): '''simple docstring''' if number < 0: raise ValueError('the value of input must not be negative' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def _lowerCamelCase( ): '''simple docstring''' def do_benchmark(lowerCAmelCase__ : int ) -> None: SCREAMING_SNAKE_CASE_ : int = 'import __main__ as z' print(F'''Benchmark when {number = }:''' ) print(F'''{get_set_bits_count_using_modulo_operator(lowerCAmelCase__ ) = }''' ) SCREAMING_SNAKE_CASE_ : int = timeit('z.get_set_bits_count_using_modulo_operator(25)' , setup=lowerCAmelCase__ ) print(F'''timeit() runs in {timing} seconds''' ) print(F'''{get_set_bits_count_using_brian_kernighans_algorithm(lowerCAmelCase__ ) = }''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = timeit( 'z.get_set_bits_count_using_brian_kernighans_algorithm(25)' , setup=lowerCAmelCase__ , ) print(F'''timeit() runs in {timing} seconds''' ) for number in (25, 37, 58, 0): do_benchmark(lowerCAmelCase__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
97
1
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def _lowerCAmelCase ( __magic_name__ : Tuple , __magic_name__ : Tuple , __magic_name__ : int=None , __magic_name__ : Dict=None ) -> List[Any]: if attention_mask is None: lowercase : Tuple =tf.cast(tf.math.not_equal(__magic_name__ , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class __SCREAMING_SNAKE_CASE : lowerCamelCase_ = OPTConfig lowerCamelCase_ = {} lowerCamelCase_ = 'gelu' def __init__( self : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str]=13 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : str=99 , UpperCAmelCase__ : Tuple=16 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : List[Any]=4 , UpperCAmelCase__ : Optional[Any]="gelu" , UpperCAmelCase__ : str=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Any=20 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : int=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : Dict=16 , UpperCAmelCase__ : List[str]=16 , ): '''simple docstring''' lowercase : Optional[int] =parent lowercase : Tuple =batch_size lowercase : Optional[int] =seq_length lowercase : List[Any] =is_training lowercase : Tuple =use_labels lowercase : Any =vocab_size lowercase : Any =hidden_size lowercase : List[str] =num_hidden_layers lowercase : Dict =num_attention_heads lowercase : Dict =intermediate_size lowercase : Tuple =hidden_act lowercase : List[str] =hidden_dropout_prob lowercase : Tuple =attention_probs_dropout_prob lowercase : Optional[int] =max_position_embeddings lowercase : List[Any] =eos_token_id lowercase : Optional[int] =pad_token_id lowercase : Dict =bos_token_id lowercase : Dict =embed_dim lowercase : int =word_embed_proj_dim lowercase : Dict =False def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' lowercase : Dict =ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowercase : Union[str, Any] =tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowercase : Dict =tf.concat([input_ids, eos_tensor] , axis=1 ) lowercase : Any =self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=UpperCAmelCase__ , **self.config_updates , ) lowercase : Optional[int] =prepare_opt_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ ) return config, inputs_dict def lowerCamelCase_ ( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ): '''simple docstring''' lowercase : Tuple =TFOPTModel(config=UpperCAmelCase__ ) lowercase : int =inputs_dict['''input_ids'''] lowercase : List[str] =input_ids[:1, :] lowercase : Dict =inputs_dict['''attention_mask'''][:1, :] lowercase : Union[str, Any] =1 # first forward pass lowercase : Optional[Any] =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) lowercase , lowercase : str =outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowercase : Any =ids_tensor((self.batch_size, 3) , config.vocab_size ) lowercase : List[Any] =tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and lowercase : Optional[int] =tf.concat([input_ids, next_tokens] , axis=-1 ) lowercase : List[Any] =tf.concat([attention_mask, next_attn_mask] , axis=-1 ) lowercase : int =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] lowercase : Optional[Any] =model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice lowercase : Optional[Any] =int(ids_tensor((1,) , output_from_past.shape[-1] ) ) lowercase : Optional[int] =output_from_no_past[:, -3:, random_slice_idx] lowercase : Optional[int] =output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(UpperCAmelCase__ , UpperCAmelCase__ , rtol=1E-3 ) @require_tf class __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ , unittest.TestCase ): lowerCamelCase_ = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () lowerCamelCase_ = (TFOPTForCausalLM,) if is_tf_available() else () lowerCamelCase_ = ( {'feature-extraction': TFOPTModel, 'text-generation': TFOPTForCausalLM} if is_tf_available() else {} ) lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = 10 def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : Any =TFOPTModelTester(self ) lowercase : Tuple =ConfigTester(self , config_class=UpperCAmelCase__ ) def lowerCamelCase_ ( self : str ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase_ ( self : Dict ): '''simple docstring''' lowercase : Any =self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' lowercase , lowercase : Dict =self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] ): if hasattr(UpperCAmelCase__ , '''weight''' ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(UpperCAmelCase__ , '''weight''' ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 10, config.vocab_size + 10]: # build the embeddings lowercase : int =model_class(config=UpperCAmelCase__ ) lowercase : str =_get_word_embedding_weight(UpperCAmelCase__ , model.get_input_embeddings() ) lowercase : List[str] =_get_word_embedding_weight(UpperCAmelCase__ , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(UpperCAmelCase__ ) lowercase : Tuple =_get_word_embedding_weight(UpperCAmelCase__ , model.get_input_embeddings() ) lowercase : Optional[Any] =_get_word_embedding_weight(UpperCAmelCase__ , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. lowercase : Any =size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , UpperCAmelCase__ ) # check that weights remain the same after resizing lowercase : int =True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: lowercase : Optional[Any] =False self.assertTrue(UpperCAmelCase__ ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , UpperCAmelCase__ ) lowercase : Optional[int] =True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: lowercase : Any =False self.assertTrue(UpperCAmelCase__ ) def _lowerCAmelCase ( __magic_name__ : List[str] ) -> Tuple: return tf.constant(__magic_name__ , dtype=tf.intaa ) @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): lowerCamelCase_ = 99 def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : Optional[Any] =tf.ones((4, 1) , dtype=tf.intaa ) * 2 lowercase : List[Any] =tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) lowercase : List[Any] =input_ids.shape[0] lowercase : str =OPTConfig( vocab_size=self.vocab_size , hidden_size=24 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' lowercase : Tuple =TFOPTModel.from_pretrained('''facebook/opt-350m''' ) lowercase : Optional[int] =_long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) lowercase : Any =tf.not_equal(UpperCAmelCase__ , model.config.pad_token_id ) with tf.GradientTape(): lowercase : List[Any] =model(input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ).last_hidden_state lowercase : Tuple =(1, 11, 512) self.assertEqual(output.shape , UpperCAmelCase__ ) lowercase : Union[str, Any] =tf.constant( [[-0.28_73, -1.92_18, -0.30_33], [-1.27_10, -0.13_38, -0.19_02], [0.40_95, 0.12_14, -1.31_21]] ) self.assertTrue(np.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=4E-3 ) ) lowercase : str =tf.function(UpperCAmelCase__ , jit_compile=UpperCAmelCase__ ) lowercase : Tuple =xla_generate(UpperCAmelCase__ , UpperCAmelCase__ )[0] self.assertTrue(np.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=4E-2 ) ) @require_tf @slow class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def lowerCamelCase_ ( self : Any ): '''simple docstring''' super().setUp() lowercase : int ='''facebook/opt-350m''' def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' lowercase : Any =TFOPTForCausalLM.from_pretrained(self.path_model ) lowercase : Dict =GPTaTokenizer.from_pretrained(self.path_model ) lowercase : int =[ '''Today is a beautiful day and I want to''', '''In the city of''', '''Paris is the capital of France and''', '''Computers and mobile phones have taken''', ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False lowercase : List[Any] =tokenizer(UpperCAmelCase__ , return_tensors='''tf''' , padding=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) lowercase : List[Any] =tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) lowercase : List[Any] =tf.constant( [ [1.38_51, -13.89_23, -10.52_29, -10.75_33, -0.23_09, -10.23_84, -0.53_65, -9.09_47, -5.16_70], [-4.70_73, -10.62_76, -3.94_15, -21.52_42, -0.28_22, -0.28_22, -0.28_22, -0.28_22, -0.28_22], [0.62_47, -3.42_29, -8.91_79, -1.42_97, -14.16_50, 1.41_46, -9.02_18, -0.27_03, -0.27_03], [6.47_83, -1.99_13, -10.79_26, -2.33_36, 1.50_92, -0.99_74, -6.82_13, 1.34_77, 1.34_77], ] ) self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-4 ) ) lowercase : Optional[int] =tf.function(UpperCAmelCase__ , jit_compile=UpperCAmelCase__ ) lowercase : Union[str, Any] =tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-4 ) ) @require_tf @slow class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @property def lowerCamelCase_ ( self : Any ): '''simple docstring''' return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' lowercase : int ='''facebook/opt-125m''' lowercase : Tuple =[ '''Today is a beautiful day and I want to''', '''In the city of New York, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] lowercase : Dict =[] lowercase : List[Any] =GPTaTokenizer.from_pretrained(UpperCAmelCase__ ) lowercase : str =TFOPTForCausalLM.from_pretrained(UpperCAmelCase__ ) for prompt in self.prompts: lowercase : Optional[int] =tokenizer(UpperCAmelCase__ , return_tensors='''tf''' ).input_ids lowercase : Optional[Any] =model.generate(UpperCAmelCase__ , max_length=10 ) lowercase : Union[str, Any] =tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) predicted_outputs += generated_string self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' lowercase : Tuple ='''facebook/opt-350m''' lowercase : str =GPTaTokenizer.from_pretrained(UpperCAmelCase__ ) lowercase : Optional[int] =TFOPTForCausalLM.from_pretrained(UpperCAmelCase__ ) lowercase : Union[str, Any] ='''left''' # use different length sentences to test batching lowercase : Tuple =[ '''Hello, my dog is a little''', '''Today, I''', ] lowercase : Union[str, Any] =tokenizer(UpperCAmelCase__ , return_tensors='''tf''' , padding=UpperCAmelCase__ ) lowercase : int =inputs['''input_ids'''] lowercase : Dict =model.generate(input_ids=UpperCAmelCase__ , attention_mask=inputs['''attention_mask'''] ) lowercase : Any =tokenizer(sentences[0] , return_tensors='''tf''' ).input_ids lowercase : Dict =model.generate(input_ids=UpperCAmelCase__ ) lowercase : str =inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs['''attention_mask'''][-1] , tf.intaa ) ) lowercase : int =tokenizer(sentences[1] , return_tensors='''tf''' ).input_ids lowercase : Union[str, Any] =model.generate(input_ids=UpperCAmelCase__ , max_length=model.config.max_length - num_paddings ) lowercase : Union[str, Any] =tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) lowercase : Any =tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCAmelCase__ ) lowercase : Dict =tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCAmelCase__ ) lowercase : Dict =[ '''Hello, my dog is a little bit of a dork.\nI\'m a little bit''', '''Today, I was in the middle of a conversation with a friend about the''', ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [non_padded_sentence, padded_sentence] ) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : List[str] ='''facebook/opt-350m''' lowercase : Any =[ '''Today is a beautiful day and I want to''', '''In the city of San Francisco, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] lowercase : List[Any] =[] lowercase : Tuple =GPTaTokenizer.from_pretrained(UpperCAmelCase__ ) lowercase : List[Any] =TFOPTForCausalLM.from_pretrained(UpperCAmelCase__ ) for prompt in self.prompts: lowercase : Optional[Any] =tokenizer(UpperCAmelCase__ , return_tensors='''tf''' ).input_ids lowercase : int =model.generate(UpperCAmelCase__ , max_length=10 ) lowercase : Any =tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) predicted_outputs += generated_string self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
92
'''simple docstring''' from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. UpperCamelCase_ = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. UpperCamelCase_ = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. UpperCamelCase_ = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : str ) -> tuple[str, float]: lowercase : int =len([g for position, g in enumerate(__magic_name__ ) if g == main_target[position]] ) return (item, float(__magic_name__ )) def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : str ) -> tuple[str, str]: lowercase : Any =random.randint(0 , len(__magic_name__ ) - 1 ) lowercase : Tuple =parent_a[:random_slice] + parent_a[random_slice:] lowercase : List[str] =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : list[str] ) -> str: lowercase : Union[str, Any] =list(__magic_name__ ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: lowercase : Dict =random.choice(__magic_name__ ) return "".join(__magic_name__ ) def _lowerCAmelCase ( __magic_name__ : tuple[str, float] , __magic_name__ : list[tuple[str, float]] , __magic_name__ : list[str] , ) -> list[str]: lowercase : Any =[] # Generate more children proportionally to the fitness score. lowercase : Dict =int(parent_a[1] * 100 ) + 1 lowercase : List[str] =10 if child_n >= 10 else child_n for _ in range(__magic_name__ ): lowercase : List[str] =population_score[random.randint(0 , __magic_name__ )][0] lowercase , lowercase : Dict =crossover(parent_a[0] , __magic_name__ ) # Append new string to the population list. pop.append(mutate(__magic_name__ , __magic_name__ ) ) pop.append(mutate(__magic_name__ , __magic_name__ ) ) return pop def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : list[str] , __magic_name__ : bool = True ) -> tuple[int, int, str]: # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: lowercase : List[str] =f'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(__magic_name__ ) # Verify that the target contains no genes besides the ones inside genes variable. lowercase : Optional[int] =sorted({c for c in target if c not in genes} ) if not_in_genes_list: lowercase : Dict =f'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(__magic_name__ ) # Generate random starting population. lowercase : int =[] for _ in range(__magic_name__ ): population.append(''''''.join([random.choice(__magic_name__ ) for i in range(len(__magic_name__ ) )] ) ) # Just some logs to know what the algorithms is doing. lowercase , lowercase : Optional[int] =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(__magic_name__ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. lowercase : List[str] =[evaluate(__magic_name__ , __magic_name__ ) for item in population] # Check if there is a matching evolution. lowercase : int =sorted(__magic_name__ , key=lambda __magic_name__ : x[1] , reverse=__magic_name__ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f'''\nGeneration: {generation}''' f'''\nTotal Population:{total_population}''' f'''\nBest score: {population_score[0][1]}''' f'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. lowercase : Any =population[: int(N_POPULATION / 3 )] population.clear() population.extend(__magic_name__ ) # Normalize population score to be between 0 and 1. lowercase : Dict =[ (item, score / len(__magic_name__ )) for item, score in population_score ] # This is selection for i in range(__magic_name__ ): population.extend(select(population_score[int(__magic_name__ )] , __magic_name__ , __magic_name__ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(__magic_name__ ) > N_POPULATION: break if __name__ == "__main__": UpperCamelCase_ = ( """This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!""" ) UpperCamelCase_ = list( """ ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm""" """nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\""" ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = basic(target_str, genes_list) print( f'''\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}''' )
92
1
'''simple docstring''' from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def lowerCAmelCase__ ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = None ): """simple docstring""" if version.parse(hfh.__version__ ).release < version.parse("""0.11.0""" ).release: # old versions of hfh don't url-encode the file path snake_case__ : List[Any] = quote(lowerCAmelCase_ ) return hfh.hf_hub_url(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="""dataset""" , revision=lowerCAmelCase_ )
707
'''simple docstring''' import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() lowerCAmelCase__ = 2 class _A : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments lowerCamelCase : Optional[int]="<s>" , lowerCamelCase : str="<pad>" , lowerCamelCase : str="</s>" , lowerCamelCase : int="<unk>" , lowerCamelCase : Tuple=None , )-> str: snake_case__ , snake_case__ , snake_case__ , snake_case__ : Dict = bos, unk, pad, eos snake_case__ : Dict = [] snake_case__ : int = [] snake_case__ : Optional[int] = {} snake_case__ : int = self.add_symbol(lowerCamelCase ) snake_case__ : Optional[int] = self.add_symbol(lowerCamelCase ) snake_case__ : List[str] = self.add_symbol(lowerCamelCase ) snake_case__ : int = self.add_symbol(lowerCamelCase ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(lowerCamelCase ) snake_case__ : int = len(self.symbols ) def __eq__( self : str , lowerCamelCase : Tuple )-> Optional[Any]: return self.indices == other.indices def __getitem__( self : Optional[int] , lowerCamelCase : Any )-> Tuple: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : Any )-> Union[str, Any]: return len(self.symbols ) def __contains__( self : Tuple , lowerCamelCase : int )-> int: return sym in self.indices @classmethod def __lowerCAmelCase ( cls : Dict , lowerCamelCase : Union[str, Any] )-> str: snake_case__ : List[str] = cls() d.add_from_file(lowerCamelCase ) return d def __lowerCAmelCase ( self : int , lowerCamelCase : int , lowerCamelCase : List[Any]=1 , lowerCamelCase : Union[str, Any]=False )-> Any: if word in self.indices and not overwrite: snake_case__ : Union[str, Any] = self.indices[word] snake_case__ : str = self.count[idx] + n return idx else: snake_case__ : Any = len(self.symbols ) snake_case__ : Optional[int] = idx self.symbols.append(lowerCamelCase ) self.count.append(lowerCamelCase ) return idx def __lowerCAmelCase ( self : Any , lowerCamelCase : List[Any] )-> Dict: return 0 def __lowerCAmelCase ( self : int , lowerCamelCase : str )-> Optional[int]: if isinstance(lowerCamelCase , lowerCamelCase ): try: with open(lowerCamelCase , """r""" , encoding="""utf-8""" ) as fd: self.add_from_file(lowerCamelCase ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception("""Incorrect encoding detected in {}, please rebuild the dataset""".format(lowerCamelCase ) ) return snake_case__ : Union[str, Any] = f.readlines() snake_case__ : Optional[Any] = self._load_meta(lowerCamelCase ) for line in lines[indices_start_line:]: try: snake_case__ , snake_case__ : Optional[int] = line.rstrip().rsplit(""" """ , 1 ) if field == "#fairseq:overwrite": snake_case__ : str = True snake_case__ , snake_case__ : Any = line.rsplit(""" """ , 1 ) else: snake_case__ : Dict = False snake_case__ : Optional[int] = int(lowerCamelCase ) snake_case__ : List[str] = line if word in self and not overwrite: raise RuntimeError( """Duplicate word found when loading Dictionary: '{}'. """ """Duplicate words can overwrite earlier ones by adding the """ """#fairseq:overwrite flag at the end of the corresponding row """ """in the dictionary file. If using the Camembert model, please """ """download an updated copy of the model file.""".format(lowerCamelCase ) ) self.add_symbol(lowerCamelCase , n=lowerCamelCase , overwrite=lowerCamelCase ) except ValueError: raise ValueError("""Incorrect dictionary format, expected '<token> <cnt> [flags]'""" ) def lowerCAmelCase__ ( UpperCAmelCase ): """simple docstring""" snake_case__ : List[str] = dict((re.sub(R"""@@$""" , """""" , UpperCAmelCase ), v) if k.endswith("""@@""" ) else (re.sub(R"""$""" , """</w>""" , UpperCAmelCase ), v) for k, v in d.items() ) snake_case__ : str = """<s> <pad> </s> <unk>""".split() # restore the special tokens for k in keep_keys: del da[f"""{k}</w>"""] snake_case__ : Optional[Any] = d[k] # restore return da def lowerCAmelCase__ ( UpperCAmelCase , UpperCAmelCase ): """simple docstring""" if not os.path.exists(UpperCAmelCase ): raise ValueError(f"""path {biogpt_checkpoint_path} does not exist!""" ) os.makedirs(UpperCAmelCase , exist_ok=UpperCAmelCase ) print(f"""Writing results to {pytorch_dump_folder_path}""" ) # handle various types of models snake_case__ : Tuple = os.path.join(UpperCAmelCase , """checkpoint.pt""" ) if not os.path.isfile(UpperCAmelCase ): raise ValueError(f"""path to the file {checkpoint_file} does not exist!""" ) snake_case__ : str = torch.load(UpperCAmelCase , map_location="""cpu""" ) snake_case__ : List[Any] = chkpt["""cfg"""]["""model"""] # dicts snake_case__ : Optional[Any] = os.path.join(UpperCAmelCase , """dict.txt""" ) if not os.path.isfile(UpperCAmelCase ): raise ValueError(f"""path to the file {dict_file} does not exist!""" ) snake_case__ : List[str] = Dictionary.load(UpperCAmelCase ) snake_case__ : Optional[int] = rewrite_dict_keys(src_dict.indices ) snake_case__ : Tuple = len(UpperCAmelCase ) snake_case__ : Optional[Any] = os.path.join(UpperCAmelCase , VOCAB_FILES_NAMES["""vocab_file"""] ) print(f"""Generating {src_vocab_file} of {src_vocab_size} records""" ) with open(UpperCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(UpperCAmelCase , ensure_ascii=UpperCAmelCase , indent=UpperCAmelCase ) ) # merges_file (bpecodes) snake_case__ : Union[str, Any] = os.path.join(UpperCAmelCase , """bpecodes""" ) if not os.path.isfile(UpperCAmelCase ): raise ValueError(f"""path to the file {bpecodes_file} does not exist!""" ) snake_case__ : Tuple = os.path.join(UpperCAmelCase , VOCAB_FILES_NAMES["""merges_file"""] ) shutil.copyfile(UpperCAmelCase , UpperCAmelCase ) # model config snake_case__ : str = os.path.join(UpperCAmelCase , """config.json""" ) snake_case__ : Dict = { """activation_dropout""": args["""activation_dropout"""], """architectures""": ["""BioGptForCausalLM"""], """attention_probs_dropout_prob""": args["""attention_dropout"""], """bos_token_id""": 0, """eos_token_id""": 2, """hidden_act""": args["""activation_fn"""], """hidden_dropout_prob""": args["""dropout"""], """hidden_size""": args["""decoder_embed_dim"""], """initializer_range""": 0.0_2, """intermediate_size""": args["""decoder_ffn_embed_dim"""], """layer_norm_eps""": 1E-1_2, """layerdrop""": args["""decoder_layerdrop"""], """max_position_embeddings""": args["""max_target_positions"""], """model_type""": """biogpt""", """num_attention_heads""": args["""decoder_attention_heads"""], """num_hidden_layers""": args["""decoder_layers"""], """pad_token_id""": 1, """scale_embedding""": not args["""no_scale_embedding"""], """tie_word_embeddings""": args["""share_decoder_input_output_embed"""], """vocab_size""": src_vocab_size, } # good hparam defaults to start with print(f"""Generating {biogpt_model_config_file}""" ) with open(UpperCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(UpperCAmelCase , ensure_ascii=UpperCAmelCase , indent=UpperCAmelCase ) ) # tokenizer config snake_case__ : int = os.path.join(UpperCAmelCase , UpperCAmelCase ) snake_case__ : List[str] = { """bos_token""": """<s>""", """eos_token""": """</s>""", """model_max_length""": 1024, """pad_token""": """<pad>""", """special_tokens_map_file""": None, """tokenizer_class""": """BioGptTokenizer""", """unk_token""": """<unk>""", } print(f"""Generating {biogpt_tokenizer_config_file}""" ) with open(UpperCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(UpperCAmelCase , ensure_ascii=UpperCAmelCase , indent=UpperCAmelCase ) ) # model snake_case__ : int = chkpt["""model"""] # remove unneeded keys snake_case__ : List[Any] = [ """decoder.version""", ] for k in ignore_keys: model_state_dict.pop(UpperCAmelCase , UpperCAmelCase ) snake_case__ : List[Any] = list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith("""output_projection.weight""" ): snake_case__ : str = model_state_dict.pop(UpperCAmelCase ) else: snake_case__ : Optional[int] = model_state_dict.pop(UpperCAmelCase ) snake_case__ : Tuple = BioGptConfig.from_pretrained(UpperCAmelCase ) snake_case__ : Optional[int] = BioGptForCausalLM(UpperCAmelCase ) # check that it loads ok model_new.load_state_dict(UpperCAmelCase ) # save snake_case__ : Dict = os.path.join(UpperCAmelCase , UpperCAmelCase ) print(f"""Generating {pytorch_weights_dump_path}""" ) torch.save(UpperCAmelCase , UpperCAmelCase ) print("""Conversion is done!""" ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--biogpt_checkpoint_path', default=None, type=str, required=True, help=( 'Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,' ' bpecodes, etc.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) lowerCAmelCase__ = parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
172
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=_UpperCamelCase ) class __lowercase ( _UpperCamelCase ): UpperCamelCase = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) UpperCamelCase = Features({'''audio''': Audio()} ) UpperCamelCase = Features({'''transcription''': Value('''string''' )} ) UpperCamelCase = '''audio''' UpperCamelCase = '''transcription''' def _lowercase ( self : str , __lowerCamelCase : Any ) -> List[Any]: """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , __lowerCamelCase ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) UpperCAmelCase = copy.deepcopy(self ) UpperCAmelCase = self.input_schema.copy() UpperCAmelCase = features[self.audio_column] UpperCAmelCase = input_schema return task_template @property def _lowercase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
377
import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput lowerCAmelCase__ = '''scheduler_config.json''' class snake_case__(_UpperCamelCase ): """simple docstring""" lowercase_ = 1 lowercase_ = 2 lowercase_ = 3 lowercase_ = 4 lowercase_ = 5 @dataclass class snake_case__(_UpperCamelCase ): """simple docstring""" lowercase_ = 42 class snake_case__: """simple docstring""" lowercase_ = SCHEDULER_CONFIG_NAME lowercase_ = ["""dtype"""] lowercase_ = [] lowercase_ = True @classmethod def snake_case ( cls : Optional[Any] , SCREAMING_SNAKE_CASE : Dict[str, Any] = None , SCREAMING_SNAKE_CASE : Optional[str] = None , SCREAMING_SNAKE_CASE : Optional[Any]=False , **SCREAMING_SNAKE_CASE : str , ): lowercase__ , lowercase__ : Union[str, Any] = cls.load_config( pretrained_model_name_or_path=SCREAMING_SNAKE_CASE , subfolder=SCREAMING_SNAKE_CASE , return_unused_kwargs=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) lowercase__ , lowercase__ : int = cls.from_config(SCREAMING_SNAKE_CASE , return_unused_kwargs=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if hasattr(SCREAMING_SNAKE_CASE , "create_state" ) and getattr(SCREAMING_SNAKE_CASE , "has_state" , SCREAMING_SNAKE_CASE ): lowercase__ : Optional[int] = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def snake_case ( self : Tuple , SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , SCREAMING_SNAKE_CASE : bool = False , **SCREAMING_SNAKE_CASE : Optional[int] ): self.save_config(save_directory=SCREAMING_SNAKE_CASE , push_to_hub=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) @property def snake_case ( self : int ): return self._get_compatibles() @classmethod def snake_case ( cls : Tuple ): lowercase__ : Optional[int] = list(set([cls.__name__] + cls._compatibles ) ) lowercase__ : List[str] = importlib.import_module(__name__.split("." )[0] ) lowercase__ : Tuple = [ getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for c in compatible_classes_str if hasattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ] return compatible_classes def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" assert len(lowerCamelCase__ ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(lowerCamelCase__ ) - x.ndim) ) , lowerCamelCase__ ) def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__=0.999 , lowerCamelCase__=jnp.floataa ): """simple docstring""" def alpha_bar(lowerCamelCase__ ): return math.cos((time_step + 0.008) / 1.008 * math.pi / 2 ) ** 2 lowercase__ : Dict = [] for i in range(lowerCamelCase__ ): lowercase__ : List[str] = i / num_diffusion_timesteps lowercase__ : Dict = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(lowerCamelCase__ ) / alpha_bar(lowerCamelCase__ ) , lowerCamelCase__ ) ) return jnp.array(lowerCamelCase__ , dtype=lowerCamelCase__ ) @flax.struct.dataclass class snake_case__: """simple docstring""" lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 @classmethod def snake_case ( cls : Union[str, Any] , SCREAMING_SNAKE_CASE : List[str] ): lowercase__ : List[Any] = scheduler.config if config.trained_betas is not None: lowercase__ : List[str] = jnp.asarray(config.trained_betas , dtype=scheduler.dtype ) elif config.beta_schedule == "linear": lowercase__ : Optional[int] = jnp.linspace(config.beta_start , config.beta_end , config.num_train_timesteps , dtype=scheduler.dtype ) elif config.beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. lowercase__ : List[str] = ( jnp.linspace( config.beta_start**0.5 , config.beta_end**0.5 , config.num_train_timesteps , dtype=scheduler.dtype ) ** 2 ) elif config.beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule lowercase__ : Any = betas_for_alpha_bar(config.num_train_timesteps , dtype=scheduler.dtype ) else: raise NotImplementedError( f"""beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}""" ) lowercase__ : Dict = 1.0 - betas lowercase__ : List[Any] = jnp.cumprod(SCREAMING_SNAKE_CASE , axis=0 ) return cls( alphas=SCREAMING_SNAKE_CASE , betas=SCREAMING_SNAKE_CASE , alphas_cumprod=SCREAMING_SNAKE_CASE , ) def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" lowercase__ : Tuple = state.alphas_cumprod lowercase__ : int = alphas_cumprod[timesteps] ** 0.5 lowercase__ : Optional[int] = sqrt_alpha_prod.flatten() lowercase__ : Tuple = broadcast_to_shape_from_left(lowerCamelCase__ , original_samples.shape ) lowercase__ : List[str] = (1 - alphas_cumprod[timesteps]) ** 0.5 lowercase__ : Union[str, Any] = sqrt_one_minus_alpha_prod.flatten() lowercase__ : Optional[Any] = broadcast_to_shape_from_left(lowerCamelCase__ , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" lowercase__ , lowercase__ : Dict = get_sqrt_alpha_prod(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) lowercase__ : int = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" lowercase__ , lowercase__ : int = get_sqrt_alpha_prod(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) lowercase__ : Any = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
496
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 snake_case = logging.get_logger(__name__) snake_case = { """google/vit-base-patch16-224""": """https://huggingface.co/vit-base-patch16-224/resolve/main/config.json""", # See all ViT models at https://huggingface.co/models?filter=vit } class A_ ( UpperCAmelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = '''vit''' def __init__( self : Dict ,__A : Dict=768 ,__A : List[Any]=12 ,__A : int=12 ,__A : Union[str, Any]=3072 ,__A : List[Any]="gelu" ,__A : Dict=0.0 ,__A : Union[str, Any]=0.0 ,__A : int=0.02 ,__A : List[str]=1e-12 ,__A : Optional[Any]=224 ,__A : Optional[int]=16 ,__A : Dict=3 ,__A : str=True ,__A : List[str]=16 ,**__A : int ,) -> List[str]: super().__init__(**__A ) _lowercase = hidden_size _lowercase = num_hidden_layers _lowercase = num_attention_heads _lowercase = intermediate_size _lowercase = hidden_act _lowercase = hidden_dropout_prob _lowercase = attention_probs_dropout_prob _lowercase = initializer_range _lowercase = layer_norm_eps _lowercase = image_size _lowercase = patch_size _lowercase = num_channels _lowercase = qkv_bias _lowercase = encoder_stride class A_ ( UpperCAmelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = version.parse('''1.11''' ) @property def __UpperCAmelCase ( self : Dict ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __UpperCAmelCase ( self : Union[str, Any] ) -> float: return 1e-4
535
def SCREAMING_SNAKE_CASE__ ( snake_case__ :str , snake_case__ :int ) -> list[str]: return [sentence[i : i + ngram_size] for i in range(len(snake_case__ ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
535
1
import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase = LongformerTokenizer _lowerCamelCase = True _lowerCamelCase = LongformerTokenizerFast _lowerCamelCase = True def lowerCamelCase ( self : int ) -> Optional[int]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _UpperCAmelCase = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] _UpperCAmelCase = dict(zip(lowerCamelCase , range(len(lowerCamelCase ) ) ) ) _UpperCAmelCase = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] _UpperCAmelCase = {"""unk_token""": """<unk>"""} _UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) _UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(lowerCamelCase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(lowerCamelCase ) ) def lowerCamelCase ( self : List[Any] , **lowerCamelCase : str ) -> Tuple: """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowerCamelCase ) def lowerCamelCase ( self : int , **lowerCamelCase : str ) -> int: """simple docstring""" kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **lowerCamelCase ) def lowerCamelCase ( self : Union[str, Any] , lowerCamelCase : Tuple ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = """lower newer""" _UpperCAmelCase = """lower newer""" return input_text, output_text def lowerCamelCase ( self : Optional[Any] ) -> str: """simple docstring""" _UpperCAmelCase = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) _UpperCAmelCase = """lower newer""" _UpperCAmelCase = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] _UpperCAmelCase = tokenizer.tokenize(lowerCamelCase ) # , add_prefix_space=True) self.assertListEqual(lowerCamelCase , lowerCamelCase ) _UpperCAmelCase = tokens + [tokenizer.unk_token] _UpperCAmelCase = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase ) , lowerCamelCase ) def lowerCamelCase ( self : Dict ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=lowerCamelCase ) , [0, 3_1414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=lowerCamelCase ) , [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2] , ) @slow def lowerCamelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.tokenizer_class.from_pretrained("""allenai/longformer-base-4096""" ) _UpperCAmelCase = tokenizer.encode("""sequence builders""" , add_special_tokens=lowerCamelCase ) _UpperCAmelCase = tokenizer.encode("""multi-sequence build""" , add_special_tokens=lowerCamelCase ) _UpperCAmelCase = tokenizer.encode( """sequence builders""" , add_special_tokens=lowerCamelCase , add_prefix_space=lowerCamelCase ) _UpperCAmelCase = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=lowerCamelCase , add_prefix_space=lowerCamelCase ) _UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCamelCase ) _UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCamelCase , lowerCamelCase ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def lowerCamelCase ( self : Optional[int] ) -> str: """simple docstring""" _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = """Encode this sequence.""" _UpperCAmelCase = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments _UpperCAmelCase = tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase , add_prefix_space=lowerCamelCase ) _UpperCAmelCase = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(lowerCamelCase , lowerCamelCase ) _UpperCAmelCase = tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase , add_prefix_space=lowerCamelCase ) _UpperCAmelCase = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(lowerCamelCase , lowerCamelCase ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) _UpperCAmelCase = tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) _UpperCAmelCase = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(lowerCamelCase , lowerCamelCase ) # Testing spaces after special tokens _UpperCAmelCase = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(lowerCamelCase , lstrip=lowerCamelCase , rstrip=lowerCamelCase )} ) # mask token has a left space _UpperCAmelCase = tokenizer.convert_tokens_to_ids(lowerCamelCase ) _UpperCAmelCase = """Encode <mask> sequence""" _UpperCAmelCase = """Encode <mask>sequence""" _UpperCAmelCase = tokenizer.encode(lowerCamelCase ) _UpperCAmelCase = encoded.index(lowerCamelCase ) _UpperCAmelCase = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(lowerCamelCase , lowerCamelCase ) _UpperCAmelCase = tokenizer.encode(lowerCamelCase ) _UpperCAmelCase = encoded.index(lowerCamelCase ) _UpperCAmelCase = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(lowerCamelCase , lowerCamelCase ) def lowerCamelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" pass def lowerCamelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase ) _UpperCAmelCase = self.tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase ) _UpperCAmelCase = """A, <mask> AllenNLP sentence.""" _UpperCAmelCase = tokenizer_r.encode_plus(lowerCamelCase , add_special_tokens=lowerCamelCase , return_token_type_ids=lowerCamelCase ) _UpperCAmelCase = tokenizer_p.encode_plus(lowerCamelCase , add_special_tokens=lowerCamelCase , return_token_type_ids=lowerCamelCase ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) _UpperCAmelCase = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) _UpperCAmelCase = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( lowerCamelCase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( lowerCamelCase , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def lowerCamelCase ( self : int ) -> str: """simple docstring""" for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase ) _UpperCAmelCase = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) _UpperCAmelCase = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , lowerCamelCase ) self.assertEqual(post_processor_state["""add_prefix_space"""] , lowerCamelCase ) self.assertEqual(post_processor_state["""trim_offsets"""] , lowerCamelCase ) def lowerCamelCase ( self : Dict ) -> Tuple: """simple docstring""" # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _UpperCAmelCase = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` _UpperCAmelCase = f"""{text_of_1_token} {text_of_1_token}""" _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase ) _UpperCAmelCase = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(lowerCamelCase ) + 1, len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , ) _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase ) _UpperCAmelCase = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(lowerCamelCase ) + 1, len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , ) _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase ) _UpperCAmelCase = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(lowerCamelCase ), len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , ) _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase ) _UpperCAmelCase = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(lowerCamelCase ), len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , ) _UpperCAmelCase = f""" {text}""" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase ) _UpperCAmelCase = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(lowerCamelCase ) + 1, 1 + len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , ) _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase ) _UpperCAmelCase = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(lowerCamelCase ), 1 + len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , ) _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained( lowerCamelCase , use_fast=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase ) _UpperCAmelCase = tokenizer_r(lowerCamelCase , return_offsets_mapping=lowerCamelCase , add_special_tokens=lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(lowerCamelCase ), 1 + len(lowerCamelCase ) + 1 + len(lowerCamelCase )) , )
108
"""simple docstring""" import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser _A = logging.getLogger(__name__) torch.set_grad_enabled(False) _A = """cuda""" if torch.cuda.is_available() else """cpu""" def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase=100 , __UpperCAmelCase=" " ) -> List[str]: lowerCAmelCase__ : str = text.split(__UpperCAmelCase ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(__UpperCAmelCase ) , __UpperCAmelCase )] def lowercase_ ( __UpperCAmelCase ) -> dict: lowerCAmelCase__ , lowerCAmelCase__ : List[str] = [], [] for title, text in zip(documents["""title"""] , documents["""text"""] ): if text is not None: for passage in split_text(__UpperCAmelCase ): titles.append(title if title is not None else """""" ) texts.append(__UpperCAmelCase ) return {"title": titles, "text": texts} def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> dict: lowerCAmelCase__ : str = ctx_tokenizer( documents["""title"""] , documents["""text"""] , truncation=__UpperCAmelCase , padding="""longest""" , return_tensors="""pt""" )["""input_ids"""] lowerCAmelCase__ : Tuple = ctx_encoder(input_ids.to(device=__UpperCAmelCase ) , return_dict=__UpperCAmelCase ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ) -> Tuple: ###################################### logger.info("""Step 1 - Create the dataset""" ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way lowerCAmelCase__ : Dict = load_dataset( """csv""" , data_files=[rag_example_args.csv_path] , split="""train""" , delimiter="""\t""" , column_names=["""title""", """text"""] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words lowerCAmelCase__ : Dict = dataset.map(__UpperCAmelCase , batched=__UpperCAmelCase , num_proc=processing_args.num_proc ) # And compute the embeddings lowerCAmelCase__ : Any = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=__UpperCAmelCase ) lowerCAmelCase__ : Any = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) lowerCAmelCase__ : List[Any] = Features( {"""text""": Value("""string""" ), """title""": Value("""string""" ), """embeddings""": Sequence(Value("""float32""" ) )} ) # optional, save as float32 instead of float64 to save space lowerCAmelCase__ : Optional[Any] = dataset.map( partial(__UpperCAmelCase , ctx_encoder=__UpperCAmelCase , ctx_tokenizer=__UpperCAmelCase ) , batched=__UpperCAmelCase , batch_size=processing_args.batch_size , features=__UpperCAmelCase , ) # And finally save your dataset lowerCAmelCase__ : List[Any] = os.path.join(rag_example_args.output_dir , """my_knowledge_dataset""" ) dataset.save_to_disk(__UpperCAmelCase ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info("""Step 2 - Index the dataset""" ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search lowerCAmelCase__ : Tuple = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index("""embeddings""" , custom_index=__UpperCAmelCase ) # And save the index lowerCAmelCase__ : Union[str, Any] = os.path.join(rag_example_args.output_dir , """my_knowledge_dataset_hnsw_index.faiss""" ) dataset.get_index("""embeddings""" ).save(__UpperCAmelCase ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class _lowerCamelCase : _lowerCamelCase :str = field( default=str(Path(a_ ).parent / "test_run" / "dummy-kb" / "my_knowledge_dataset.csv" ) , metadata={"help": "Path to a tab-separated csv file with columns 'title' and 'text'"} , ) _lowerCamelCase :Optional[str] = field( default=a_ , metadata={"help": "Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."} , ) _lowerCamelCase :str = field( default="facebook/rag-sequence-nq" , metadata={"help": "The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"} , ) _lowerCamelCase :str = field( default="facebook/dpr-ctx_encoder-multiset-base" , metadata={ "help": ( "The DPR context encoder model to use. Either 'facebook/dpr-ctx_encoder-single-nq-base' or" " 'facebook/dpr-ctx_encoder-multiset-base'" ) } , ) _lowerCamelCase :Optional[str] = field( default=str(Path(a_ ).parent / "test_run" / "dummy-kb" ) , metadata={"help": "Path to a directory where the dataset passages and the index will be saved"} , ) @dataclass class _lowerCamelCase : _lowerCamelCase :Optional[int] = field( default=a_ , metadata={ "help": "The number of processes to use to split the documents into passages. Default is single process." } , ) _lowerCamelCase :int = field( default=16 , metadata={ "help": "The batch size to use when computing the passages embeddings using the DPR context encoder." } , ) @dataclass class _lowerCamelCase : _lowerCamelCase :int = field( default=768 , metadata={"help": "The dimension of the embeddings to pass to the HNSW Faiss index."} , ) _lowerCamelCase :int = field( default=128 , metadata={ "help": ( "The number of bi-directional links created for every new element during the HNSW index construction." ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) _A = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) _A , _A , _A = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: _A = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
299
0
import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType a , a , a = False, False, False @dataclass class _A : __a = None __a = True __a = True __a = None # Automatically constructed __a = "dict" __a = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()} ) __a = field(default="""Audio""" , init=__lowercase , repr=__lowercase ) def __call__( self ): return self.pa_type def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ): try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("""To support encoding audio data, please install 'soundfile'.""" ) from err if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {"bytes": None, "path": value} elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes _UpperCAmelCase = BytesIO() sf.write(_SCREAMING_SNAKE_CASE , value["""array"""] , value["""sampling_rate"""] , format="""wav""" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("""path""" ) is not None and os.path.isfile(value["""path"""] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("""pcm""" ): # "PCM" only has raw audio bytes if value.get("""sampling_rate""" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("""To use PCM files, please specify a 'sampling_rate' in Audio object""" ) if value.get("""bytes""" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) _UpperCAmelCase = np.frombuffer(value["""bytes"""] , dtype=np.intaa ).astype(np.floataa ) / 3_2767 else: _UpperCAmelCase = np.memmap(value["""path"""] , dtype="""h""" , mode="""r""" ).astype(np.floataa ) / 3_2767 _UpperCAmelCase = BytesIO(bytes() ) sf.write(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , value["""sampling_rate"""] , format="""wav""" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( F"An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}." ) def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ): if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Audio(decode=True) instead.""" ) _UpperCAmelCase , _UpperCAmelCase = (value["""path"""], BytesIO(value["""bytes"""] )) if value["""bytes"""] is not None else (value["""path"""], None) if path is None and file is None: raise ValueError(F"An audio sample should have one of 'path' or 'bytes' but both are None in {value}." ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("""To support decoding audio files, please install 'librosa' and 'soundfile'.""" ) from err _UpperCAmelCase = xsplitext(_SCREAMING_SNAKE_CASE )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( """Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, """ """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """ ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( """Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, """ """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """ ) if file is None: _UpperCAmelCase = token_per_repo_id or {} _UpperCAmelCase = path.split("""::""" )[-1] try: _UpperCAmelCase = string_to_dict(_SCREAMING_SNAKE_CASE , config.HUB_DATASETS_URL )["""repo_id"""] _UpperCAmelCase = token_per_repo_id[repo_id] except (ValueError, KeyError): _UpperCAmelCase = None with xopen(_SCREAMING_SNAKE_CASE , """rb""" , use_auth_token=_SCREAMING_SNAKE_CASE ) as f: _UpperCAmelCase , _UpperCAmelCase = sf.read(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase , _UpperCAmelCase = sf.read(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = array.T if self.mono: _UpperCAmelCase = librosa.to_mono(_SCREAMING_SNAKE_CASE ) if self.sampling_rate and self.sampling_rate != sampling_rate: _UpperCAmelCase = librosa.resample(_SCREAMING_SNAKE_CASE , orig_sr=_SCREAMING_SNAKE_CASE , target_sr=self.sampling_rate ) _UpperCAmelCase = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def UpperCAmelCase ( self ): from .features import Value if self.decode: raise ValueError("""Cannot flatten a decoded Audio feature.""" ) return { "bytes": Value("""binary""" ), "path": Value("""string""" ), } def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ): if pa.types.is_string(storage.type ): _UpperCAmelCase = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.binary() ) _UpperCAmelCase = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): _UpperCAmelCase = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.string() ) _UpperCAmelCase = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("""array""" ): _UpperCAmelCase = pa.array([Audio().encode_example(_SCREAMING_SNAKE_CASE ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: _UpperCAmelCase = storage.field("""bytes""" ) else: _UpperCAmelCase = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: _UpperCAmelCase = storage.field("""path""" ) else: _UpperCAmelCase = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.string() ) _UpperCAmelCase = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type ) def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ): @no_op_if_value_is_null def path_to_bytes(_SCREAMING_SNAKE_CASE ): with xopen(_SCREAMING_SNAKE_CASE , """rb""" ) as f: _UpperCAmelCase = f.read() return bytes_ _UpperCAmelCase = pa.array( [ (path_to_bytes(x["""path"""] ) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) _UpperCAmelCase = pa.array( [os.path.basename(_SCREAMING_SNAKE_CASE ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) _UpperCAmelCase = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type )
175
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( snake_case ) -> list[int]: if len(snake_case ) == 0: return array _UpperCAmelCase , _UpperCAmelCase = min(snake_case ), max(snake_case ) # Compute the variables _UpperCAmelCase = _max - _min + 1 _UpperCAmelCase , _UpperCAmelCase = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: _UpperCAmelCase = i - _min _UpperCAmelCase = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. _UpperCAmelCase = 0 for i in range(snake_case ): while holes_repeat[i] > 0: _UpperCAmelCase = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() a = input("Enter numbers separated by comma:\n") a = [int(x) for x in user_input.split(",")] print(pigeon_sort(unsorted))
175
1
from __future__ import annotations import math def __UpperCAmelCase ( lowerCamelCase_ : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCamelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True UpperCamelCase__ : List[str] = [num for num in range(3, 10_00_01, 2) if not is_prime(num)] def __UpperCAmelCase ( lowerCamelCase_ : int ) -> list[int]: """simple docstring""" if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise ValueError('n must be an integer' ) if n <= 0: raise ValueError('n must be >= 0' ) SCREAMING_SNAKE_CASE_ : Dict = [] for num in range(len(lowerCamelCase_ ) ): SCREAMING_SNAKE_CASE_ : List[Any] = 0 while 2 * i * i <= odd_composites[num]: SCREAMING_SNAKE_CASE_ : Dict = odd_composites[num] - 2 * i * i if is_prime(lowerCamelCase_ ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(lowerCamelCase_ ) == n: return list_nums return [] def __UpperCAmelCase ( ) -> int: """simple docstring""" return compute_nums(1 )[0] if __name__ == "__main__": print(F"""{solution() = }""")
105
def SCREAMING_SNAKE_CASE_ ( _snake_case :int ) -> int: if not isinstance(_snake_case , _snake_case ): raise ValueError('''Input must be an integer''' ) if input_num <= 0: raise ValueError('''Input must be positive''' ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
2
0
import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class _UpperCamelCase: def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any]=1_3 , SCREAMING_SNAKE_CASE__ : str=7 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=9_9 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_2 , SCREAMING_SNAKE_CASE__ : Tuple=5 , SCREAMING_SNAKE_CASE__ : Tuple=4 , SCREAMING_SNAKE_CASE__ : Dict=3_7 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : int=1_2_8 , SCREAMING_SNAKE_CASE__ : int=3_2 , SCREAMING_SNAKE_CASE__ : Any=1_6 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Dict=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : int=None , ): '''simple docstring''' __a : List[str] = parent __a : str = batch_size __a : List[str] = seq_length __a : Any = is_training __a : Dict = use_input_mask __a : str = use_token_type_ids __a : Optional[Any] = use_labels __a : List[str] = vocab_size __a : Optional[int] = hidden_size __a : Optional[Any] = num_hidden_layers __a : int = num_attention_heads __a : Optional[int] = intermediate_size __a : Union[str, Any] = hidden_act __a : List[Any] = hidden_dropout_prob __a : List[Any] = attention_probs_dropout_prob __a : List[Any] = max_position_embeddings __a : int = type_vocab_size __a : Any = type_sequence_label_size __a : str = initializer_range __a : Optional[Any] = num_labels __a : int = num_choices __a : str = scope def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : str = None if self.use_input_mask: __a : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) __a : Dict = None if self.use_token_type_ids: __a : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Any = None __a : Optional[Any] = None __a : int = None if self.use_labels: __a : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a : Dict = ids_tensor([self.batch_size] , self.num_choices ) __a : Optional[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return NezhaConfig( 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=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self : int ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Union[str, Any] = self.prepare_config_and_inputs() __a : Optional[Any] = True __a : Optional[int] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' __a : List[str] = NezhaModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a : Optional[int] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , ): '''simple docstring''' __a : List[str] = True __a : Union[str, Any] = NezhaModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a : List[str] = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , encoder_attention_mask=SCREAMING_SNAKE_CASE__ , ) __a : Tuple = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , ) __a : Tuple = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCAmelCase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' __a : Tuple = NezhaForMaskedLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a : Dict = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' __a : Optional[Any] = NezhaForNextSentencePrediction(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a : List[str] = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __lowerCAmelCase ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' __a : Any = NezhaForPreTraining(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a : List[str] = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , next_sentence_label=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' __a : List[str] = NezhaForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a : Dict = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , start_positions=SCREAMING_SNAKE_CASE__ , end_positions=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): '''simple docstring''' __a : int = self.num_labels __a : Dict = NezhaForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a : Optional[int] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : int = self.num_labels __a : Dict = NezhaForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a : List[str] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : Union[str, Any] = self.num_choices __a : Optional[int] = NezhaForMultipleChoice(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : List[str] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a : Dict = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : int = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Union[str, Any] = config_and_inputs __a : Optional[int] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _UpperCamelCase( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): __SCREAMING_SNAKE_CASE : Tuple = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( { '''feature-extraction''': NezhaModel, '''fill-mask''': NezhaForMaskedLM, '''question-answering''': NezhaForQuestionAnswering, '''text-classification''': NezhaForSequenceClassification, '''token-classification''': NezhaForTokenClassification, '''zero-shot''': NezhaForSequenceClassification, } if is_torch_available() else {} ) __SCREAMING_SNAKE_CASE : Dict = True def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=False ): '''simple docstring''' __a : Dict = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): __a : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : str = NezhaModelTester(self ) __a : List[str] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=3_7 ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' self.config_tester.run_common_tests() def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) : Tuple = self.model_tester.prepare_config_and_inputs_for_decoder() __a : Union[str, Any] = None self.model_tester.create_and_check_model_as_decoder( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @slow def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : List[Any] = NezhaModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @slow @require_torch_gpu def __lowerCAmelCase ( self : int ): '''simple docstring''' __a , __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __a : Any = True __a : Dict = model_class(config=SCREAMING_SNAKE_CASE__ ) __a : Dict = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : int = torch.jit.trace( SCREAMING_SNAKE_CASE__ , (inputs_dict['input_ids'].to('cpu' ), inputs_dict['attention_mask'].to('cpu' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , 'bert.pt' ) ) __a : int = torch.jit.load(os.path.join(SCREAMING_SNAKE_CASE__ , 'bert.pt' ) , map_location=SCREAMING_SNAKE_CASE__ ) loaded(inputs_dict['input_ids'].to(SCREAMING_SNAKE_CASE__ ) , inputs_dict['attention_mask'].to(SCREAMING_SNAKE_CASE__ ) ) @require_torch class _UpperCamelCase( unittest.TestCase ): @slow def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' __a : Any = NezhaModel.from_pretrained('sijunhe/nezha-cn-base' ) __a : Any = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __a : Dict = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __a : Dict = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ )[0] __a : Dict = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) __a : Optional[int] = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' __a : Dict = NezhaForMaskedLM.from_pretrained('sijunhe/nezha-cn-base' ) __a : Optional[int] = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __a : Dict = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __a : List[Any] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ )[0] __a : List[str] = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
577
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ = { '''configuration_time_series_transformer''': [ '''TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TimeSeriesTransformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ '''TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TimeSeriesTransformerForPrediction''', '''TimeSeriesTransformerModel''', '''TimeSeriesTransformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
577
1
'''simple docstring''' import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : str=13 , __SCREAMING_SNAKE_CASE : int=7 , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : Any=True , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Dict=99 , __SCREAMING_SNAKE_CASE : Optional[int]=24 , __SCREAMING_SNAKE_CASE : Any=2 , __SCREAMING_SNAKE_CASE : Any=6 , __SCREAMING_SNAKE_CASE : Optional[int]=37 , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : List[Any]=0.1 , __SCREAMING_SNAKE_CASE : int=512 , __SCREAMING_SNAKE_CASE : str=16 , __SCREAMING_SNAKE_CASE : Any=2 , __SCREAMING_SNAKE_CASE : List[str]=0.02 , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : List[Any]=1_000 , ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = scope __SCREAMING_SNAKE_CASE = range_bbox def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __SCREAMING_SNAKE_CASE = bbox[i, j, 3] __SCREAMING_SNAKE_CASE = bbox[i, j, 1] __SCREAMING_SNAKE_CASE = t if bbox[i, j, 2] < bbox[i, j, 0]: __SCREAMING_SNAKE_CASE = bbox[i, j, 2] __SCREAMING_SNAKE_CASE = bbox[i, j, 0] __SCREAMING_SNAKE_CASE = t __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def UpperCAmelCase__ ( self : str ) -> int: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int , ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = LiltModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[Any] , ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = LiltForTokenClassification(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = LiltForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , start_positions=__SCREAMING_SNAKE_CASE , end_positions=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) lowerCAmelCase__ = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase__ = False lowerCAmelCase__ = False def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" return True def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = LiltModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , hidden_size=37 ) def UpperCAmelCase__ ( self : int ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Optional[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self : Dict ) -> int: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = LiltModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) @require_torch @slow class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 2]] , device=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(input_ids=__SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.Size([1, 2, 768] ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=__SCREAMING_SNAKE_CASE , ) self.assertTrue(outputs.last_hidden_state.shape , __SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , __SCREAMING_SNAKE_CASE , atol=1E-3 ) )
627
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """tf_padding""" ) ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """depth_multiplier""" ) ) class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : str=13 , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Optional[int]=32 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.25 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : int=1_024 , __SCREAMING_SNAKE_CASE : Optional[Any]=32 , __SCREAMING_SNAKE_CASE : List[Any]="relu6" , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=True , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : List[Any]=10 , __SCREAMING_SNAKE_CASE : int=None , ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = depth_multiplier __SCREAMING_SNAKE_CASE = min_depth __SCREAMING_SNAKE_CASE = tf_padding __SCREAMING_SNAKE_CASE = int(last_hidden_size * depth_multiplier ) __SCREAMING_SNAKE_CASE = output_stride __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = classifier_dropout_prob __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase__ ( self : Optional[int] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCAmelCase__ ( self : Any ) -> Tuple: """simple docstring""" return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : int ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = MobileNetVaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = MobileNetVaForImageClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self : str ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = config_and_inputs __SCREAMING_SNAKE_CASE = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () lowerCAmelCase__ = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = MobileNetVaModelTester(self ) __SCREAMING_SNAKE_CASE = MobileNetVaConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""MobileNetV1 does not use inputs_embeds""" ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not support input and output embeddings""" ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not output attentions""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> Optional[Any]: """simple docstring""" def check_hidden_states_output(__SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : str ): __SCREAMING_SNAKE_CASE = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = outputs.hidden_states __SCREAMING_SNAKE_CASE = 26 self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __SCREAMING_SNAKE_CASE = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = MobileNetVaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase__ ( self : Dict ) -> List[str]: """simple docstring""" return ( MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v1_1.0_224""" ) if is_vision_available() else None ) @slow def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224""" ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.default_image_processor __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**__SCREAMING_SNAKE_CASE ) # verify the logits __SCREAMING_SNAKE_CASE = torch.Size((1, 1_001) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.tensor([-4.1739, -1.1233, 3.1205] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) )
627
1
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": lowercase__ : int = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument( "--original_config_file", type=str, required=True, help="The YAML config file corresponding to the original architecture.", ) parser.add_argument( "--num_in_channels", default=None, type=int, help="The number of input channels. If `None` number of input channels will be automatically inferred.", ) parser.add_argument( "--image_size", default=5_1_2, type=int, help=( "The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2" " Base. Use 768 for Stable Diffusion v2." ), ) parser.add_argument( "--extract_ema", action="store_true", help=( "Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights" " or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield" " higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning." ), ) parser.add_argument( "--upcast_attention", action="store_true", help=( "Whether the attention computation should always be upcasted. This is necessary when running stable" " diffusion 2.1." ), ) parser.add_argument( "--from_safetensors", action="store_true", help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.", ) parser.add_argument( "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)") def A_ ( snake_case : Union[str, Any] ) -> List[Any]: '''simple docstring''' if string == "True": return True elif string == "False": return False else: raise ValueError(f"could not parse string as bool {string}" ) parser.add_argument( "--use_linear_projection", help="Override for use linear projection", required=False, type=parse_bool ) parser.add_argument("--cross_attention_dim", help="Override for cross attention_dim", required=False, type=int) lowercase__ : int = parser.parse_args() lowercase__ : Tuple = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
451
from collections import Counter from timeit import timeit def A_ ( snake_case : str = "" , ) -> bool: '''simple docstring''' return sum(c % 2 for c in Counter(input_str.replace(''' ''' , '''''' ).lower() ).values() ) < 2 def A_ ( snake_case : str = "" ) -> bool: '''simple docstring''' if len(snake_case ) == 0: return True __UpperCamelCase = input_str.replace(''' ''' , '''''' ).lower() # character_freq_dict: Stores the frequency of every character in the input string __UpperCamelCase = {} for character in lower_case_input_str: __UpperCamelCase = character_freq_dict.get(snake_case , 0 ) + 1 __UpperCamelCase = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def A_ ( snake_case : str = "" ) -> None: '''simple docstring''' print('''\nFor string = ''' , snake_case , ''':''' ) print( '''> can_string_be_rearranged_as_palindrome_counter()''' , '''\tans =''' , can_string_be_rearranged_as_palindrome_counter(snake_case ) , '''\ttime =''' , timeit( '''z.can_string_be_rearranged_as_palindrome_counter(z.check_str)''' , setup='''import __main__ as z''' , ) , '''seconds''' , ) print( '''> can_string_be_rearranged_as_palindrome()''' , '''\tans =''' , can_string_be_rearranged_as_palindrome(snake_case ) , '''\ttime =''' , timeit( '''z.can_string_be_rearranged_as_palindrome(z.check_str)''' , setup='''import __main__ as z''' , ) , '''seconds''' , ) if __name__ == "__main__": lowercase__ : Tuple = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) lowercase__ : Dict = can_string_be_rearranged_as_palindrome_counter(check_str) print(F"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
451
1
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # Construct model if gpta_config_file == "": UpperCamelCase : Union[str, Any] = GPTaConfig() else: UpperCamelCase : Dict = GPTaConfig.from_json_file(SCREAMING_SNAKE_CASE ) UpperCamelCase : Optional[Any] = GPTaModel(SCREAMING_SNAKE_CASE ) # Load weights from numpy load_tf_weights_in_gpta(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Save pytorch-model UpperCamelCase : str = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME UpperCamelCase : Dict = pytorch_dump_folder_path + """/""" + CONFIG_NAME print(f"""Save PyTorch model to {pytorch_weights_dump_path}""" ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE ) print(f"""Save configuration file to {pytorch_config_dump_path}""" ) with open(SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __magic_name__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--gpt2_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) __magic_name__ : int = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
102
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __magic_name__ = { '''configuration_conditional_detr''': [ '''CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConditionalDetrConfig''', '''ConditionalDetrOnnxConfig''', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''ConditionalDetrFeatureExtractor'''] __magic_name__ = ['''ConditionalDetrImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ConditionalDetrForObjectDetection''', '''ConditionalDetrForSegmentation''', '''ConditionalDetrModel''', '''ConditionalDetrPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
250
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowercase_ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['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 lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
215
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import is_flaky, require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DonutImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any], _lowerCamelCase : int, _lowerCamelCase : List[Any]=7, _lowerCamelCase : Any=3, _lowerCamelCase : List[Any]=18, _lowerCamelCase : str=30, _lowerCamelCase : List[Any]=4_00, _lowerCamelCase : List[str]=True, _lowerCamelCase : List[Any]=None, _lowerCamelCase : Union[str, Any]=True, _lowerCamelCase : List[str]=False, _lowerCamelCase : str=True, _lowerCamelCase : int=True, _lowerCamelCase : List[str]=[0.5, 0.5, 0.5], _lowerCamelCase : Union[str, Any]=[0.5, 0.5, 0.5], ): '''simple docstring''' __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size if size is not None else {'''height''': 18, '''width''': 20} __A = do_thumbnail __A = do_align_axis __A = do_pad __A = do_normalize __A = image_mean __A = image_std def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Union[str, Any] = DonutImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = DonutImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_thumbnail''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_align_long_axis''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_pad''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''image_std''' ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'''height''': 18, '''width''': 20} ) __A = self.image_processing_class.from_dict(self.image_processor_dict, size=42 ) self.assertEqual(image_processor.size, {'''height''': 42, '''width''': 42} ) # Previous config had dimensions in (width, height) order __A = self.image_processing_class.from_dict(self.image_processor_dict, size=(42, 84) ) self.assertEqual(image_processor.size, {'''height''': 84, '''width''': 42} ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' pass @is_flaky() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processing(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) # Test batched __A = 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.size['''height'''], self.image_processor_tester.size['''width'''], ), ) @is_flaky() def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = 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 __A = image_processing(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) # Test batched __A = 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.size['''height'''], self.image_processor_tester.size['''width'''], ), ) @is_flaky() def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = 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 __A = image_processing(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ), ) # Test batched __A = 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.size['''height'''], self.image_processor_tester.size['''width'''], ), )
215
1
def _a ( __lowercase ) -> Optional[int]: """simple docstring""" __UpperCamelCase = len(lowercase__ ) for _ in range(lowercase__ ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: __UpperCamelCase , __UpperCamelCase = arr[i + 1], arr[i] return arr if __name__ == "__main__": _snake_case = list(range(10, 0, -1)) print(F'''Original: {arr}. Sorted: {odd_even_transposition(arr)}''')
383
from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig A = logging.get_logger(__name__) A = 'T5Config' class SCREAMING_SNAKE_CASE ( __snake_case ): """simple docstring""" __A = """mt5""" __A = MTaConfig class SCREAMING_SNAKE_CASE ( __snake_case ): """simple docstring""" __A = """mt5""" __A = MTaConfig class SCREAMING_SNAKE_CASE ( __snake_case ): """simple docstring""" __A = """mt5""" __A = MTaConfig
187
0
"""simple docstring""" from math import isclose, sqrt def lowerCamelCase__ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Tuple = point_y / 4 / point_x _lowerCAmelCase : Any = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) _lowerCAmelCase : Dict = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) _lowerCAmelCase : Any = (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 _lowerCAmelCase : Tuple = outgoing_gradient**2 + 4 _lowerCAmelCase : Dict = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) _lowerCAmelCase : List[str] = (point_y - outgoing_gradient * point_x) ** 2 - 100 _lowerCAmelCase : int = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) _lowerCAmelCase : str = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point _lowerCAmelCase : Dict = x_minus if isclose(_lowerCamelCase , _lowerCamelCase ) else x_plus _lowerCAmelCase : Dict = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def lowerCamelCase__ ( _lowerCamelCase = 1.4 , _lowerCamelCase = -9.6 ): '''simple docstring''' _lowerCAmelCase : int = 0 _lowerCAmelCase : float = first_x_coord _lowerCAmelCase : float = first_y_coord _lowerCAmelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): _lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase : List[str] = next_point(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F'''{solution() = }''')
16
"""simple docstring""" import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { """vocab_file""": """vocab.json""", """tokenizer_config_file""": """tokenizer_config.json""", """merges_file""": """merges.txt""", } _lowerCAmelCase = { """vocab_file""": { """facebook/s2t-wav2vec2-large-en-de""": ( """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json""" ), }, """tokenizer_config_file""": { """facebook/s2t-wav2vec2-large-en-de""": ( """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json""" ), }, """merges_file""": { """facebook/s2t-wav2vec2-large-en-de""": ( """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt""" ), }, } _lowerCAmelCase = """</w>""" _lowerCAmelCase = """@@ """ def lowerCamelCase__ ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : List[str] = set() _lowerCAmelCase : Dict = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _lowerCAmelCase : Any = char return pairs # Speech2Text2 has no max input length _lowerCAmelCase = {"""facebook/s2t-wav2vec2-large-en-de""": 1_0_2_4} class __UpperCamelCase ( a__ ): _UpperCAmelCase = VOCAB_FILES_NAMES _UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase = ["input_ids", "attention_mask"] def __init__( self ,_A ,_A="<s>" ,_A="<pad>" ,_A="</s>" ,_A="<unk>" ,_A=False ,_A=None ,**_A ,): '''simple docstring''' super().__init__( unk_token=_A ,bos_token=_A ,eos_token=_A ,pad_token=_A ,do_lower_case=_A ,**_A ,) _lowerCAmelCase : List[Any] = do_lower_case with open(_A ,encoding='utf-8' ) as vocab_handle: _lowerCAmelCase : Optional[int] = json.load(_A ) _lowerCAmelCase : Tuple = {v: k for k, v in self.encoder.items()} if merges_file is None: logger.info(F"""No merges files provided. {self.__class__.__name__} can only be used for decoding.""" ) _lowerCAmelCase : Optional[Any] = None _lowerCAmelCase : Tuple = None else: with open(_A ,encoding='utf-8' ) as merges_handle: _lowerCAmelCase : Optional[Any] = merges_handle.read().split('\n' )[:-1] _lowerCAmelCase : List[str] = [tuple(merge.split()[:2] ) for merge in merges] _lowerCAmelCase : List[Any] = dict(zip(_A ,range(len(_A ) ) ) ) _lowerCAmelCase : Union[str, Any] = {} @property def __lowerCamelCase ( self ): '''simple docstring''' return len(self.decoder ) def __lowerCamelCase ( self ): '''simple docstring''' return dict(self.encoder ,**self.added_tokens_encoder ) def __lowerCamelCase ( self ,_A ): '''simple docstring''' _lowerCAmelCase : str = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,) if token in self.cache: return self.cache[token] _lowerCAmelCase : str = get_pairs(_A ) if not pairs: return token while True: _lowerCAmelCase : List[str] = min(_A ,key=lambda _A : self.bpe_ranks.get(_A ,float('inf' ) ) ) if bigram not in self.bpe_ranks: break _lowerCAmelCase, _lowerCAmelCase : Optional[int] = bigram _lowerCAmelCase : Union[str, Any] = [] _lowerCAmelCase : Dict = 0 while i < len(_A ): try: _lowerCAmelCase : Dict = word.index(_A ,_A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _lowerCAmelCase : Optional[Any] = 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 : Optional[Any] = tuple(_A ) _lowerCAmelCase : List[str] = new_word if len(_A ) == 1: break else: _lowerCAmelCase : List[str] = get_pairs(_A ) _lowerCAmelCase : Any = ' '.join(_A ) if word == "\n " + BPE_TOKEN_MERGES: _lowerCAmelCase : str = '\n' + BPE_TOKEN_MERGES if word.endswith(_A ): _lowerCAmelCase : Dict = word.replace(_A ,'' ) _lowerCAmelCase : str = word.replace(' ' ,_A ) _lowerCAmelCase : str = word return word def __lowerCamelCase ( self ,_A ): '''simple docstring''' if self.bpe_ranks is None: raise ValueError( 'This tokenizer was instantiated without a `merges.txt` file, so' ' that it can only be used for decoding, not for encoding.' 'Make sure to provide `merges.txt` file at instantiation to enable ' 'encoding.' ) if self.do_lower_case: _lowerCAmelCase : Optional[Any] = text.lower() _lowerCAmelCase : Tuple = text.split() _lowerCAmelCase : Union[str, Any] = [] for token in text: if token: split_tokens.extend(list(self.bpe(_A ).split(' ' ) ) ) return split_tokens def __lowerCamelCase ( self ,_A ): '''simple docstring''' return self.encoder.get(_A ,self.encoder.get(self.unk_token ) ) def __lowerCamelCase ( self ,_A ): '''simple docstring''' _lowerCAmelCase : int = self.decoder.get(_A ,self.unk_token ) return result def __lowerCamelCase ( self ,_A ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = ' '.join(_A ) # make sure @@ tokens are concatenated _lowerCAmelCase : int = ''.join(string.split(_A ) ) return string def __lowerCamelCase ( self ,_A ,_A = None ): '''simple docstring''' if not os.path.isdir(_A ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _lowerCAmelCase : List[Any] = os.path.join( _A ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) _lowerCAmelCase : str = 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 : str = 0 if self.bpe_ranks is None: return (vocab_file,) with open(_A ,'w' ,encoding='utf-8' ) as writer: 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 {merges_file}: BPE merge indices are not consecutive.""" ' Please check that the tokenizer is not corrupted!' ) _lowerCAmelCase : Dict = token_index writer.write(' '.join(_A ) + '\n' ) index += 1 return (vocab_file, merges_file)
16
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __UpperCamelCase ( UpperCamelCase , UpperCamelCase , unittest.TestCase ): lowercase_ : Optional[Any] = StableDiffusionSAGPipeline lowercase_ : str = TEXT_TO_IMAGE_PARAMS lowercase_ : Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS lowercase_ : Optional[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS lowercase_ : int = TEXT_TO_IMAGE_IMAGE_PARAMS lowercase_ : Dict = False def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase :Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) lowerCAmelCase :List[str] = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' , clip_sample=UpperCAmelCase , set_alpha_to_one=UpperCAmelCase , ) torch.manual_seed(0 ) lowerCAmelCase :List[Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) lowerCAmelCase :str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) lowerCAmelCase :Optional[int] = CLIPTextModel(UpperCAmelCase ) lowerCAmelCase :Any = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) lowerCAmelCase :Optional[Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def UpperCAmelCase__ ( self : Union[str, Any] , UpperCAmelCase : Any , UpperCAmelCase : Tuple=0 ) -> Dict: if str(UpperCAmelCase ).startswith('mps' ): lowerCAmelCase :Any = torch.manual_seed(UpperCAmelCase ) else: lowerCAmelCase :str = torch.Generator(device=UpperCAmelCase ).manual_seed(UpperCAmelCase ) lowerCAmelCase :int = { 'prompt': '.', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 1.0, 'sag_scale': 1.0, 'output_type': 'numpy', } return inputs def UpperCAmelCase__ ( self : Dict ) -> Any: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def UpperCAmelCase__ ( self : List[str] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : Optional[Any] ) -> List[str]: lowerCAmelCase :Tuple = StableDiffusionSAGPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' ) lowerCAmelCase :str = sag_pipe.to(UpperCAmelCase ) sag_pipe.set_progress_bar_config(disable=UpperCAmelCase ) lowerCAmelCase :Optional[int] = '.' lowerCAmelCase :List[Any] = torch.manual_seed(0 ) lowerCAmelCase :Optional[Any] = sag_pipe( [prompt] , generator=UpperCAmelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='np' ) lowerCAmelCase :List[Any] = output.images lowerCAmelCase :int = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCAmelCase :Optional[Any] = np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: lowerCAmelCase :List[Any] = StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) lowerCAmelCase :str = sag_pipe.to(UpperCAmelCase ) sag_pipe.set_progress_bar_config(disable=UpperCAmelCase ) lowerCAmelCase :Optional[Any] = '.' lowerCAmelCase :List[str] = torch.manual_seed(0 ) lowerCAmelCase :Optional[Any] = sag_pipe( [prompt] , generator=UpperCAmelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='np' ) lowerCAmelCase :Union[str, Any] = output.images lowerCAmelCase :Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCAmelCase :Dict = np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: lowerCAmelCase :int = StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) lowerCAmelCase :Optional[Any] = sag_pipe.to(UpperCAmelCase ) sag_pipe.set_progress_bar_config(disable=UpperCAmelCase ) lowerCAmelCase :List[Any] = '.' lowerCAmelCase :int = torch.manual_seed(0 ) lowerCAmelCase :Dict = sag_pipe( [prompt] , width=768 , height=512 , generator=UpperCAmelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='np' , ) lowerCAmelCase :List[Any] = output.images assert image.shape == (1, 512, 768, 3)
553
"""simple docstring""" import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def UpperCAmelCase ( a__ , a__=None ): '''simple docstring''' lowerCAmelCase :str = None if token is not None: lowerCAmelCase :List[Any] = {'Accept': 'application/vnd.github+json', 'Authorization': F"""Bearer {token}"""} lowerCAmelCase :Dict = F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100""" lowerCAmelCase :Optional[Any] = requests.get(a__ , headers=a__ ).json() lowerCAmelCase :Tuple = {} try: job_links.update({job['name']: job['html_url'] for job in result['jobs']} ) lowerCAmelCase :List[Any] = math.ceil((result['total_count'] - 1_00) / 1_00 ) for i in range(a__ ): lowerCAmelCase :List[Any] = requests.get(url + F"""&page={i + 2}""" , headers=a__ ).json() job_links.update({job['name']: job['html_url'] for job in result['jobs']} ) return job_links except Exception: print(F"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" ) return {} def UpperCAmelCase ( a__ , a__=None ): '''simple docstring''' lowerCAmelCase :Optional[Any] = None if token is not None: lowerCAmelCase :Any = {'Accept': 'application/vnd.github+json', 'Authorization': F"""Bearer {token}"""} lowerCAmelCase :Optional[int] = F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100""" lowerCAmelCase :Any = requests.get(a__ , headers=a__ ).json() lowerCAmelCase :str = {} try: artifacts.update({artifact['name']: artifact['archive_download_url'] for artifact in result['artifacts']} ) lowerCAmelCase :List[Any] = math.ceil((result['total_count'] - 1_00) / 1_00 ) for i in range(a__ ): lowerCAmelCase :List[Any] = requests.get(url + F"""&page={i + 2}""" , headers=a__ ).json() artifacts.update({artifact['name']: artifact['archive_download_url'] for artifact in result['artifacts']} ) return artifacts except Exception: print(F"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" ) return {} def UpperCAmelCase ( a__ , a__ , a__ , a__ ): '''simple docstring''' lowerCAmelCase :Optional[Any] = None if token is not None: lowerCAmelCase :Optional[Any] = {'Accept': 'application/vnd.github+json', 'Authorization': F"""Bearer {token}"""} lowerCAmelCase :Tuple = requests.get(a__ , headers=a__ , allow_redirects=a__ ) lowerCAmelCase :Optional[int] = result.headers['Location'] lowerCAmelCase :int = requests.get(a__ , allow_redirects=a__ ) lowerCAmelCase :Union[str, Any] = os.path.join(a__ , F"""{artifact_name}.zip""" ) with open(a__ , 'wb' ) as fp: fp.write(response.content ) def UpperCAmelCase ( a__ , a__=None ): '''simple docstring''' lowerCAmelCase :Optional[Any] = [] lowerCAmelCase :Dict = [] lowerCAmelCase :Optional[Any] = None with zipfile.ZipFile(a__ ) as z: for filename in z.namelist(): if not os.path.isdir(a__ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(a__ ) as f: for line in f: lowerCAmelCase :int = line.decode('UTF-8' ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs lowerCAmelCase :int = line[: line.index(': ' )] lowerCAmelCase :int = line[line.index(': ' ) + len(': ' ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith('FAILED ' ): # `test` is the test method that failed lowerCAmelCase :int = line[len('FAILED ' ) :] failed_tests.append(a__ ) elif filename == "job_name.txt": lowerCAmelCase :List[str] = line if len(a__ ) != len(a__ ): raise ValueError( F"""`errors` and `failed_tests` should have the same number of elements. Got {len(a__ )} for `errors` """ F"""and {len(a__ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some""" ' problem.' ) lowerCAmelCase :Optional[int] = None if job_name and job_links: lowerCAmelCase :Dict = job_links.get(a__ , a__ ) # A list with elements of the form (line of error, error, failed test) lowerCAmelCase :Union[str, Any] = [x + [y] + [job_link] for x, y in zip(a__ , a__ )] return result def UpperCAmelCase ( a__ , a__=None ): '''simple docstring''' lowerCAmelCase :Any = [] lowerCAmelCase :Optional[int] = [os.path.join(a__ , a__ ) for p in os.listdir(a__ ) if p.endswith('.zip' )] for p in paths: errors.extend(get_errors_from_single_artifact(a__ , job_links=a__ ) ) return errors def UpperCAmelCase ( a__ , a__=None ): '''simple docstring''' lowerCAmelCase :int = Counter() counter.update([x[1] for x in logs] ) lowerCAmelCase :Tuple = counter.most_common() lowerCAmelCase :Dict = {} for error, count in counts: if error_filter is None or error not in error_filter: lowerCAmelCase :Optional[int] = {'count': count, 'failed_tests': [(x[2], x[0]) for x in logs if x[1] == error]} lowerCAmelCase :Optional[Any] = dict(sorted(r.items() , key=lambda a__ : item[1]["count"] , reverse=a__ ) ) return r def UpperCAmelCase ( a__ ): '''simple docstring''' lowerCAmelCase :Tuple = test.split('::' )[0] if test.startswith('tests/models/' ): lowerCAmelCase :Union[str, Any] = test.split('/' )[2] else: lowerCAmelCase :Optional[int] = None return test def UpperCAmelCase ( a__ , a__=None ): '''simple docstring''' lowerCAmelCase :str = [(x[0], x[1], get_model(x[2] )) for x in logs] lowerCAmelCase :Any = [x for x in logs if x[2] is not None] lowerCAmelCase :Tuple = {x[2] for x in logs} lowerCAmelCase :Optional[Any] = {} for test in tests: lowerCAmelCase :Union[str, Any] = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) lowerCAmelCase :List[str] = counter.most_common() lowerCAmelCase :str = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} lowerCAmelCase :Optional[Any] = sum(error_counts.values() ) if n_errors > 0: lowerCAmelCase :Dict = {'count': n_errors, 'errors': error_counts} lowerCAmelCase :Dict = dict(sorted(r.items() , key=lambda a__ : item[1]["count"] , reverse=a__ ) ) return r def UpperCAmelCase ( a__ ): '''simple docstring''' lowerCAmelCase :Any = '| no. | error | status |' lowerCAmelCase :Optional[int] = '|-:|:-|:-|' lowerCAmelCase :Tuple = [header, sep] for error in reduced_by_error: lowerCAmelCase :Optional[Any] = reduced_by_error[error]['count'] lowerCAmelCase :List[str] = F"""| {count} | {error[:1_00]} | |""" lines.append(a__ ) return "\n".join(a__ ) def UpperCAmelCase ( a__ ): '''simple docstring''' lowerCAmelCase :Any = '| model | no. of errors | major error | count |' lowerCAmelCase :int = '|-:|-:|-:|-:|' lowerCAmelCase :int = [header, sep] for model in reduced_by_model: lowerCAmelCase :Dict = reduced_by_model[model]['count'] lowerCAmelCase , lowerCAmelCase :Any = list(reduced_by_model[model]['errors'].items() )[0] lowerCAmelCase :Any = F"""| {model} | {count} | {error[:60]} | {_count} |""" lines.append(a__ ) return "\n".join(a__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') parser.add_argument( '--output_dir', type=str, required=True, help='Where to store the downloaded artifacts and other result files.', ) parser.add_argument('--token', default=None, type=str, help='A token that has actions:read permission.') __SCREAMING_SNAKE_CASE = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) __SCREAMING_SNAKE_CASE = get_job_links(args.workflow_run_id, token=args.token) __SCREAMING_SNAKE_CASE = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: __SCREAMING_SNAKE_CASE = k.find(' / ') __SCREAMING_SNAKE_CASE = k[index + len(' / ') :] __SCREAMING_SNAKE_CASE = v with open(os.path.join(args.output_dir, 'job_links.json'), 'w', encoding='UTF-8') as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) __SCREAMING_SNAKE_CASE = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, 'artifacts.json'), 'w', encoding='UTF-8') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) __SCREAMING_SNAKE_CASE = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error __SCREAMING_SNAKE_CASE = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors __SCREAMING_SNAKE_CASE = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, 'errors.json'), 'w', encoding='UTF-8') as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) __SCREAMING_SNAKE_CASE = reduce_by_error(errors) __SCREAMING_SNAKE_CASE = reduce_by_model(errors) __SCREAMING_SNAKE_CASE = make_github_table(reduced_by_error) __SCREAMING_SNAKE_CASE = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, 'reduced_by_error.txt'), 'w', encoding='UTF-8') as fp: fp.write(sa) with open(os.path.join(args.output_dir, 'reduced_by_model.txt'), 'w', encoding='UTF-8') as fp: fp.write(sa)
553
1
'''simple docstring''' def UpperCAmelCase ( lowerCamelCase_ :list ): '''simple docstring''' snake_case_ : Optional[Any] = len(lowerCamelCase_ ) for _ in range(lowerCamelCase_ ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: snake_case_ , snake_case_ : Optional[int] = arr[i + 1], arr[i] return arr if __name__ == "__main__": __A : str = list(range(10, 0, -1)) print(F'Original: {arr}. Sorted: {odd_even_transposition(arr)}')
267
'''simple docstring''' def UpperCAmelCase ( lowerCamelCase_ :int ): '''simple docstring''' if num < 0: return False snake_case_ : int = num snake_case_ : int = 0 while num > 0: snake_case_ : Tuple = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
267
1
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor lowerCAmelCase : Any = logging.get_logger(__name__) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" def __init__( self : str , *lowerCAmelCase__ : List[Any] , **lowerCAmelCase__ : Tuple): warnings.warn( "The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use GLPNImageProcessor instead." , lowerCAmelCase__ , ) super().__init__(*lowerCAmelCase__ , **lowerCAmelCase__)
671
def A_ ( _UpperCAmelCase ): if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE_: List[Any] = str(abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple = [list(_UpperCAmelCase ) for char in range(len(_UpperCAmelCase ) )] for index in range(len(_UpperCAmelCase ) ): num_transpositions[index].pop(_UpperCAmelCase ) return max( int("".join(list(_UpperCAmelCase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
671
1
'''simple docstring''' import copy from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging UpperCAmelCase__ : Any = logging.get_logger(__name__) class a__ ( UpperCAmelCase ): """simple docstring""" UpperCAmelCase__ : List[str] =["""input_features"""] def __init__( self : str , UpperCAmelCase__ : Tuple=8_0 , UpperCAmelCase__ : Tuple=1_6_0_0_0 , UpperCAmelCase__ : List[str]=1_6_0 , UpperCAmelCase__ : List[Any]=3_0 , UpperCAmelCase__ : str=4_0_0 , UpperCAmelCase__ : Any=0.0 , UpperCAmelCase__ : Optional[int]=False , **UpperCAmelCase__ : List[Any] , ) ->Any: """simple docstring""" super().__init__( feature_size=UpperCAmelCase__ , sampling_rate=UpperCAmelCase__ , padding_value=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , **UpperCAmelCase__ , ) SCREAMING_SNAKE_CASE : List[str] = n_fft SCREAMING_SNAKE_CASE : Optional[int] = hop_length SCREAMING_SNAKE_CASE : Optional[Any] = chunk_length SCREAMING_SNAKE_CASE : str = chunk_length * sampling_rate SCREAMING_SNAKE_CASE : List[str] = self.n_samples // hop_length SCREAMING_SNAKE_CASE : Optional[Any] = sampling_rate SCREAMING_SNAKE_CASE : Union[str, Any] = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=UpperCAmelCase__ , min_frequency=0.0 , max_frequency=8_0_0_0.0 , sampling_rate=UpperCAmelCase__ , norm="""slaney""" , mel_scale="""slaney""" , ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : np.array ) ->np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = spectrogram( UpperCAmelCase__ , window_function(self.n_fft , """hann""" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel="""log10""" , ) SCREAMING_SNAKE_CASE : str = log_spec[:, :-1] SCREAMING_SNAKE_CASE : Union[str, Any] = np.maximum(UpperCAmelCase__ , log_spec.max() - 8.0 ) SCREAMING_SNAKE_CASE : List[Any] = (log_spec + 4.0) / 4.0 return log_spec @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def _lowercase ( UpperCAmelCase__ : List[np.ndarray] , UpperCAmelCase__ : List[np.ndarray] , UpperCAmelCase__ : float = 0.0 ) ->List[np.ndarray]: """simple docstring""" if attention_mask is not None: SCREAMING_SNAKE_CASE : List[str] = np.array(UpperCAmelCase__ , np.intaa ) SCREAMING_SNAKE_CASE : Dict = [] for vector, length in zip(UpperCAmelCase__ , attention_mask.sum(-1 ) ): SCREAMING_SNAKE_CASE : Tuple = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 ) if length < normed_slice.shape[0]: SCREAMING_SNAKE_CASE : int = padding_value normed_input_values.append(UpperCAmelCase__ ) else: SCREAMING_SNAKE_CASE : str = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values] return normed_input_values def __call__( self : Optional[int] , UpperCAmelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[str] = "max_length" , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[bool] = None , **UpperCAmelCase__ : Dict , ) ->BatchFeature: """simple docstring""" if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a" f" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input" f" was sampled with {self.sampling_rate} and not {sampling_rate}." ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) SCREAMING_SNAKE_CASE : List[Any] = isinstance(UpperCAmelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"Only mono-channel audio is supported for input to {self}" ) SCREAMING_SNAKE_CASE : Tuple = is_batched_numpy or ( isinstance(UpperCAmelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE : Tuple = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(UpperCAmelCase__ , np.ndarray ): SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(UpperCAmelCase__ , dtype=np.floataa ) elif isinstance(UpperCAmelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE : Any = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE : Optional[Any] = [np.asarray([raw_speech] ).T] SCREAMING_SNAKE_CASE : List[str] = BatchFeature({"""input_features""": raw_speech} ) # convert into correct format for padding SCREAMING_SNAKE_CASE : Tuple = self.pad( UpperCAmelCase__ , padding=UpperCAmelCase__ , max_length=max_length if max_length else self.n_samples , truncation=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_attention_mask=return_attention_mask or do_normalize , ) # zero-mean and unit-variance normalization if do_normalize: SCREAMING_SNAKE_CASE : Optional[Any] = self.zero_mean_unit_var_norm( padded_inputs["""input_features"""] , attention_mask=padded_inputs["""attention_mask"""] , padding_value=self.padding_value , ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.stack(padded_inputs["""input_features"""] , axis=0 ) # make sure list is in array format SCREAMING_SNAKE_CASE : str = padded_inputs.get("""input_features""" ).transpose(2 , 0 , 1 ) SCREAMING_SNAKE_CASE : str = [self._np_extract_fbank_features(UpperCAmelCase__ ) for waveform in input_features[0]] if isinstance(input_features[0] , UpperCAmelCase__ ): SCREAMING_SNAKE_CASE : int = [np.asarray(UpperCAmelCase__ , dtype=np.floataa ) for feature in input_features] else: SCREAMING_SNAKE_CASE : List[Any] = input_features if return_attention_mask: # rescale from sample (48000) to feature (3000) SCREAMING_SNAKE_CASE : List[str] = padded_inputs["""attention_mask"""][:, :: self.hop_length] if return_tensors is not None: SCREAMING_SNAKE_CASE : Tuple = padded_inputs.convert_to_tensors(UpperCAmelCase__ ) return padded_inputs def _lowercase ( self : List[str] ) ->Dict[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] return output
702
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCAmelCase__ : str = {"""processing_layoutxlm""": ["""LayoutXLMProcessor"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Any = ["""LayoutXLMTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : List[str] = ["""LayoutXLMTokenizerFast"""] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys UpperCAmelCase__ : List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
446
0
import torch from diffusers import StableDiffusionPipeline __snake_case = '''path-to-your-trained-model''' __snake_case = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to('''cuda''') __snake_case = '''A photo of sks dog in a bucket''' __snake_case = pipe(prompt, num_inference_steps=5_0, guidance_scale=7.5).images[0] image.save('''dog-bucket.png''')
1
def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def SCREAMING_SNAKE_CASE ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
87
0
from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : list[int] ,lowerCAmelCase_ : list[int] ,lowerCAmelCase_ : list[int] ,lowerCAmelCase_ : list[list[str]] ,lowerCAmelCase_ : int ,) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : int =len(SCREAMING_SNAKE_CASE_ ) # 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(SCREAMING_SNAKE_CASE_ ): # 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] ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,) def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : int ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : list[list[str]] =[] depth_first_search([] ,[] ,[] ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) # Print all the boards for board in boards: for column in board: print(SCREAMING_SNAKE_CASE_ ) print('' ) print(len(SCREAMING_SNAKE_CASE_ ) ,'solutions were found.' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
702
from __future__ import annotations __SCREAMING_SNAKE_CASE = '#' class lowerCAmelCase_ : '''simple docstring''' def __init__( self ): SCREAMING_SNAKE_CASE_ : dict ={} def __lowerCamelCase ( self , __UpperCAmelCase ): SCREAMING_SNAKE_CASE_ : Tuple =self._trie for char in text: if char not in trie: SCREAMING_SNAKE_CASE_ : Optional[int] ={} SCREAMING_SNAKE_CASE_ : Any =trie[char] SCREAMING_SNAKE_CASE_ : Optional[Any] =True def __lowerCamelCase ( self , __UpperCAmelCase ): SCREAMING_SNAKE_CASE_ : Tuple =self._trie for char in prefix: if char in trie: SCREAMING_SNAKE_CASE_ : Tuple =trie[char] else: return [] return self._elements(__UpperCAmelCase ) def __lowerCamelCase ( self , __UpperCAmelCase ): SCREAMING_SNAKE_CASE_ : Optional[int] =[] for c, v in d.items(): SCREAMING_SNAKE_CASE_ : List[Any] =[' '] if c == END else [(c + s) for s in self._elements(__UpperCAmelCase )] result.extend(__UpperCAmelCase ) return tuple(__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = Trie() __SCREAMING_SNAKE_CASE = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : str ) -> tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : str =trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def SCREAMING_SNAKE_CASE__ ( ) -> None: """simple docstring""" print(autocomplete_using_trie('de' ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
153
0
import os # Precomputes a list of the 100 first triangular numbers __A = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def lowerCAmelCase_ ( ) -> List[str]: """simple docstring""" lowerCamelCase__: Optional[Any] =os.path.dirname(os.path.realpath(__a ) ) lowerCamelCase__: Optional[int] =os.path.join(__a , "words.txt" ) lowerCamelCase__: Dict ="" with open(__a ) as f: lowerCamelCase__: int =f.readline() lowerCamelCase__: Any =[word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCamelCase__: Optional[Any] =[ word for word in [sum(ord(__a ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(__a ) if __name__ == "__main__": print(solution())
59
"""simple docstring""" import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase : Any = logging.get_logger(__name__) def A ( _A ): """simple docstring""" snake_case_ :List[str] = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: snake_case_ :List[str] = 128 elif "12-12" in model_name: snake_case_ :Union[str, Any] = 12 snake_case_ :Optional[Any] = 12 elif "14-14" in model_name: snake_case_ :Any = 14 snake_case_ :Union[str, Any] = 14 elif "16-16" in model_name: snake_case_ :List[Any] = 16 snake_case_ :Dict = 16 else: raise ValueError("Model not supported" ) snake_case_ :Tuple = "huggingface/label-files" if "speech-commands" in model_name: snake_case_ :Union[str, Any] = 35 snake_case_ :Union[str, Any] = "speech-commands-v2-id2label.json" else: snake_case_ :Union[str, Any] = 527 snake_case_ :List[str] = "audioset-id2label.json" snake_case_ :Any = json.load(open(hf_hub_download(_A, _A, repo_type="dataset" ), "r" ) ) snake_case_ :Union[str, Any] = {int(_A ): v for k, v in idalabel.items()} snake_case_ :Union[str, Any] = idalabel snake_case_ :Any = {v: k for k, v in idalabel.items()} return config def A ( _A ): """simple docstring""" if "module.v" in name: snake_case_ :Optional[Any] = name.replace("module.v", "audio_spectrogram_transformer" ) if "cls_token" in name: snake_case_ :Optional[Any] = name.replace("cls_token", "embeddings.cls_token" ) if "dist_token" in name: snake_case_ :str = name.replace("dist_token", "embeddings.distillation_token" ) if "pos_embed" in name: snake_case_ :Union[str, Any] = name.replace("pos_embed", "embeddings.position_embeddings" ) if "patch_embed.proj" in name: snake_case_ :List[str] = name.replace("patch_embed.proj", "embeddings.patch_embeddings.projection" ) # transformer blocks if "blocks" in name: snake_case_ :Optional[Any] = name.replace("blocks", "encoder.layer" ) if "attn.proj" in name: snake_case_ :List[Any] = name.replace("attn.proj", "attention.output.dense" ) if "attn" in name: snake_case_ :Optional[Any] = name.replace("attn", "attention.self" ) if "norm1" in name: snake_case_ :Tuple = name.replace("norm1", "layernorm_before" ) if "norm2" in name: snake_case_ :Dict = name.replace("norm2", "layernorm_after" ) if "mlp.fc1" in name: snake_case_ :int = name.replace("mlp.fc1", "intermediate.dense" ) if "mlp.fc2" in name: snake_case_ :int = name.replace("mlp.fc2", "output.dense" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: snake_case_ :Optional[int] = name.replace("audio_spectrogram_transformer.norm", "audio_spectrogram_transformer.layernorm" ) # classifier head if "module.mlp_head.0" in name: snake_case_ :Any = name.replace("module.mlp_head.0", "classifier.layernorm" ) if "module.mlp_head.1" in name: snake_case_ :str = name.replace("module.mlp_head.1", "classifier.dense" ) return name def A ( _A, _A ): """simple docstring""" for key in orig_state_dict.copy().keys(): snake_case_ :int = orig_state_dict.pop(_A ) if "qkv" in key: snake_case_ :Optional[Any] = key.split("." ) snake_case_ :Union[str, Any] = int(key_split[3] ) snake_case_ :str = config.hidden_size if "weight" in key: snake_case_ :Any = val[:dim, :] snake_case_ :Optional[Any] = val[dim : dim * 2, :] snake_case_ :List[Any] = val[-dim:, :] else: snake_case_ :str = val[:dim] snake_case_ :Optional[Any] = val[dim : dim * 2] snake_case_ :Any = val[-dim:] else: snake_case_ :int = val return orig_state_dict def A ( _A ): """simple docstring""" snake_case_ :Any = [ "module.v.head.weight", "module.v.head.bias", "module.v.head_dist.weight", "module.v.head_dist.bias", ] for k in ignore_keys: state_dict.pop(_A, _A ) @torch.no_grad() def A ( _A, _A, _A=False ): """simple docstring""" snake_case_ :Any = get_audio_spectrogram_transformer_config(_A ) snake_case_ :List[str] = { "ast-finetuned-audioset-10-10-0.4593": ( "https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1" ), "ast-finetuned-audioset-10-10-0.450": ( "https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1" ), "ast-finetuned-audioset-10-10-0.448": ( "https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1" ), "ast-finetuned-audioset-10-10-0.448-v2": ( "https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1" ), "ast-finetuned-audioset-12-12-0.447": ( "https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1" ), "ast-finetuned-audioset-14-14-0.443": ( "https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1" ), "ast-finetuned-audioset-16-16-0.442": ( "https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1" ), "ast-finetuned-speech-commands-v2": ( "https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1" ), } # load original state_dict snake_case_ :Optional[int] = model_name_to_url[model_name] snake_case_ :str = torch.hub.load_state_dict_from_url(_A, map_location="cpu" ) # remove some keys remove_keys(_A ) # rename some keys snake_case_ :int = convert_state_dict(_A, _A ) # load 🤗 model snake_case_ :str = ASTForAudioClassification(_A ) model.eval() model.load_state_dict(_A ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 snake_case_ :int = -4.2_677_393 if "speech-commands" not in model_name else -6.845_978 snake_case_ :Union[str, Any] = 4.5_689_974 if "speech-commands" not in model_name else 5.5_654_526 snake_case_ :Union[str, Any] = 1_024 if "speech-commands" not in model_name else 128 snake_case_ :Optional[int] = ASTFeatureExtractor(mean=_A, std=_A, max_length=_A ) if "speech-commands" in model_name: snake_case_ :Optional[int] = load_dataset("speech_commands", "v0.02", split="validation" ) snake_case_ :int = dataset[0]["audio"]["array"] else: snake_case_ :Any = hf_hub_download( repo_id="nielsr/audio-spectogram-transformer-checkpoint", filename="sample_audio.flac", repo_type="dataset", ) snake_case_ , snake_case_ :List[Any] = torchaudio.load(_A ) snake_case_ :Optional[int] = waveform.squeeze().numpy() snake_case_ :Any = feature_extractor(_A, sampling_rate=16_000, return_tensors="pt" ) # forward pass snake_case_ :Dict = model(**_A ) snake_case_ :List[str] = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": snake_case_ :Optional[int] = torch.tensor([-0.8_760, -7.0_042, -8.6_602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": snake_case_ :Any = torch.tensor([-1.1_986, -7.0_903, -8.2_718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": snake_case_ :List[Any] = torch.tensor([-2.6_128, -8.0_080, -9.4_344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": snake_case_ :Dict = torch.tensor([-1.5_080, -7.4_534, -8.8_917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": snake_case_ :int = torch.tensor([-0.5_050, -6.5_833, -8.0_843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": snake_case_ :Dict = torch.tensor([-0.3_826, -7.0_336, -8.2_413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": snake_case_ :List[str] = torch.tensor([-1.2_113, -6.9_101, -8.3_470] ) elif model_name == "ast-finetuned-speech-commands-v2": snake_case_ :Optional[Any] = torch.tensor([6.1_589, -8.0_566, -8.7_984] ) else: raise ValueError("Unknown model name" ) if not torch.allclose(logits[0, :3], _A, atol=1e-4 ): raise ValueError("Logits don't match" ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(_A ).mkdir(exist_ok=_A ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_A ) print(F'''Saving feature extractor to {pytorch_dump_folder_path}''' ) feature_extractor.save_pretrained(_A ) if push_to_hub: print("Pushing model and feature extractor to the hub..." ) model.push_to_hub(F'''MIT/{model_name}''' ) feature_extractor.push_to_hub(F'''MIT/{model_name}''' ) if __name__ == "__main__": __UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='ast-finetuned-audioset-10-10-0.4593', type=str, help='Name of the Audio Spectrogram Transformer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __UpperCAmelCase : Optional[Any] = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
584
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 lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = { """facebook/levit-128S""": """https://huggingface.co/facebook/levit-128S/resolve/main/config.json""", # See all LeViT models at https://huggingface.co/models?filter=levit } class a__ ( __snake_case ): A__ : Optional[Any] = 'levit' def __init__( self , UpperCAmelCase=2_2_4 , UpperCAmelCase=3 , UpperCAmelCase=3 , UpperCAmelCase=2 , UpperCAmelCase=1 , UpperCAmelCase=1_6 , UpperCAmelCase=[1_2_8, 2_5_6, 3_8_4] , UpperCAmelCase=[4, 8, 1_2] , UpperCAmelCase=[4, 4, 4] , UpperCAmelCase=[1_6, 1_6, 1_6] , UpperCAmelCase=0 , UpperCAmelCase=[2, 2, 2] , UpperCAmelCase=[2, 2, 2] , UpperCAmelCase=0.02 , **UpperCAmelCase , ) -> str: super().__init__(**UpperCAmelCase ) __a = image_size __a = num_channels __a = kernel_size __a = stride __a = padding __a = hidden_sizes __a = num_attention_heads __a = depths __a = key_dim __a = drop_path_rate __a = patch_size __a = attention_ratio __a = mlp_ratio __a = initializer_range __a = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class a__ ( __snake_case ): A__ : Optional[int] = version.parse('1.11' ) @property def __SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __SCREAMING_SNAKE_CASE ( self ) -> float: return 1e-4
246
import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor lowerCamelCase_ : Dict = logging.get_logger(__name__) class a__ ( __snake_case ): def __init__( self , *UpperCAmelCase , **UpperCAmelCase ) -> None: warnings.warn( 'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use BeitImageProcessor instead.' , UpperCAmelCase , ) super().__init__(*UpperCAmelCase , **UpperCAmelCase )
246
1
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> list: UpperCamelCase = int(__UpperCamelCase ) if n_element < 1: UpperCamelCase = ValueError("""a should be a positive number""" ) raise my_error UpperCamelCase = [1] UpperCamelCase ,UpperCamelCase ,UpperCamelCase = (0, 0, 0) UpperCamelCase = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') SCREAMING_SNAKE_CASE__ = hamming(int(n)) print('-----------------------------------------------------') print(f'The list with nth numbers is: {hamming_numbers}') print('-----------------------------------------------------')
301
'''simple docstring''' import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { 'facebook/detr-resnet-50': 'https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json', # See all DETR models at https://huggingface.co/models?filter=detr } class a_ ( lowerCamelCase ): lowercase = """detr""" lowercase = ["""past_key_values"""] lowercase = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _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.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE="resnet50" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _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 , ) -> List[Any]: """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) UpperCamelCase = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = backbone_config.get("""model_type""" ) UpperCamelCase = CONFIG_MAPPING[backbone_model_type] UpperCamelCase = config_class.from_dict(_SCREAMING_SNAKE_CASE ) # set timm attributes to None UpperCamelCase ,UpperCamelCase ,UpperCamelCase = None, None, None UpperCamelCase = use_timm_backbone UpperCamelCase = backbone_config UpperCamelCase = num_channels UpperCamelCase = num_queries UpperCamelCase = d_model UpperCamelCase = encoder_ffn_dim UpperCamelCase = encoder_layers UpperCamelCase = encoder_attention_heads UpperCamelCase = decoder_ffn_dim UpperCamelCase = decoder_layers UpperCamelCase = decoder_attention_heads UpperCamelCase = dropout UpperCamelCase = attention_dropout UpperCamelCase = activation_dropout UpperCamelCase = activation_function UpperCamelCase = init_std UpperCamelCase = init_xavier_std UpperCamelCase = encoder_layerdrop UpperCamelCase = decoder_layerdrop UpperCamelCase = encoder_layers UpperCamelCase = auxiliary_loss UpperCamelCase = position_embedding_type UpperCamelCase = backbone UpperCamelCase = use_pretrained_backbone UpperCamelCase = dilation # Hungarian matcher UpperCamelCase = class_cost UpperCamelCase = bbox_cost UpperCamelCase = giou_cost # Loss coefficients UpperCamelCase = mask_loss_coefficient UpperCamelCase = dice_loss_coefficient UpperCamelCase = bbox_loss_coefficient UpperCamelCase = giou_loss_coefficient UpperCamelCase = eos_coefficient super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def A__ ( self ) -> int: """simple docstring""" return self.encoder_attention_heads @property def A__ ( self ) -> int: """simple docstring""" return self.d_model @classmethod def A__ ( cls , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" return cls(backbone_config=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Dict[str, any]: """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: UpperCamelCase = self.backbone_config.to_dict() UpperCamelCase = self.__class__.model_type return output class a_ ( lowerCamelCase ): lowercase = version.parse("""1.11""" ) @property def A__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def A__ ( self ) -> float: """simple docstring""" return 1e-5 @property def A__ ( self ) -> int: """simple docstring""" return 12
301
1
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): @property def _lowercase ( self : Any): torch.manual_seed(0) A__ : Dict = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , ) return model def _lowercase ( self : List[Any]): A__ : Tuple = self.dummy_uncond_unet A__ : Any = ScoreSdeVeScheduler() A__ : Optional[Any] = ScoreSdeVePipeline(unet=A_ , scheduler=A_) sde_ve.to(A_) sde_ve.set_progress_bar_config(disable=A_) A__ : Tuple = torch.manual_seed(0) A__ : List[str] = sde_ve(num_inference_steps=2 , output_type="numpy" , generator=A_).images A__ : int = torch.manual_seed(0) A__ : List[str] = sde_ve(num_inference_steps=2 , output_type="numpy" , generator=A_ , return_dict=A_)[ 0 ] A__ : str = image[0, -3:, -3:, -1] A__ : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A__ : Any = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2 @slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def _lowercase ( self : Union[str, Any]): A__ : str = "google/ncsnpp-church-256" A__ : str = UNetaDModel.from_pretrained(A_) A__ : Union[str, Any] = ScoreSdeVeScheduler.from_pretrained(A_) A__ : List[str] = ScoreSdeVePipeline(unet=A_ , scheduler=A_) sde_ve.to(A_) sde_ve.set_progress_bar_config(disable=A_) A__ : Tuple = torch.manual_seed(0) A__ : int = sde_ve(num_inference_steps=10 , output_type="numpy" , generator=A_).images A__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) A__ : Tuple = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
705
from collections.abc import Callable import numpy as np def snake_case__ ( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> np.array: """simple docstring""" A__ : Any = int(np.ceil((x_end - xa) / step_size ) ) A__ : Union[str, Any] = np.zeros((n + 1,) ) A__ : Any = ya A__ : Union[str, Any] = xa for k in range(__lowercase ): A__ : Any = y[k] + step_size * ode_func(__lowercase , y[k] ) A__ : Any = y[k] + ( (step_size / 2) * (ode_func(__lowercase , y[k] ) + ode_func(x + step_size , __lowercase )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
182
0
"""simple docstring""" import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class snake_case : def SCREAMING_SNAKE_CASE_ ( self :Any ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDConditionModel( sample_size=3_2 , layers_per_block=1 , block_out_channels=[3_2, 6_4] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=3 , out_channels=6 , cross_attention_dim=3_2 , encoder_hid_dim=3_2 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0_0_0_1 , beta_end=0.0_2 , thresholding=_lowerCamelCase , dynamic_thresholding_ratio=0.9_5 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Dict = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def SCREAMING_SNAKE_CASE_ ( self :Tuple ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[int] = UNetaDConditionModel( sample_size=3_2 , layers_per_block=[1, 2] , block_out_channels=[3_2, 6_4] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=6 , out_channels=6 , cross_attention_dim=3_2 , encoder_hid_dim=3_2 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , class_embed_type='''timestep''' , mid_block_scale_factor=1.4_1_4 , time_embedding_act_fn='''gelu''' , time_embedding_dim=3_2 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0_0_0_1 , beta_end=0.0_2 , thresholding=_lowerCamelCase , dynamic_thresholding_ratio=0.9_5 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[str] = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0_0_0_1 , beta_end=0.0_2 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : int = self.get_dummy_components() __SCREAMING_SNAKE_CASE : Optional[int] = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''prompt'''] __SCREAMING_SNAKE_CASE : Tuple = inputs['''generator'''] __SCREAMING_SNAKE_CASE : Optional[Any] = inputs['''num_inference_steps'''] __SCREAMING_SNAKE_CASE : Union[str, Any] = inputs['''output_type'''] if "image" in inputs: __SCREAMING_SNAKE_CASE : Tuple = inputs['''image'''] else: __SCREAMING_SNAKE_CASE : Tuple = None if "mask_image" in inputs: __SCREAMING_SNAKE_CASE : Dict = inputs['''mask_image'''] else: __SCREAMING_SNAKE_CASE : str = None if "original_image" in inputs: __SCREAMING_SNAKE_CASE : Union[str, Any] = inputs['''original_image'''] else: __SCREAMING_SNAKE_CASE : Tuple = None __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = pipe.encode_prompt(_lowerCamelCase ) # inputs with prompt converted to embeddings __SCREAMING_SNAKE_CASE : Optional[int] = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: __SCREAMING_SNAKE_CASE : Tuple = image if mask_image is not None: __SCREAMING_SNAKE_CASE : Optional[Any] = mask_image if original_image is not None: __SCREAMING_SNAKE_CASE : str = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = pipe(**_lowerCamelCase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = self.pipeline_class.from_pretrained(_lowerCamelCase ) pipe_loaded.to(_lowerCamelCase ) pipe_loaded.set_progress_bar_config(disable=_lowerCamelCase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(_lowerCamelCase , _lowerCamelCase ) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = inputs['''generator'''] __SCREAMING_SNAKE_CASE : List[str] = inputs['''num_inference_steps'''] __SCREAMING_SNAKE_CASE : Union[str, Any] = inputs['''output_type'''] # inputs with prompt converted to embeddings __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: __SCREAMING_SNAKE_CASE : int = image if mask_image is not None: __SCREAMING_SNAKE_CASE : Optional[Any] = mask_image if original_image is not None: __SCREAMING_SNAKE_CASE : Tuple = original_image __SCREAMING_SNAKE_CASE : List[Any] = pipe_loaded(**_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : Any = np.abs(to_np(_lowerCamelCase ) - to_np(_lowerCamelCase ) ).max() self.assertLess(_lowerCamelCase , 1e-4 ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_components() __SCREAMING_SNAKE_CASE : str = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = pipe(**_lowerCamelCase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = self.pipeline_class.from_pretrained(_lowerCamelCase ) pipe_loaded.to(_lowerCamelCase ) pipe_loaded.set_progress_bar_config(disable=_lowerCamelCase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = pipe_loaded(**_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : Optional[int] = np.abs(to_np(_lowerCamelCase ) - to_np(_lowerCamelCase ) ).max() self.assertLess(_lowerCamelCase , 1e-4 )
674
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
1
from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Any = logging.get_logger(__name__) A__: Optional[Any] = { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json''' ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class _a ( UpperCamelCase__): """simple docstring""" UpperCamelCase__ = """speech_to_text_2""" UpperCamelCase__ = ["""past_key_values"""] UpperCamelCase__ = {"""num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self: Optional[int] , __lowerCamelCase: str=1_0000 , __lowerCamelCase: Optional[int]=6 , __lowerCamelCase: Dict=2048 , __lowerCamelCase: Optional[Any]=4 , __lowerCamelCase: Optional[int]=0.0 , __lowerCamelCase: str=True , __lowerCamelCase: List[str]="relu" , __lowerCamelCase: List[str]=256 , __lowerCamelCase: Any=0.1 , __lowerCamelCase: Optional[Any]=0.0 , __lowerCamelCase: int=0.0 , __lowerCamelCase: Optional[int]=0.02 , __lowerCamelCase: str=2 , __lowerCamelCase: Optional[Any]=True , __lowerCamelCase: Optional[int]=1 , __lowerCamelCase: Tuple=0 , __lowerCamelCase: Optional[Any]=2 , __lowerCamelCase: Optional[Any]=1024 , **__lowerCamelCase: Optional[Any] , ): '''simple docstring''' UpperCamelCase__: Optional[Any] = vocab_size UpperCamelCase__: Optional[Any] = d_model UpperCamelCase__: Tuple = decoder_ffn_dim UpperCamelCase__: Union[str, Any] = decoder_layers UpperCamelCase__: Tuple = decoder_attention_heads UpperCamelCase__: Any = dropout UpperCamelCase__: List[str] = attention_dropout UpperCamelCase__: List[Any] = activation_dropout UpperCamelCase__: Tuple = activation_function UpperCamelCase__: Dict = init_std UpperCamelCase__: int = decoder_layerdrop UpperCamelCase__: Tuple = use_cache UpperCamelCase__: Optional[Any] = decoder_layers UpperCamelCase__: Tuple = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase__: Dict = max_target_positions super().__init__( pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , decoder_start_token_id=__lowerCamelCase , **__lowerCamelCase , )
721
def lowerCAmelCase_ ( ): for n in range(1 ,1_00_00_00): yield n * (n + 1) // 2 def lowerCAmelCase_ ( A_): UpperCamelCase__: int = 1 UpperCamelCase__: Dict = 2 while i * i <= n: UpperCamelCase__: Any = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def lowerCAmelCase_ ( ): return next(i for i in triangle_number_generator() if count_divisors(A_) > 5_00) if __name__ == "__main__": print(solution())
221
0
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class snake_case__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): SCREAMING_SNAKE_CASE__ = StableDiffusionPanoramaPipeline SCREAMING_SNAKE_CASE__ = TEXT_TO_IMAGE_PARAMS SCREAMING_SNAKE_CASE__ = TEXT_TO_IMAGE_BATCH_PARAMS SCREAMING_SNAKE_CASE__ = TEXT_TO_IMAGE_IMAGE_PARAMS SCREAMING_SNAKE_CASE__ = TEXT_TO_IMAGE_IMAGE_PARAMS def __lowerCAmelCase ( self : int ): '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) UpperCAmelCase : Any = DDIMScheduler() torch.manual_seed(0 ) UpperCAmelCase : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCAmelCase : 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 , ) UpperCAmelCase : Union[str, Any] = CLIPTextModel(lowercase ) UpperCAmelCase : Any = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) UpperCAmelCase : Optional[Any] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def __lowerCAmelCase ( self : str , lowercase : Optional[int] , lowercase : Optional[int]=0 ): '''simple docstring''' UpperCAmelCase : List[str] = torch.manual_seed(lowercase ) UpperCAmelCase : List[str] = { "prompt": "a photo of the dolomites", "generator": generator, # Setting height and width to None to prevent OOMs on CPU. "height": None, "width": None, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def __lowerCAmelCase ( self : int ): '''simple docstring''' UpperCAmelCase : Tuple = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase : Dict = self.get_dummy_components() UpperCAmelCase : Optional[Any] = StableDiffusionPanoramaPipeline(**lowercase ) UpperCAmelCase : int = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) UpperCAmelCase : Optional[Any] = self.get_dummy_inputs(lowercase ) UpperCAmelCase : Optional[Any] = sd_pipe(**lowercase ).images UpperCAmelCase : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase : int = np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25E-3 ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase : Tuple = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase : Any = self.get_dummy_components() UpperCAmelCase : Union[str, Any] = StableDiffusionPanoramaPipeline(**lowercase ) UpperCAmelCase : str = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) UpperCAmelCase : int = self.get_dummy_inputs(lowercase ) UpperCAmelCase : Optional[Any] = "french fries" UpperCAmelCase : Optional[int] = sd_pipe(**lowercase , negative_prompt=lowercase ) UpperCAmelCase : Optional[Any] = output.images UpperCAmelCase : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase : Optional[Any] = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCAmelCase ( self : int ): '''simple docstring''' UpperCAmelCase : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase : Dict = self.get_dummy_components() UpperCAmelCase : int = StableDiffusionPanoramaPipeline(**lowercase ) UpperCAmelCase : int = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) UpperCAmelCase : Optional[int] = self.get_dummy_inputs(lowercase ) UpperCAmelCase : Optional[int] = sd_pipe(**lowercase , view_batch_size=2 ) UpperCAmelCase : int = output.images UpperCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase : Dict = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCAmelCase ( self : str ): '''simple docstring''' UpperCAmelCase : str = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase : List[Any] = self.get_dummy_components() UpperCAmelCase : List[str] = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" ) UpperCAmelCase : List[Any] = StableDiffusionPanoramaPipeline(**lowercase ) UpperCAmelCase : Dict = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) UpperCAmelCase : List[str] = self.get_dummy_inputs(lowercase ) UpperCAmelCase : List[Any] = sd_pipe(**lowercase ).images UpperCAmelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase : Optional[Any] = np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCAmelCase ( self : Dict ): '''simple docstring''' UpperCAmelCase : int = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase : Optional[int] = self.get_dummy_components() UpperCAmelCase : Optional[int] = PNDMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" , skip_prk_steps=lowercase ) UpperCAmelCase : List[Any] = StableDiffusionPanoramaPipeline(**lowercase ) UpperCAmelCase : Optional[int] = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) UpperCAmelCase : Union[str, Any] = self.get_dummy_inputs(lowercase ) UpperCAmelCase : List[str] = sd_pipe(**lowercase ).images UpperCAmelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase : Optional[Any] = np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : List[str] , lowercase : List[str]=0 ): '''simple docstring''' UpperCAmelCase : List[Any] = torch.manual_seed(lowercase ) UpperCAmelCase : str = { "prompt": "a photo of the dolomites", "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase : Union[str, Any] = "stabilityai/stable-diffusion-2-base" UpperCAmelCase : Optional[int] = DDIMScheduler.from_pretrained(lowercase , subfolder="scheduler" ) UpperCAmelCase : Optional[Any] = StableDiffusionPanoramaPipeline.from_pretrained(lowercase , scheduler=lowercase , safety_checker=lowercase ) pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) pipe.enable_attention_slicing() UpperCAmelCase : str = self.get_inputs() UpperCAmelCase : Union[str, Any] = pipe(**lowercase ).images UpperCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) UpperCAmelCase : List[Any] = np.array( [ 0.3_6_9_6_8_3_9_2, 0.2_7_0_2_5_3_7_2, 0.3_2_4_4_6_7_6_6, 0.2_8_3_7_9_3_8_7, 0.3_6_3_6_3_2_7_4, 0.3_0_7_3_3_3_4_7, 0.2_7_1_0_0_0_2_7, 0.2_7_0_5_4_1_2_5, 0.2_5_5_3_6_0_9_6, ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-2 def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase : str = StableDiffusionPanoramaPipeline.from_pretrained( "stabilityai/stable-diffusion-2-base" , safety_checker=lowercase ) UpperCAmelCase : Any = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) pipe.enable_attention_slicing() UpperCAmelCase : Any = self.get_inputs() UpperCAmelCase : List[Any] = pipe(**lowercase ).images UpperCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) UpperCAmelCase : Optional[int] = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def __lowerCAmelCase ( self : Dict ): '''simple docstring''' UpperCAmelCase : Dict = 0 def callback_fn(lowercase : int , lowercase : int , lowercase : torch.FloatTensor ) -> None: UpperCAmelCase : Dict = True nonlocal number_of_steps number_of_steps += 1 if step == 1: UpperCAmelCase : List[str] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) UpperCAmelCase : Tuple = latents[0, -3:, -3:, -1] UpperCAmelCase : Union[str, Any] = np.array( [ 0.1_8_6_8_1_8_6_9, 0.3_3_9_0_7_8_1_6, 0.5_3_6_1_2_7_6, 0.1_4_4_3_2_8_6_5, -0.0_2_8_5_6_6_1_1, -0.7_3_9_4_1_1_2_3, 0.2_3_3_9_7_9_8_7, 0.4_7_3_2_2_6_8_2, -0.3_7_8_2_3_1_6_4, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: UpperCAmelCase : Any = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) UpperCAmelCase : Dict = latents[0, -3:, -3:, -1] UpperCAmelCase : List[str] = np.array( [ 0.1_8_5_3_9_6_4_5, 0.3_3_9_8_7_2_4_8, 0.5_3_7_8_5_5_9, 0.1_4_4_3_7_1_4_2, -0.0_2_4_5_5_2_6_1, -0.7_3_3_8_3_1_7, 0.2_3_9_9_0_7_5_5, 0.4_7_3_5_6_2_7_2, -0.3_7_8_6_5_0_5, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 UpperCAmelCase : Optional[int] = False UpperCAmelCase : int = "stabilityai/stable-diffusion-2-base" UpperCAmelCase : Any = DDIMScheduler.from_pretrained(lowercase , subfolder="scheduler" ) UpperCAmelCase : Tuple = StableDiffusionPanoramaPipeline.from_pretrained(lowercase , scheduler=lowercase , safety_checker=lowercase ) UpperCAmelCase : List[str] = pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) pipe.enable_attention_slicing() UpperCAmelCase : int = self.get_inputs() pipe(**lowercase , callback=lowercase , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCAmelCase : int = "stabilityai/stable-diffusion-2-base" UpperCAmelCase : int = DDIMScheduler.from_pretrained(lowercase , subfolder="scheduler" ) UpperCAmelCase : str = StableDiffusionPanoramaPipeline.from_pretrained(lowercase , scheduler=lowercase , safety_checker=lowercase ) UpperCAmelCase : Optional[Any] = pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() UpperCAmelCase : Tuple = self.get_inputs() UpperCAmelCase : Tuple = pipe(**lowercase ) UpperCAmelCase : str = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
595
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() snake_case_ : Optional[Any] = logging.get_logger(__name__) def lowercase_ ( _lowercase : str ): '''simple docstring''' UpperCAmelCase : Any = "huggingface/label-files" UpperCAmelCase : List[Any] = "imagenet-1k-id2label.json" UpperCAmelCase : Optional[int] = json.load(open(hf_hub_download(_lowercase , _lowercase , repo_type="dataset" ) , "r" ) ) UpperCAmelCase : Union[str, Any] = {int(_lowercase ): v for k, v in idalabel.items()} UpperCAmelCase : Tuple = {v: k for k, v in idalabel.items()} UpperCAmelCase : List[Any] = "std_conv" if "bit" in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" UpperCAmelCase : Optional[Any] = BitConfig( conv_layer=_lowercase , num_labels=10_00 , idalabel=_lowercase , labelaid=_lowercase , ) return config def lowercase_ ( _lowercase : Dict ): '''simple docstring''' if "stem.conv" in name: UpperCAmelCase : int = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: UpperCAmelCase : List[Any] = name.replace("blocks" , "layers" ) if "head.fc" in name: UpperCAmelCase : List[Any] = name.replace("head.fc" , "classifier.1" ) if name.startswith("norm" ): UpperCAmelCase : str = "bit." + name if "bit" not in name and "classifier" not in name: UpperCAmelCase : int = "bit.encoder." + name return name def lowercase_ ( ): '''simple docstring''' UpperCAmelCase : Optional[Any] = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase : Union[str, Any] = Image.open(requests.get(_lowercase , stream=_lowercase ).raw ) return im @torch.no_grad() def lowercase_ ( _lowercase : Any , _lowercase : str , _lowercase : str=False ): '''simple docstring''' UpperCAmelCase : int = get_config(_lowercase ) # load original model from timm UpperCAmelCase : Dict = create_model(_lowercase , pretrained=_lowercase ) timm_model.eval() # load state_dict of original model UpperCAmelCase : Tuple = timm_model.state_dict() for key in state_dict.copy().keys(): UpperCAmelCase : Any = state_dict.pop(_lowercase ) UpperCAmelCase : Optional[int] = val.squeeze() if "head" in key else val # load HuggingFace model UpperCAmelCase : int = BitForImageClassification(_lowercase ) model.eval() model.load_state_dict(_lowercase ) # create image processor UpperCAmelCase : List[str] = create_transform(**resolve_data_config({} , model=_lowercase ) ) UpperCAmelCase : int = transform.transforms UpperCAmelCase : Dict = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } UpperCAmelCase : Tuple = BitImageProcessor( do_resize=_lowercase , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_lowercase , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=_lowercase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) UpperCAmelCase : Tuple = prepare_img() UpperCAmelCase : Optional[int] = transform(_lowercase ).unsqueeze(0 ) UpperCAmelCase : str = processor(_lowercase , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(_lowercase , _lowercase ) # verify logits with torch.no_grad(): UpperCAmelCase : Optional[int] = model(_lowercase ) UpperCAmelCase : Optional[int] = outputs.logits print("Logits:" , logits[0, :3] ) print("Predicted class:" , model.config.idalabel[logits.argmax(-1 ).item()] ) UpperCAmelCase : Optional[int] = timm_model(_lowercase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_lowercase , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(_lowercase ).mkdir(exist_ok=_lowercase ) print(F"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(_lowercase ) processor.save_pretrained(_lowercase ) if push_to_hub: print(F"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(F"""ybelkada/{model_name}""" ) processor.push_to_hub(F"""ybelkada/{model_name}""" ) if __name__ == "__main__": snake_case_ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""resnetv2_50x1_bitm""", type=str, help="""Name of the BiT timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to push the model to the hub.""", ) snake_case_ : Any = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
595
1
import requests from bsa import BeautifulSoup def lowerCamelCase__ ( __lowerCAmelCase : Union[str, Any] = "AAPL" ): """simple docstring""" lowerCAmelCase_ = F"""https://in.finance.yahoo.com/quote/{symbol}?s={symbol}""" lowerCAmelCase_ = BeautifulSoup(requests.get(lowerCamelCase_ ).text , "html.parser" ) lowerCAmelCase_ = 'My(6px) Pos(r) smartphone_Mt(6px)' return soup.find("div" , class_=class_ ).find("span" ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f"""Current {symbol:<4} stock price is {stock_price(symbol):>8}""")
706
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _A = "▁" _A = {"vocab_file": "spiece.model"} _A = { "vocab_file": {"google/pegasus-xsum": "https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"} } _A = { "google/pegasus-xsum": 5_12, } _A = logging.get_logger(__name__) class _lowerCAmelCase ( __a ): _lowercase =VOCAB_FILES_NAMES _lowercase =VOCAB_FILES_NAMES _lowercase =PRETRAINED_VOCAB_FILES_MAP _lowercase =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase =['''input_ids''', '''attention_mask'''] def __init__( self , _UpperCamelCase , _UpperCamelCase="<pad>" , _UpperCamelCase="</s>" , _UpperCamelCase="<unk>" , _UpperCamelCase="<mask_2>" , _UpperCamelCase="<mask_1>" , _UpperCamelCase=None , _UpperCamelCase=103 , _UpperCamelCase = None , **_UpperCamelCase , ) -> None: lowerCAmelCase_ = offset if additional_special_tokens is not None: if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError( f"""additional_special_tokens should be of type {type(_UpperCamelCase )}, but is""" f""" {type(_UpperCamelCase )}""" ) lowerCAmelCase_ = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f"""<unk_{i}>""" for i in range(len(_UpperCamelCase ) , self.offset - 1 ) ] if len(set(_UpperCamelCase ) ) != len(_UpperCamelCase ): raise ValueError( "Please make sure that the provided additional_special_tokens do not contain an incorrectly" f""" shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.""" ) lowerCAmelCase_ = additional_special_tokens_extended else: lowerCAmelCase_ = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f"""<unk_{i}>""" for i in range(2 , self.offset )] lowerCAmelCase_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_UpperCamelCase , unk_token=_UpperCamelCase , mask_token=_UpperCamelCase , pad_token=_UpperCamelCase , mask_token_sent=_UpperCamelCase , offset=_UpperCamelCase , additional_special_tokens=_UpperCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_UpperCamelCase , ) lowerCAmelCase_ = mask_token_sent lowerCAmelCase_ = vocab_file lowerCAmelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_UpperCamelCase ) # add special tokens to encoder dict lowerCAmelCase_ = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) lowerCAmelCase_ = {v: k for k, v in self.encoder.items()} @property def __a ( self ) -> int: return len(self.sp_model ) + self.offset def __a ( self ) -> Dict[str, int]: lowerCAmelCase_ = {self.convert_ids_to_tokens(_UpperCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> List[Any]: lowerCAmelCase_ = self.__dict__.copy() lowerCAmelCase_ = None return state def __setstate__( self , _UpperCamelCase ) -> Optional[int]: lowerCAmelCase_ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase_ = {} lowerCAmelCase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __a ( self , _UpperCamelCase ) -> List[str]: return self.sp_model.encode(_UpperCamelCase , out_type=_UpperCamelCase ) def __a ( self , _UpperCamelCase ) -> int: if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] lowerCAmelCase_ = self.sp_model.piece_to_id(_UpperCamelCase ) return sp_id + self.offset def __a ( self , _UpperCamelCase ) -> str: if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: lowerCAmelCase_ = self.sp_model.IdToPiece(index - self.offset ) return token def __a ( self , _UpperCamelCase ) -> Optional[Any]: lowerCAmelCase_ = [] lowerCAmelCase_ = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_UpperCamelCase ) + token lowerCAmelCase_ = [] else: current_sub_tokens.append(_UpperCamelCase ) out_string += self.sp_model.decode(_UpperCamelCase ) return out_string.strip() def __a ( self , _UpperCamelCase=False ) -> Optional[int]: return 1 def __a ( self , _UpperCamelCase ) -> int: lowerCAmelCase_ = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def __a ( self , _UpperCamelCase , _UpperCamelCase = None , _UpperCamelCase = False ) -> List[int]: if already_has_special_tokens: return self._special_token_mask(_UpperCamelCase ) elif token_ids_a is None: return self._special_token_mask(_UpperCamelCase ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def __a ( self , _UpperCamelCase , _UpperCamelCase=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def __a ( self , _UpperCamelCase , _UpperCamelCase = None ) -> Tuple[str]: if not os.path.isdir(_UpperCamelCase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCAmelCase_ = os.path.join( _UpperCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _UpperCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_UpperCamelCase , "wb" ) as fi: lowerCAmelCase_ = self.sp_model.serialized_model_proto() fi.write(_UpperCamelCase ) return (out_vocab_file,)
279
0
'''simple docstring''' from __future__ import annotations from PIL import Image # Define glider example a__ : Optional[int] = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] # Define blinker example a__ : List[Any] = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def __lowerCamelCase ( UpperCAmelCase_ ) ->list[list[int]]: snake_case__ = [] for i in range(len(UpperCAmelCase_ ) ): snake_case__ = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours snake_case__ = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(UpperCAmelCase_ ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(UpperCAmelCase_ ) - 1: neighbour_count += cells[i + 1][j] if i < len(UpperCAmelCase_ ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. snake_case__ = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(UpperCAmelCase_ ) return next_generation def __lowerCamelCase ( UpperCAmelCase_ , UpperCAmelCase_ ) ->list[Image.Image]: snake_case__ = [] for _ in range(UpperCAmelCase_ ): # Create output image snake_case__ = Image.new('RGB' , (len(cells[0] ), len(UpperCAmelCase_ )) ) snake_case__ = img.load() # Save cells to image for x in range(len(UpperCAmelCase_ ) ): for y in range(len(cells[0] ) ): snake_case__ = 2_55 - cells[y][x] * 2_55 snake_case__ = (colour, colour, colour) # Save image images.append(UpperCAmelCase_ ) snake_case__ = new_generation(UpperCAmelCase_ ) return images if __name__ == "__main__": a__ : Any = generate_images(GLIDER, 16) images[0].save('''out.gif''', save_all=True, append_images=images[1:])
368
'''simple docstring''' from collections import Counter from timeit import timeit def __lowerCamelCase ( UpperCAmelCase_ = "" , ) ->bool: return sum(c % 2 for c in Counter(input_str.replace(' ' , '' ).lower() ).values() ) < 2 def __lowerCamelCase ( UpperCAmelCase_ = "" ) ->bool: if len(UpperCAmelCase_ ) == 0: return True snake_case__ = input_str.replace(' ' , '' ).lower() # character_freq_dict: Stores the frequency of every character in the input string snake_case__ = {} for character in lower_case_input_str: snake_case__ = character_freq_dict.get(UpperCAmelCase_ , 0 ) + 1 snake_case__ = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def __lowerCamelCase ( UpperCAmelCase_ = "" ) ->None: print('\nFor string = ' , UpperCAmelCase_ , ':' ) print( '> can_string_be_rearranged_as_palindrome_counter()' , '\tans =' , can_string_be_rearranged_as_palindrome_counter(UpperCAmelCase_ ) , '\ttime =' , timeit( 'z.can_string_be_rearranged_as_palindrome_counter(z.check_str)' , setup='import __main__ as z' , ) , 'seconds' , ) print( '> can_string_be_rearranged_as_palindrome()' , '\tans =' , can_string_be_rearranged_as_palindrome(UpperCAmelCase_ ) , '\ttime =' , timeit( 'z.can_string_be_rearranged_as_palindrome(z.check_str)' , setup='import __main__ as z' , ) , 'seconds' , ) if __name__ == "__main__": a__ : str = input( '''Enter string to determine if it can be rearranged as a palindrome or not: ''' ).strip() benchmark(check_str) a__ : List[Any] = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"""{check_str} can {'' if status else 'not '}be rearranged as a palindrome""")
368
1
'''simple docstring''' import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, is_tf_available, is_torch_available, ) lowercase : Optional[int] = logging.getLogger(__name__) @dataclass(frozen=UpperCamelCase_ ) class _lowerCAmelCase : """simple docstring""" lowerCAmelCase = 42 lowerCAmelCase = 42 lowerCAmelCase = None lowerCAmelCase = None lowerCAmelCase = None @dataclass(frozen=UpperCamelCase_ ) class _lowerCAmelCase : """simple docstring""" lowerCAmelCase = 42 lowerCAmelCase = None lowerCAmelCase = None lowerCAmelCase = None lowerCAmelCase = None if is_torch_available(): import torch from torch.utils.data import Dataset class _lowerCAmelCase ( UpperCamelCase_ ): """simple docstring""" lowerCAmelCase = 42 def __init__( self : List[str] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : PreTrainedTokenizer , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int] = None , SCREAMING_SNAKE_CASE : str=False , SCREAMING_SNAKE_CASE : bool = False , ) -> List[Any]: """simple docstring""" lowerCAmelCase = hans_processors[task]() lowerCAmelCase = os.path.join( SCREAMING_SNAKE_CASE , "cached_{}_{}_{}_{}".format( "dev" if evaluate else "train" , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE , ) , ) lowerCAmelCase = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) lowerCAmelCase = label_list[2], label_list[1] lowerCAmelCase = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. lowerCAmelCase = cached_features_file + '.lock' with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) lowerCAmelCase = ( processor.get_dev_examples(SCREAMING_SNAKE_CASE ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE ) ) logger.info("Training examples: %s" , len(SCREAMING_SNAKE_CASE ) ) lowerCAmelCase = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) logger.info("Saving features into cached file %s" , SCREAMING_SNAKE_CASE ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self : Optional[int] ) -> str: """simple docstring""" return len(self.features ) def __getitem__( self : Optional[Any] , SCREAMING_SNAKE_CASE : int ) -> Dict: """simple docstring""" return self.features[i] def __A ( self : str ) -> str: """simple docstring""" return self.label_list if is_tf_available(): import tensorflow as tf class _lowerCAmelCase : """simple docstring""" lowerCAmelCase = 42 def __init__( self : Any , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : PreTrainedTokenizer , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int] = 1_2_8 , SCREAMING_SNAKE_CASE : Union[str, Any]=False , SCREAMING_SNAKE_CASE : bool = False , ) -> Dict: """simple docstring""" lowerCAmelCase = hans_processors[task]() lowerCAmelCase = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) lowerCAmelCase = label_list[2], label_list[1] lowerCAmelCase = label_list lowerCAmelCase = processor.get_dev_examples(SCREAMING_SNAKE_CASE ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE ) lowerCAmelCase = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def gen(): for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc="convert examples to features" ): if ex_index % 1_0_0_0_0 == 0: logger.info("Writing example %d of %d" % (ex_index, len(SCREAMING_SNAKE_CASE )) ) yield ( { "example_id": 0, "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label, ) lowerCAmelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ( { "example_id": tf.intaa, "input_ids": tf.intaa, "attention_mask": tf.intaa, "token_type_ids": tf.intaa, }, tf.intaa, ) , ( { "example_id": tf.TensorShape([] ), "input_ids": tf.TensorShape([None, None] ), "attention_mask": tf.TensorShape([None, None] ), "token_type_ids": tf.TensorShape([None, None] ), }, tf.TensorShape([] ), ) , ) def __A ( self : Dict ) -> str: """simple docstring""" return self.dataset def __len__( self : Tuple ) -> int: """simple docstring""" return len(self.features ) def __getitem__( self : Dict , SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Tuple: """simple docstring""" return self.features[i] def __A ( self : str ) -> Dict: """simple docstring""" return self.label_list class _lowerCAmelCase ( UpperCamelCase_ ): """simple docstring""" def __A ( self : str , SCREAMING_SNAKE_CASE : Dict ) -> int: """simple docstring""" return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE , "heuristics_train_set.txt" ) ) , "train" ) def __A ( self : Dict , SCREAMING_SNAKE_CASE : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE , "heuristics_evaluation_set.txt" ) ) , "dev" ) def __A ( self : Tuple ) -> List[Any]: """simple docstring""" return ["contradiction", "entailment", "neutral"] def __A ( self : Dict , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : int ) -> Any: """simple docstring""" lowerCAmelCase = [] for i, line in enumerate(SCREAMING_SNAKE_CASE ): if i == 0: continue lowerCAmelCase = '%s-%s' % (set_type, line[0]) lowerCAmelCase = line[5] lowerCAmelCase = line[6] lowerCAmelCase = line[7][2:] if line[7].startswith("ex" ) else line[7] lowerCAmelCase = line[0] examples.append(InputExample(guid=SCREAMING_SNAKE_CASE , text_a=SCREAMING_SNAKE_CASE , text_b=SCREAMING_SNAKE_CASE , label=SCREAMING_SNAKE_CASE , pairID=SCREAMING_SNAKE_CASE ) ) return examples def __a ( A__ , A__ , A__ , A__ , ) -> Optional[int]: lowerCAmelCase = {label: i for i, label in enumerate(SCREAMING_SNAKE_CASE_ )} lowerCAmelCase = [] for ex_index, example in tqdm.tqdm(enumerate(SCREAMING_SNAKE_CASE_ ) , desc="convert examples to features" ): if ex_index % 1_0000 == 0: logger.info("Writing example %d" % (ex_index) ) lowerCAmelCase = tokenizer( example.text_a , example.text_b , add_special_tokens=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , padding="max_length" , truncation=SCREAMING_SNAKE_CASE_ , return_overflowing_tokens=SCREAMING_SNAKE_CASE_ , ) lowerCAmelCase = label_map[example.label] if example.label in label_map else 0 lowerCAmelCase = int(example.pairID ) features.append(InputFeatures(**SCREAMING_SNAKE_CASE_ , label=SCREAMING_SNAKE_CASE_ , pairID=SCREAMING_SNAKE_CASE_ ) ) for i, example in enumerate(examples[:5] ): logger.info("*** Example ***" ) logger.info(f"guid: {example}" ) logger.info(f"features: {features[i]}" ) return features lowercase : Optional[int] = { 'hans': 3, } lowercase : Optional[Any] = { 'hans': HansProcessor, }
703
'''simple docstring''' import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch lowercase : Optional[int] = random.Random() def __a ( A__ , A__=1.0 , A__=None , A__=None ) -> Any: if rng is None: lowerCAmelCase = global_rng lowerCAmelCase = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : int=7 , SCREAMING_SNAKE_CASE : Optional[Any]=4_0_0 , SCREAMING_SNAKE_CASE : Optional[Any]=2_0_0_0 , SCREAMING_SNAKE_CASE : Union[str, Any]=1 , SCREAMING_SNAKE_CASE : int=0.0 , SCREAMING_SNAKE_CASE : Optional[int]=1_6_0_0_0 , SCREAMING_SNAKE_CASE : Any=True , SCREAMING_SNAKE_CASE : Optional[Any]=8_0 , SCREAMING_SNAKE_CASE : int=1_6 , SCREAMING_SNAKE_CASE : Any=6_4 , SCREAMING_SNAKE_CASE : List[Any]="hann_window" , SCREAMING_SNAKE_CASE : Dict=8_0 , SCREAMING_SNAKE_CASE : Any=7_6_0_0 , SCREAMING_SNAKE_CASE : Optional[Any]=1E-10 , SCREAMING_SNAKE_CASE : Union[str, Any]=True , ) -> Any: """simple docstring""" lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = min_seq_length lowerCAmelCase = max_seq_length lowerCAmelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) lowerCAmelCase = feature_size lowerCAmelCase = padding_value lowerCAmelCase = sampling_rate lowerCAmelCase = do_normalize lowerCAmelCase = num_mel_bins lowerCAmelCase = hop_length lowerCAmelCase = win_length lowerCAmelCase = win_function lowerCAmelCase = fmin lowerCAmelCase = fmax lowerCAmelCase = mel_floor lowerCAmelCase = return_attention_mask def __A ( self : Union[str, Any] ) -> List[str]: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __A ( self : List[str] , SCREAMING_SNAKE_CASE : int=False , SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> str: """simple docstring""" def _flatten(SCREAMING_SNAKE_CASE : List[Any] ): return list(itertools.chain(*SCREAMING_SNAKE_CASE ) ) if equal_length: lowerCAmelCase = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size lowerCAmelCase = [ _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: lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs def __A ( self : List[str] , SCREAMING_SNAKE_CASE : Tuple=False , SCREAMING_SNAKE_CASE : Optional[int]=False ) -> str: """simple docstring""" if equal_length: lowerCAmelCase = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size lowerCAmelCase = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch class _lowerCAmelCase ( UpperCamelCase_ , unittest.TestCase ): """simple docstring""" lowerCAmelCase = SpeechTaFeatureExtractor def __A ( self : Optional[int] ) -> Dict: """simple docstring""" lowerCAmelCase = SpeechTaFeatureExtractionTester(self ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(SCREAMING_SNAKE_CASE , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(SCREAMING_SNAKE_CASE , axis=0 ) - 1 ) < 1E-3 ) ) def __A ( self : int ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test not batched input lowerCAmelCase = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values lowerCAmelCase = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def __A ( self : Any ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = ["longest", "max_length", "do_not_pad"] lowerCAmelCase = [None, 1_6_0_0, None] for max_length, padding in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , return_tensors="np" ) lowerCAmelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self.assertTrue(input_values[0][8_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self.assertTrue(input_values[0][1_0_0_0:].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def __A ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase = range(8_0_0 , 1_4_0_0 , 2_0_0 ) lowerCAmelCase = [floats_list((1, x) )[0] for x in lengths] lowerCAmelCase = ["longest", "max_length", "do_not_pad"] lowerCAmelCase = [None, 1_6_0_0, None] for max_length, padding in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): lowerCAmelCase = feat_extract(SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE ) lowerCAmelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def __A ( self : str ) -> Any: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = feat_extract( SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=1_0_0_0 , padding="max_length" , return_tensors="np" ) lowerCAmelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __A ( self : int ) -> Optional[int]: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = feat_extract( SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=1_0_0_0 , padding="longest" , return_tensors="np" ) lowerCAmelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_0_0_0) ) lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = feat_extract( SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=2_0_0_0 , padding="longest" , return_tensors="np" ) lowerCAmelCase = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_2_0_0) ) def __A ( self : Optional[int] ) -> Any: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase = np.random.rand(1_0_0 ).astype(np.floataa ) lowerCAmelCase = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: lowerCAmelCase = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) lowerCAmelCase = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __A ( self : int ) -> Optional[int]: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 lowerCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size lowerCAmelCase = feature_extractor(audio_target=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input lowerCAmelCase = feature_extractor(speech_inputs[0] , return_tensors="np" ).input_values lowerCAmelCase = feature_extractor(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. lowerCAmelCase = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] lowerCAmelCase = np.asarray(SCREAMING_SNAKE_CASE ) lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def __A ( self : Dict ) -> Optional[Any]: """simple docstring""" lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target() lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_dict ) lowerCAmelCase = feat_extract.model_input_names[0] lowerCAmelCase = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(SCREAMING_SNAKE_CASE ) == len(SCREAMING_SNAKE_CASE ) for x, y in zip(SCREAMING_SNAKE_CASE , processed_features[input_name] ) ) ) lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target(equal_length=SCREAMING_SNAKE_CASE ) lowerCAmelCase = BatchFeature({input_name: speech_inputs} , tensor_type="np" ) lowerCAmelCase = processed_features[input_name] if len(batch_features_input.shape ) < 3: lowerCAmelCase = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __A ( self : List[str] ) -> Optional[int]: """simple docstring""" lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target(equal_length=SCREAMING_SNAKE_CASE ) lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_dict ) lowerCAmelCase = feat_extract.model_input_names[0] lowerCAmelCase = BatchFeature({input_name: speech_inputs} , tensor_type="pt" ) lowerCAmelCase = processed_features[input_name] if len(batch_features_input.shape ) < 3: lowerCAmelCase = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __A ( self : Optional[int] ) -> Dict: """simple docstring""" lowerCAmelCase = self.feature_extraction_class(**self.feat_extract_dict ) lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target() lowerCAmelCase = feat_extract.model_input_names[0] lowerCAmelCase = BatchFeature({input_name: speech_inputs} ) lowerCAmelCase = feat_extract.num_mel_bins # hack! lowerCAmelCase = feat_extract.pad(SCREAMING_SNAKE_CASE , padding="longest" , return_tensors="np" )[input_name] lowerCAmelCase = feat_extract.pad(SCREAMING_SNAKE_CASE , padding="longest" , return_tensors="pt" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def __A ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase = self.feat_extract_dict lowerCAmelCase = True lowerCAmelCase = self.feature_extraction_class(**SCREAMING_SNAKE_CASE ) lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target() lowerCAmelCase = [len(SCREAMING_SNAKE_CASE ) for x in speech_inputs] lowerCAmelCase = feat_extract.model_input_names[0] lowerCAmelCase = BatchFeature({input_name: speech_inputs} ) lowerCAmelCase = feat_extract.num_mel_bins # hack! lowerCAmelCase = feat_extract.pad(SCREAMING_SNAKE_CASE , padding="longest" , return_tensors="np" ) self.assertIn("attention_mask" , SCREAMING_SNAKE_CASE ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , SCREAMING_SNAKE_CASE ) def __A ( self : Tuple ) -> List[Any]: """simple docstring""" lowerCAmelCase = self.feat_extract_dict lowerCAmelCase = True lowerCAmelCase = self.feature_extraction_class(**SCREAMING_SNAKE_CASE ) lowerCAmelCase = self.feat_extract_tester.prepare_inputs_for_target() lowerCAmelCase = [len(SCREAMING_SNAKE_CASE ) for x in speech_inputs] lowerCAmelCase = feat_extract.model_input_names[0] lowerCAmelCase = BatchFeature({input_name: speech_inputs} ) lowerCAmelCase = min(SCREAMING_SNAKE_CASE ) lowerCAmelCase = feat_extract.num_mel_bins # hack! lowerCAmelCase = feat_extract.pad( SCREAMING_SNAKE_CASE , padding="max_length" , max_length=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , return_tensors="np" ) self.assertIn("attention_mask" , SCREAMING_SNAKE_CASE ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" from datasets import load_dataset lowerCAmelCase = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech lowerCAmelCase = ds.sort("id" ).select(range(SCREAMING_SNAKE_CASE ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] def __A ( self : List[Any] ) -> int: """simple docstring""" lowerCAmelCase = torch.tensor( [2.38_04E-03, 2.07_52E-03, 1.98_36E-03, 2.10_57E-03, 1.61_74E-03, 3.05_18E-04, 9.15_53E-05, 3.35_69E-04, 9.76_56E-04, 1.83_11E-03, 2.01_42E-03, 2.10_57E-03, 1.73_95E-03, 4.57_76E-04, -3.96_73E-04, 4.57_76E-04, 1.00_71E-03, 9.15_53E-05, 4.88_28E-04, 1.15_97E-03, 7.32_42E-04, 9.46_04E-04, 1.80_05E-03, 1.83_11E-03, 8.85_01E-04, 4.27_25E-04, 4.88_28E-04, 7.32_42E-04, 1.09_86E-03, 2.10_57E-03] ) # fmt: on lowerCAmelCase = self._load_datasamples(1 ) lowerCAmelCase = SpeechTaFeatureExtractor() lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 9_3_6_8_0) ) self.assertTrue(torch.allclose(input_values[0, :3_0] , SCREAMING_SNAKE_CASE , atol=1E-6 ) ) def __A ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" lowerCAmelCase = torch.tensor( [-2.6_8_7_0, -3.0_1_0_4, -3.1_3_5_6, -3.5_3_5_2, -3.0_0_4_4, -3.0_3_5_3, -3.4_7_1_9, -3.6_7_7_7, -3.1_5_2_0, -2.9_4_3_5, -2.6_5_5_3, -2.8_7_9_5, -2.9_9_4_4, -2.5_9_2_1, -3.0_2_7_9, -3.0_3_8_6, -3.0_8_6_4, -3.1_2_9_1, -3.2_3_5_3, -2.7_4_4_4, -2.6_8_3_1, -2.7_2_8_7, -3.1_7_6_1, -3.1_5_7_1, -3.2_7_2_6, -3.0_5_8_2, -3.1_0_0_7, -3.4_5_3_3, -3.4_6_9_5, -3.0_9_9_8] ) # fmt: on lowerCAmelCase = self._load_datasamples(1 ) lowerCAmelCase = SpeechTaFeatureExtractor() lowerCAmelCase = feature_extractor(audio_target=SCREAMING_SNAKE_CASE , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 3_6_6, 8_0) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , SCREAMING_SNAKE_CASE , atol=1E-4 ) )
159
0
'''simple docstring''' import math class UpperCamelCase__ : """simple docstring""" def __init__( self : Tuple , __A : int=0 ): # a graph with Node 0,1,...,N-1 """simple docstring""" _lowercase = n _lowercase = [ [math.inf for j in range(0 , __UpperCamelCase )] for i in range(0 , __UpperCamelCase ) ] # adjacency matrix for weight _lowercase = [ [math.inf for j in range(0 , __UpperCamelCase )] for i in range(0 , __UpperCamelCase ) ] # dp[i][j] stores minimum distance from i to j def snake_case ( self : Optional[Any] , __A : Union[str, Any] , __A : Any , __A : Optional[int] ): """simple docstring""" _lowercase = w def snake_case ( self : Any ): """simple docstring""" for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): _lowercase = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def snake_case ( self : str , __A : Union[str, Any] , __A : Union[str, Any] ): """simple docstring""" return self.dp[u][v] if __name__ == "__main__": __magic_name__ : Union[str, Any] = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
497
import functools def a(lowercase__ , lowercase__ ): '''simple docstring''' # Validation if not isinstance(lowercase__ , lowercase__ ) or not all(isinstance(lowercase__ , lowercase__ ) for day in days ): raise ValueError('The parameter days should be a list of integers' ) if len(lowercase__ ) != 3 or not all(isinstance(lowercase__ , lowercase__ ) for cost in costs ): raise ValueError('The parameter costs should be a list of three integers' ) if len(lowercase__ ) == 0: return 0 if min(lowercase__ ) <= 0: raise ValueError('All days elements should be greater than 0' ) if max(lowercase__ ) >= 366: raise ValueError('All days elements should be less than 366' ) snake_case_ = set(lowercase__ ) @functools.cache def dynamic_programming(lowercase__ ) -> int: if index > 365: return 0 if index not in days_set: return dynamic_programming(index + 1 ) return min( costs[0] + dynamic_programming(index + 1 ) , costs[1] + dynamic_programming(index + 7 ) , costs[2] + dynamic_programming(index + 30 ) , ) return dynamic_programming(1 ) if __name__ == "__main__": import doctest doctest.testmod()
187
0
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : bool = False ) -> list[float]: if radian_mode: return [magnitude * cos(SCREAMING_SNAKE_CASE ), magnitude * sin(SCREAMING_SNAKE_CASE )] return [magnitude * cos(radians(SCREAMING_SNAKE_CASE ) ), magnitude * sin(radians(SCREAMING_SNAKE_CASE ) )] def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : NDArray[floataa] , SCREAMING_SNAKE_CASE : NDArray[floataa] , SCREAMING_SNAKE_CASE : float = 10**-1 ) -> bool: __lowercase = cross(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) __lowercase = sum(SCREAMING_SNAKE_CASE ) return abs(SCREAMING_SNAKE_CASE ) < eps if __name__ == "__main__": # Test to check if it works SCREAMING_SNAKE_CASE__ = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) SCREAMING_SNAKE_CASE__ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg SCREAMING_SNAKE_CASE__ = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) SCREAMING_SNAKE_CASE__ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg SCREAMING_SNAKE_CASE__ = array([[0, -2000], [0, -1200], [0, 1_5600], [0, -1_2400]]) SCREAMING_SNAKE_CASE__ = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
702
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) class A__ ( lowerCAmelCase__ ): lowerCAmelCase__ : List[str] = ["pixel_values"] def __init__( self : Tuple , _UpperCAmelCase : bool = True , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , _UpperCAmelCase : bool = True , _UpperCAmelCase : Union[int, float] = 1 / 2_55 , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : bool = True , **_UpperCAmelCase : str , ) -> None: """simple docstring""" super().__init__(**_UpperCAmelCase ) __lowercase = size if size is not None else {'height': 3_84, 'width': 3_84} __lowercase = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase ) __lowercase = do_resize __lowercase = size __lowercase = resample __lowercase = do_rescale __lowercase = rescale_factor __lowercase = do_normalize __lowercase = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __lowercase = image_std if image_std is not None else OPENAI_CLIP_STD __lowercase = do_convert_rgb def a__ ( self : int , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Dict[str, int] , _UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : int , ) -> np.ndarray: """simple docstring""" __lowercase = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""" ) __lowercase = (size['height'], size['width']) return resize(_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def a__ ( self : Optional[int] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[int, float] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Any , ) -> str: """simple docstring""" return rescale(_UpperCAmelCase , scale=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def a__ ( self : str , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : List[str] , ) -> np.ndarray: """simple docstring""" return normalize(_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def a__ ( self : int , _UpperCAmelCase : ImageInput , _UpperCAmelCase : Optional[bool] = None , _UpperCAmelCase : Optional[Dict[str, int]] = None , _UpperCAmelCase : PILImageResampling = None , _UpperCAmelCase : Optional[bool] = None , _UpperCAmelCase : Optional[float] = None , _UpperCAmelCase : Optional[bool] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[str, TensorType]] = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : ChannelDimension = ChannelDimension.FIRST , **_UpperCAmelCase : int , ) -> PIL.Image.Image: """simple docstring""" __lowercase = do_resize if do_resize is not None else self.do_resize __lowercase = resample if resample is not None else self.resample __lowercase = do_rescale if do_rescale is not None else self.do_rescale __lowercase = rescale_factor if rescale_factor is not None else self.rescale_factor __lowercase = do_normalize if do_normalize is not None else self.do_normalize __lowercase = image_mean if image_mean is not None else self.image_mean __lowercase = image_std if image_std is not None else self.image_std __lowercase = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __lowercase = size if size is not None else self.size __lowercase = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase ) __lowercase = make_list_of_images(_UpperCAmelCase ) if not valid_images(_UpperCAmelCase ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __lowercase = [convert_to_rgb(_UpperCAmelCase ) for image in images] # All transformations expect numpy arrays. __lowercase = [to_numpy_array(_UpperCAmelCase ) for image in images] if do_resize: __lowercase = [self.resize(image=_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase ) for image in images] if do_rescale: __lowercase = [self.rescale(image=_UpperCAmelCase , scale=_UpperCAmelCase ) for image in images] if do_normalize: __lowercase = [self.normalize(image=_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase ) for image in images] __lowercase = [to_channel_dimension_format(_UpperCAmelCase , _UpperCAmelCase ) for image in images] __lowercase = BatchFeature(data={'pixel_values': images} , tensor_type=_UpperCAmelCase ) return encoded_outputs
688
0
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a : Union[str, Any] = [ """cross_validation.py""", """gradient_accumulation.py""", """local_sgd.py""", """multi_process_metrics.py""", """memory.py""", """automatic_gradient_accumulation.py""", """fsdp_with_peak_mem_tracking.py""", """deepspeed_with_config_support.py""", """megatron_lm_gpt_pretraining.py""", ] class __UpperCAmelCase( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ = None , snake_case__ = None ): '''simple docstring''' lowercase__ : List[str]= None lowercase__ : Optional[Any]= os.path.abspath(os.path.join("examples" , "by_feature" ) ) lowercase__ : Union[str, Any]= os.path.abspath("examples" ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: lowercase__ : List[Any]= os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section="main()" if parser_only else "training_function()" , ): lowercase__ : Tuple= compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) lowercase__ : Optional[Any]= '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: lowercase__ : List[Any]= diff.replace(_lowerCamelCase , "" ) self.assertEqual(_lowerCamelCase , "" ) def UpperCAmelCase_ ( self ): '''simple docstring''' self.one_complete_example("complete_nlp_example.py" , _lowerCamelCase ) self.one_complete_example("complete_nlp_example.py" , _lowerCamelCase ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= os.path.abspath(os.path.join("examples" , "cv_example.py" ) ) lowercase__ : Optional[int]= [ ''' ''' * 16 + '''{\n\n''', ''' ''' * 20 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 20 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 20 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 20 + '''"epoch": epoch,\n\n''', ''' ''' * 16 + '''},\n\n''', ''' ''' * 16 + '''step=epoch,\n''', ''' ''' * 12, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example("complete_cv_example.py" , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example("complete_cv_example.py" , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "1"} ) class __UpperCAmelCase( __UpperCAmelCase ): """simple docstring""" __lowerCamelCase = False @classmethod def UpperCAmelCase_ ( cls ): '''simple docstring''' super().setUpClass() lowercase__ : Dict= tempfile.mkdtemp() lowercase__ : str= os.path.join(cls._tmpdir , "default_config.yml" ) write_basic_config(save_location=cls.configPath ) lowercase__ : List[Any]= ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def UpperCAmelCase_ ( cls ): '''simple docstring''' super().tearDownClass() shutil.rmtree(cls._tmpdir ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : str= F''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , "epoch_0" ) ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= F''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() lowercase__ : Optional[int]= run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , "step_2" ) ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= F''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() lowercase__ : Any= run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn("epoch 0:" , _lowerCamelCase ) self.assertIn("epoch 1:" , _lowerCamelCase ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= F''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() lowercase__ : List[str]= run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): lowercase__ : List[Any]= torch.cuda.device_count() else: lowercase__ : Optional[int]= 1 if num_processes > 1: self.assertNotIn("epoch 0:" , _lowerCamelCase ) self.assertIn("epoch 1:" , _lowerCamelCase ) else: self.assertIn("epoch 0:" , _lowerCamelCase ) self.assertIn("epoch 1:" , _lowerCamelCase ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "0"} ): lowercase__ : Union[str, Any]= run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) lowercase__ : Any= re.findall("({.+})" , _lowerCamelCase ) lowercase__ : List[Any]= [r for r in results if '''accuracy''' in r][-1] lowercase__ : Tuple= ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results["accuracy"] , 0.75 ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def UpperCAmelCase_ ( self ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: lowercase__ : int= F''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , "tracking" ) ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
218
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
0
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _UpperCamelCase( __lowerCamelCase , unittest.TestCase ): __SCREAMING_SNAKE_CASE : Tuple = TransfoXLTokenizer __SCREAMING_SNAKE_CASE : Dict = False __SCREAMING_SNAKE_CASE : Tuple = False def __lowerCAmelCase ( self : int ): '''simple docstring''' super().setUp() __a : Optional[Any] = [ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __a : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : List[str] , **SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' __a : str = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' __a : Dict = '<unk> UNwanted , running' __a : int = '<unk> unwanted, running' return input_text, output_text def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' __a : int = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [0, 4, 8, 7] ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : Tuple = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' __a : int = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def __lowerCAmelCase ( self : int ): '''simple docstring''' __a : str = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE__ ) __a : List[str] = 'Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __a : List[str] = [ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): '''simple docstring''' __a : List[str] = self.get_tokenizer() __a : Optional[int] = len(SCREAMING_SNAKE_CASE__ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
577
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : Tuple = ['''image_processor''', '''tokenizer'''] __SCREAMING_SNAKE_CASE : str = '''OwlViTImageProcessor''' __SCREAMING_SNAKE_CASE : int = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None , **SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' __a : Optional[Any] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , SCREAMING_SNAKE_CASE__ , ) __a : List[Any] = kwargs.pop('feature_extractor' ) __a : 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__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]="max_length" , SCREAMING_SNAKE_CASE__ : Optional[int]="np" , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''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(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and not isinstance(text[0] , SCREAMING_SNAKE_CASE__ )): __a : Any = [self.tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )] elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(text[0] , SCREAMING_SNAKE_CASE__ ): __a : Union[str, Any] = [] # Maximum number of queries across batch __a : List[str] = max([len(SCREAMING_SNAKE_CASE__ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(SCREAMING_SNAKE_CASE__ ) != max_num_queries: __a : Optional[int] = t + [' '] * (max_num_queries - len(SCREAMING_SNAKE_CASE__ )) __a : Optional[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) encodings.append(SCREAMING_SNAKE_CASE__ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": __a : Optional[Any] = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) __a : str = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp __a : Optional[Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) __a : Tuple = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch __a : Dict = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) __a : Union[str, Any] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf __a : Tuple = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) __a : Tuple = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) __a : Optional[Any] = BatchEncoding() __a : Optional[Any] = input_ids __a : List[Any] = attention_mask if query_images is not None: __a : str = BatchEncoding() __a : Union[str, Any] = self.image_processor( SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).pixel_values __a : Tuple = query_pixel_values if images is not None: __a : int = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None and images is not None: __a : Union[str, Any] = image_features.pixel_values return encoding elif query_images is not None and images is not None: __a : Dict = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**SCREAMING_SNAKE_CASE__ ) , tensor_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' return self.image_processor.post_process(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' return self.image_processor.post_process_object_detection(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' return self.image_processor.post_process_image_guided_detection(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def __lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , SCREAMING_SNAKE_CASE__ , ) return self.image_processor_class @property def __lowerCAmelCase ( self : int ): '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , SCREAMING_SNAKE_CASE__ , ) return self.image_processor
577
1
'''simple docstring''' import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py A__: List[Any] = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. A__: Optional[Any] = direct_transformers_import(PATH_TO_TRANSFORMERS) A__: int = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` A__: List[Any] = re.compile(R'''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') A__: str = { 'DecisionTransformerConfig', 'EncoderDecoderConfig', 'MusicgenConfig', 'RagConfig', 'SpeechEncoderDecoderConfig', 'TimmBackboneConfig', 'VisionEncoderDecoderConfig', 'VisionTextDualEncoderConfig', 'LlamaConfig', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ) -> List[str]: _a : Any =None # source code of `config_class` _a : Optional[int] =inspect.getsource(_UpperCAmelCase ) _a : Any =_re_checkpoint.findall(_UpperCAmelCase ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith("""/""" ): _a : int =ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link _a : Tuple =F"https://huggingface.co/{ckpt_name}" if ckpt_link == ckpt_link_from_name: _a : List[str] =ckpt_name break return checkpoint def SCREAMING_SNAKE_CASE_ ( ) -> str: _a : List[str] =[] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue _a : int =get_checkpoint_from_config_class(_UpperCAmelCase ) _a : Optional[int] =config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(_UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: _a : str ='''\n'''.join(sorted(_UpperCAmelCase ) ) raise ValueError(F"The following configurations don\'t contain any valid checkpoint:\n{message}" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
694
from math import loga def UpperCAmelCase__ ( __magic_name__ : int ): '''simple docstring''' if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(__magic_name__ , __magic_name__ ): raise TypeError('''Input value must be a \'int\' type''' ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
348
0
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home __UpperCAmelCase = HUGGINGFACE_HUB_CACHE __UpperCAmelCase = 'config.json' __UpperCAmelCase = 'diffusion_pytorch_model.bin' __UpperCAmelCase = 'diffusion_flax_model.msgpack' __UpperCAmelCase = 'model.onnx' __UpperCAmelCase = 'diffusion_pytorch_model.safetensors' __UpperCAmelCase = 'weights.pb' __UpperCAmelCase = 'https://huggingface.co' __UpperCAmelCase = default_cache_path __UpperCAmelCase = 'diffusers_modules' __UpperCAmelCase = os.getenv('HF_MODULES_CACHE', os.path.join(hf_cache_home, 'modules')) __UpperCAmelCase = ['fp16', 'non-ema'] __UpperCAmelCase = '.self_attn'
194
"""simple docstring""" # This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class __lowercase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): snake_case_ = StableDiffusionControlNetImgaImgPipeline snake_case_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} snake_case_ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS snake_case_ = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({"""control_image"""} ) snake_case_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase ( self : str ): '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase__ : Union[str, Any] = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") ,cross_attention_dim=32 ,) torch.manual_seed(0 ) UpperCAmelCase__ : Optional[int] = ControlNetModel( block_out_channels=(32, 64) ,layers_per_block=2 ,in_channels=4 ,down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,cross_attention_dim=32 ,conditioning_embedding_out_channels=(16, 32) ,) torch.manual_seed(0 ) UpperCAmelCase__ : Tuple = DDIMScheduler( beta_start=0.0_0_0_8_5 ,beta_end=0.0_1_2 ,beta_schedule="""scaled_linear""" ,clip_sample=A ,set_alpha_to_one=A ,) torch.manual_seed(0 ) UpperCAmelCase__ : Any = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] ,up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] ,latent_channels=4 ,) torch.manual_seed(0 ) UpperCAmelCase__ : int = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_000 ,) UpperCAmelCase__ : List[str] = CLIPTextModel(A ) UpperCAmelCase__ : Dict = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) UpperCAmelCase__ : Optional[int] = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def __lowercase ( self : Union[str, Any] ,A : Dict ,A : Optional[Any]=0 ): '''simple docstring''' if str(A ).startswith("""mps""" ): UpperCAmelCase__ : List[str] = torch.manual_seed(A ) else: UpperCAmelCase__ : List[Any] = torch.Generator(device=A ).manual_seed(A ) UpperCAmelCase__ : Tuple = 2 UpperCAmelCase__ : Any = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) ,generator=A ,device=torch.device(A ) ,) UpperCAmelCase__ : str = floats_tensor(control_image.shape ,rng=random.Random(A ) ).to(A ) UpperCAmelCase__ : Dict = image.cpu().permute(0 ,2 ,3 ,1 )[0] UpperCAmelCase__ : List[str] = Image.fromarray(np.uinta(A ) ).convert("""RGB""" ).resize((64, 64) ) UpperCAmelCase__ : Any = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def __lowercase ( self : Optional[Any] ): '''simple docstring''' return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() ,reason="""XFormers attention is only available with CUDA and `xformers` installed""" ,) def __lowercase ( self : Dict ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def __lowercase ( self : Any ): '''simple docstring''' self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) class __lowercase ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): snake_case_ = StableDiffusionControlNetImgaImgPipeline snake_case_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""} snake_case_ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS snake_case_ = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def __lowercase ( self : str ): '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase__ : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") ,cross_attention_dim=32 ,) torch.manual_seed(0 ) def init_weights(A : Union[str, Any] ): if isinstance(A ,torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) UpperCAmelCase__ : int = ControlNetModel( block_out_channels=(32, 64) ,layers_per_block=2 ,in_channels=4 ,down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,cross_attention_dim=32 ,conditioning_embedding_out_channels=(16, 32) ,) controlneta.controlnet_down_blocks.apply(A ) torch.manual_seed(0 ) UpperCAmelCase__ : Dict = ControlNetModel( block_out_channels=(32, 64) ,layers_per_block=2 ,in_channels=4 ,down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,cross_attention_dim=32 ,conditioning_embedding_out_channels=(16, 32) ,) controlneta.controlnet_down_blocks.apply(A ) torch.manual_seed(0 ) UpperCAmelCase__ : str = DDIMScheduler( beta_start=0.0_0_0_8_5 ,beta_end=0.0_1_2 ,beta_schedule="""scaled_linear""" ,clip_sample=A ,set_alpha_to_one=A ,) torch.manual_seed(0 ) UpperCAmelCase__ : 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 ) UpperCAmelCase__ : Tuple = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_000 ,) UpperCAmelCase__ : Optional[Any] = CLIPTextModel(A ) UpperCAmelCase__ : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) UpperCAmelCase__ : Dict = MultiControlNetModel([controlneta, controlneta] ) UpperCAmelCase__ : Union[str, Any] = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def __lowercase ( self : Optional[int] ,A : List[Any] ,A : List[Any]=0 ): '''simple docstring''' if str(A ).startswith("""mps""" ): UpperCAmelCase__ : List[str] = torch.manual_seed(A ) else: UpperCAmelCase__ : int = torch.Generator(device=A ).manual_seed(A ) UpperCAmelCase__ : Optional[int] = 2 UpperCAmelCase__ : List[Any] = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) ,generator=A ,device=torch.device(A ) ,), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) ,generator=A ,device=torch.device(A ) ,), ] UpperCAmelCase__ : List[Any] = floats_tensor(control_image[0].shape ,rng=random.Random(A ) ).to(A ) UpperCAmelCase__ : str = image.cpu().permute(0 ,2 ,3 ,1 )[0] UpperCAmelCase__ : Union[str, Any] = Image.fromarray(np.uinta(A ) ).convert("""RGB""" ).resize((64, 64) ) UpperCAmelCase__ : Any = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def __lowercase ( self : Dict ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = self.get_dummy_components() UpperCAmelCase__ : List[str] = self.pipeline_class(**A ) pipe.to(A ) UpperCAmelCase__ : Any = 1_0.0 UpperCAmelCase__ : Any = 4 UpperCAmelCase__ : Optional[int] = self.get_dummy_inputs(A ) UpperCAmelCase__ : Optional[Any] = steps UpperCAmelCase__ : List[str] = scale UpperCAmelCase__ : Optional[Any] = pipe(**A )[0] UpperCAmelCase__ : Any = self.get_dummy_inputs(A ) UpperCAmelCase__ : Optional[int] = steps UpperCAmelCase__ : Tuple = scale UpperCAmelCase__ : List[Any] = pipe(**A ,control_guidance_start=0.1 ,control_guidance_end=0.2 )[0] UpperCAmelCase__ : List[str] = self.get_dummy_inputs(A ) UpperCAmelCase__ : Union[str, Any] = steps UpperCAmelCase__ : Any = scale UpperCAmelCase__ : str = pipe(**A ,control_guidance_start=[0.1, 0.3] ,control_guidance_end=[0.2, 0.7] )[0] UpperCAmelCase__ : Any = self.get_dummy_inputs(A ) UpperCAmelCase__ : List[str] = steps UpperCAmelCase__ : Union[str, Any] = scale UpperCAmelCase__ : Union[str, Any] = pipe(**A ,control_guidance_start=0.4 ,control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 def __lowercase ( self : Any ): '''simple docstring''' return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @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] ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) def __lowercase ( self : Dict ): '''simple docstring''' UpperCAmelCase__ : Dict = self.get_dummy_components() UpperCAmelCase__ : str = self.pipeline_class(**A ) pipe.to(A ) pipe.set_progress_bar_config(disable=A ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(A ) except NotImplementedError: pass @slow @require_torch_gpu class __lowercase ( unittest.TestCase ): def __lowercase ( self : List[str] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : str = ControlNetModel.from_pretrained("""lllyasviel/sd-controlnet-canny""" ) UpperCAmelCase__ : Tuple = StableDiffusionControlNetImgaImgPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" ,safety_checker=A ,controlnet=A ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=A ) UpperCAmelCase__ : Optional[int] = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCAmelCase__ : Dict = """evil space-punk bird""" UpperCAmelCase__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ).resize((512, 512) ) UpperCAmelCase__ : Optional[Any] = load_image( """https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png""" ).resize((512, 512) ) UpperCAmelCase__ : List[str] = pipe( A ,A ,control_image=A ,generator=A ,output_type="""np""" ,num_inference_steps=50 ,strength=0.6 ,) UpperCAmelCase__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) UpperCAmelCase__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy""" ) assert np.abs(expected_image - image ).max() < 9e-2
194
1
from __future__ import annotations from scipy.special import comb # type: ignore class a : '''simple docstring''' def __init__( self : Optional[int] , __snake_case : list[tuple[float, float]] ): UpperCAmelCase_ = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. UpperCAmelCase_ = len(__snake_case ) - 1 def lowerCamelCase_ ( self : str , __snake_case : float ): assert 0 <= t <= 1, "Time t must be between 0 and 1." UpperCAmelCase_ = [] for i in range(len(self.list_of_points ) ): # basis function for each i output_values.append( comb(self.degree , __snake_case ) * ((1 - t) ** (self.degree - i)) * (t**i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(__snake_case ) , 5 ) == 1 return output_values def lowerCamelCase_ ( self : Union[str, Any] , __snake_case : float ): assert 0 <= t <= 1, "Time t must be between 0 and 1." UpperCAmelCase_ = self.basis_function(__snake_case ) UpperCAmelCase_ = 0.0 UpperCAmelCase_ = 0.0 for i in range(len(self.list_of_points ) ): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCamelCase_ ( self : Optional[int] , __snake_case : float = 0.01 ): from matplotlib import pyplot as plt # type: ignore UpperCAmelCase_ = [] # x coordinates of points to plot UpperCAmelCase_ = [] # y coordinates of points to plot UpperCAmelCase_ = 0.0 while t <= 1: UpperCAmelCase_ = self.bezier_curve_function(__snake_case ) to_plot_x.append(value[0] ) to_plot_y.append(value[1] ) t += step_size UpperCAmelCase_ = [i[0] for i in self.list_of_points] UpperCAmelCase_ = [i[1] for i in self.list_of_points] plt.plot( __snake_case , __snake_case , color='''blue''' , label='''Curve of Degree ''' + str(self.degree ) , ) plt.scatter(__snake_case , __snake_case , color='''red''' , label='''Control Points''' ) plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
144
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : List[str] , __UpperCamelCase : List[Any] , __UpperCamelCase : Optional[int] , __UpperCamelCase : Optional[Any] ) -> Optional[Any]: if height >= 1: move_tower(height - 1 , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) move_disk(__UpperCamelCase , __UpperCamelCase ) move_tower(height - 1 , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) def SCREAMING_SNAKE_CASE ( __UpperCamelCase : List[str] , __UpperCamelCase : Union[str, Any] ) -> List[str]: print('''moving disk from''' , __UpperCamelCase , '''to''' , __UpperCamelCase ) def SCREAMING_SNAKE_CASE ( ) -> List[Any]: UpperCAmelCase_ = int(input('''Height of hanoi: ''' ).strip() ) move_tower(__UpperCamelCase , '''A''' , '''B''' , '''C''' ) if __name__ == "__main__": main()
144
1
import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class lowerCAmelCase__( snake_case__ , unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = RoFormerTokenizer A_ : int = RoFormerTokenizerFast A_ : Dict = True A_ : Optional[Any] = True def _lowerCamelCase ( self : Union[str, Any] ): '''simple docstring''' super().setUp() def _lowerCamelCase ( self : int , **__snake_case : Any ): '''simple docstring''' return self.tokenizer_class.from_pretrained('''junnyu/roformer_chinese_base''' , **__snake_case ) def _lowerCamelCase ( self : List[str] , **__snake_case : str ): '''simple docstring''' return self.rust_tokenizer_class.from_pretrained('''junnyu/roformer_chinese_base''' , **__snake_case ) def _lowerCamelCase ( self : Any ): '''simple docstring''' UpperCAmelCase_ : List[str] = '''永和服装饰品有限公司,今天天气非常好''' UpperCAmelCase_ : List[str] = '''永和 服装 饰品 有限公司 , 今 天 天 气 非常 好''' return input_text, output_text def _lowerCamelCase ( self : List[Any] ): '''simple docstring''' UpperCAmelCase_ : List[str] = self.get_tokenizer() UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = self.get_chinese_input_output_texts() UpperCAmelCase_ : int = tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , output_text.split() ) UpperCAmelCase_ : Any = tokens + [tokenizer.unk_token] UpperCAmelCase_ : Union[str, Any] = [22_943, 21_332, 34_431, 45_904, 117, 306, 1_231, 1_231, 2_653, 33_994, 1_266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , __snake_case ) def _lowerCamelCase ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase_ : List[str] = self.get_rust_tokenizer() UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = self.get_chinese_input_output_texts() UpperCAmelCase_ : List[str] = tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , output_text.split() ) UpperCAmelCase_ : str = tokens + [tokenizer.unk_token] UpperCAmelCase_ : List[str] = [22_943, 21_332, 34_431, 45_904, 117, 306, 1_231, 1_231, 2_653, 33_994, 1_266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , __snake_case ) def _lowerCamelCase ( self : List[str] ): '''simple docstring''' pass def _lowerCamelCase ( self : Optional[Any] ): '''simple docstring''' pass def _lowerCamelCase ( self : Dict ): '''simple docstring''' pass
641
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def snake_case_ ( __lowercase , __lowercase ): # Load checkpoint UpperCAmelCase_ : Tuple = torch.load(__lowercase , map_location='''cpu''' ) UpperCAmelCase_ : Optional[int] = chkpt['''model'''] # We have the base model one level deeper than the original XLM repository UpperCAmelCase_ : str = {} for k, v in state_dict.items(): if "pred_layer" in k: UpperCAmelCase_ : Tuple = v else: UpperCAmelCase_ : Union[str, Any] = v UpperCAmelCase_ : int = chkpt['''params'''] UpperCAmelCase_ : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(__lowercase , (torch.FloatTensor, numpy.ndarray) )} UpperCAmelCase_ : int = chkpt['''dico_word2id'''] UpperCAmelCase_ : List[Any] = {s + '''</w>''' if s.find('''@@''' ) == -1 and i > 1_3 else s.replace('''@@''' , '''''' ): i for s, i in vocab.items()} # Save pytorch-model UpperCAmelCase_ : Tuple = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME UpperCAmelCase_ : Tuple = pytorch_dump_folder_path + '''/''' + CONFIG_NAME UpperCAmelCase_ : Dict = pytorch_dump_folder_path + '''/''' + VOCAB_FILES_NAMES['''vocab_file'''] print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(__lowercase , __lowercase ) print(F'''Save configuration file to {pytorch_config_dump_path}''' ) with open(__lowercase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__lowercase , indent=2 ) + '''\n''' ) print(F'''Save vocab file to {pytorch_config_dump_path}''' ) with open(__lowercase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(__lowercase , indent=2 ) + '''\n''' ) if __name__ == "__main__": __UpperCamelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xlm_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __UpperCamelCase : Dict = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
641
1
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _UpperCamelCase = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class lowerCamelCase__ ( snake_case , unittest.TestCase ): SCREAMING_SNAKE_CASE = XLNetTokenizer SCREAMING_SNAKE_CASE = XLNetTokenizerFast SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True def _UpperCamelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = XLNetTokenizer(A ,keep_accents=A ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def _UpperCamelCase ( self ): 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 ): 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] ,"""<eod>""" ) self.assertEqual(len(A ) ,1_006 ) def _UpperCamelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size ,1_000 ) def _UpperCamelCase ( self ): UpperCAmelCase = XLNetTokenizer(A ,keep_accents=A ) UpperCAmelCase = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(A ,["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) ,[285, 46, 10, 170, 382] ) UpperCAmelCase = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( A ,[ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] ,) UpperCAmelCase = tokenizer.convert_tokens_to_ids(A ) self.assertListEqual(A ,[8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) UpperCAmelCase = tokenizer.convert_ids_to_tokens(A ) self.assertListEqual( A ,[ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] ,) def _UpperCamelCase ( self ): UpperCAmelCase = XLNetTokenizer(A ,do_lower_case=A ) UpperCAmelCase = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( A ,[ SPIECE_UNDERLINE + """""", """i""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """se""", """.""", ] ,) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) ,["""▁he""", """ll""", """o"""] ) def _UpperCamelCase ( self ): UpperCAmelCase = XLNetTokenizer(A ,do_lower_case=A ) UpperCAmelCase = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( A ,[ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """se""", """.""", ] ,) @slow def _UpperCamelCase ( self ): UpperCAmelCase = XLNetTokenizer.from_pretrained("""xlnet-base-cased""" ) UpperCAmelCase = tokenizer.encode("""sequence builders""" ,add_special_tokens=A ) UpperCAmelCase = tokenizer.encode("""multi-sequence build""" ,add_special_tokens=A ) UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(A ) UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(A ,A ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def _UpperCamelCase ( self ): # fmt: off UpperCAmelCase = {"""input_ids""": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], """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, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=A ,model_name="""xlnet-base-cased""" ,revision="""c841166438c31ec7ca9a106dee7bb312b73ae511""" ,)
341
"""simple docstring""" def _a ( _snake_case ): """simple docstring""" UpperCAmelCase = int(_snake_case ) if decimal in (0, 1): # Exit cases for the recursion return str(_snake_case ) UpperCAmelCase , UpperCAmelCase = divmod(_snake_case , 2 ) return binary_recursive(_snake_case ) + str(_snake_case ) def _a ( _snake_case ): """simple docstring""" UpperCAmelCase = str(_snake_case ).strip() if not number: raise ValueError("""No input value was provided""" ) UpperCAmelCase = """-""" if number.startswith("""-""" ) else """""" UpperCAmelCase = number.lstrip("""-""" ) if not number.isnumeric(): raise ValueError("""Input value is not an integer""" ) return F'''{negative}0b{binary_recursive(int(_snake_case ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
341
1
def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Optional[int] = len(_a) SCREAMING_SNAKE_CASE : Optional[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): SCREAMING_SNAKE_CASE : Dict = True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1): SCREAMING_SNAKE_CASE : 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: SCREAMING_SNAKE_CASE : Optional[int] = subset[i - 1][j] if arr[i - 1] <= j: SCREAMING_SNAKE_CASE : 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()
193
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'microsoft/wavlm-base': 'https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json', # See all WavLM models at https://huggingface.co/models?filter=wavlm } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ ='wavlm' def __init__( self : Optional[int] , a : Optional[Any]=32 , a : int=768 , a : Tuple=12 , a : List[str]=12 , a : str=3072 , a : Any="gelu" , a : Dict=0.1 , a : int=0.1 , a : str=0.1 , a : Optional[Any]=0.0 , a : Any=0.1 , a : Any=0.1 , a : List[str]=0.02 , a : List[Any]=1e-5 , a : Any="group" , a : Optional[int]="gelu" , a : List[str]=(512, 512, 512, 512, 512, 512, 512) , a : Any=(5, 2, 2, 2, 2, 2, 2) , a : Union[str, Any]=(10, 3, 3, 3, 3, 2, 2) , a : Optional[Any]=False , a : Dict=128 , a : Optional[Any]=16 , a : Optional[Any]=320 , a : str=800 , a : Optional[int]=False , a : Tuple=True , a : Optional[Any]=0.05 , a : Any=10 , a : Optional[int]=2 , a : Dict=0.0 , a : str=10 , a : Tuple=320 , a : Optional[int]=2 , a : int=0.1 , a : List[str]=100 , a : Tuple=256 , a : str=256 , a : Tuple=0.1 , a : str="mean" , a : int=False , a : int=False , a : Optional[Any]=256 , a : Any=(512, 512, 512, 512, 1500) , a : Tuple=(5, 3, 3, 1, 1) , a : str=(1, 2, 3, 1, 1) , a : Optional[Any]=512 , a : Optional[Any]=80 , a : Tuple=0 , a : Any=1 , a : Optional[Any]=2 , a : int=False , a : Dict=3 , a : Any=2 , a : List[Any]=3 , a : int=None , **a : Any , ) -> Dict: """simple docstring""" super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a ) SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = feat_extract_norm SCREAMING_SNAKE_CASE : Any = feat_extract_activation SCREAMING_SNAKE_CASE : Any = list(a ) SCREAMING_SNAKE_CASE : Optional[int] = list(a ) SCREAMING_SNAKE_CASE : Optional[Any] = list(a ) SCREAMING_SNAKE_CASE : Any = conv_bias SCREAMING_SNAKE_CASE : str = num_buckets SCREAMING_SNAKE_CASE : str = max_bucket_distance SCREAMING_SNAKE_CASE : List[str] = num_conv_pos_embeddings SCREAMING_SNAKE_CASE : Any = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE : Union[str, Any] = len(self.conv_dim ) SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : Dict = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE : int = hidden_dropout SCREAMING_SNAKE_CASE : Optional[int] = attention_dropout SCREAMING_SNAKE_CASE : List[str] = activation_dropout SCREAMING_SNAKE_CASE : int = feat_proj_dropout SCREAMING_SNAKE_CASE : Any = final_dropout SCREAMING_SNAKE_CASE : Optional[int] = layerdrop SCREAMING_SNAKE_CASE : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE : int = initializer_range SCREAMING_SNAKE_CASE : Dict = num_ctc_classes SCREAMING_SNAKE_CASE : Tuple = vocab_size SCREAMING_SNAKE_CASE : int = do_stable_layer_norm SCREAMING_SNAKE_CASE : List[Any] = use_weighted_layer_sum SCREAMING_SNAKE_CASE : 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 SCREAMING_SNAKE_CASE : int = apply_spec_augment SCREAMING_SNAKE_CASE : int = mask_time_prob SCREAMING_SNAKE_CASE : Union[str, Any] = mask_time_length SCREAMING_SNAKE_CASE : List[Any] = mask_time_min_masks SCREAMING_SNAKE_CASE : Tuple = mask_feature_prob SCREAMING_SNAKE_CASE : List[str] = mask_feature_length # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE : str = num_codevectors_per_group SCREAMING_SNAKE_CASE : Dict = num_codevector_groups SCREAMING_SNAKE_CASE : Tuple = contrastive_logits_temperature SCREAMING_SNAKE_CASE : List[Any] = num_negatives SCREAMING_SNAKE_CASE : Optional[int] = codevector_dim SCREAMING_SNAKE_CASE : int = proj_codevector_dim SCREAMING_SNAKE_CASE : List[Any] = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE : Any = ctc_loss_reduction SCREAMING_SNAKE_CASE : Dict = ctc_zero_infinity # adapter SCREAMING_SNAKE_CASE : Any = add_adapter SCREAMING_SNAKE_CASE : Optional[int] = adapter_kernel_size SCREAMING_SNAKE_CASE : Any = adapter_stride SCREAMING_SNAKE_CASE : List[Any] = num_adapter_layers SCREAMING_SNAKE_CASE : int = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE : List[Any] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE : Union[str, Any] = list(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = list(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = list(a ) SCREAMING_SNAKE_CASE : Tuple = xvector_output_dim @property def __UpperCamelCase ( self : int ) -> Union[str, Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
193
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = ArgumentParser("Accelerate CLI tool" , usage="accelerate <command> [<args>]" , allow_abbrev=lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = parser.add_subparsers(help="accelerate command helpers" ) # Register commands get_config_parser(subparsers=lowercase ) env_command_parser(subparsers=lowercase ) launch_command_parser(subparsers=lowercase ) tpu_command_parser(subparsers=lowercase ) test_command_parser(subparsers=lowercase ) # Let's go SCREAMING_SNAKE_CASE : int = parser.parse_args() if not hasattr(lowercase , "func" ): parser.print_help() exit(1 ) # Run args.func(lowercase ) if __name__ == "__main__": main()
62
import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} snake_case = { """vocab_file""": { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt""" ), } } snake_case = { """junnyu/roformer_chinese_small""": 1_536, """junnyu/roformer_chinese_base""": 1_536, """junnyu/roformer_chinese_char_small""": 512, """junnyu/roformer_chinese_char_base""": 512, """junnyu/roformer_small_discriminator""": 128, """junnyu/roformer_small_generator""": 128, } snake_case = { """junnyu/roformer_chinese_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_base""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_base""": {"""do_lower_case""": True}, """junnyu/roformer_small_discriminator""": {"""do_lower_case""": True}, """junnyu/roformer_small_generator""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase_ : int = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : List[Any] = PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = RoFormerTokenizer def __init__( self : Tuple , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : List[str]="[UNK]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : Any="[PAD]" , UpperCAmelCase_ : List[str]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : List[str] , ): super().__init__( UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , tokenize_chinese_chars=UpperCAmelCase_ , strip_accents=UpperCAmelCase_ , **UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , UpperCAmelCase_ ) != do_lower_case or pre_tok_state.get("strip_accents" , UpperCAmelCase_ ) != strip_accents ): SCREAMING_SNAKE_CASE : Optional[Any] = getattr(UpperCAmelCase_ , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Any = do_lower_case SCREAMING_SNAKE_CASE : List[str] = strip_accents SCREAMING_SNAKE_CASE : Tuple = pre_tok_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = do_lower_case def __getstate__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE : Optional[Any] = BertPreTokenizer() return state def __setstate__( self : Tuple , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Dict = d SCREAMING_SNAKE_CASE : Dict = self.__dict__["_tokenizer"].get_vocab() SCREAMING_SNAKE_CASE : Any = PreTokenizer.custom(JiebaPreTokenizer(UpperCAmelCase_ ) ) def _A ( self : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE : List[Any] = [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 _A ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : List[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _A ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): SCREAMING_SNAKE_CASE : Optional[int] = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Any=False , **UpperCAmelCase_ : str , ): SCREAMING_SNAKE_CASE : Union[str, Any] = BertPreTokenizer() return super().save_pretrained(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ )
62
1
from collections import deque class UpperCamelCase__ : def __init__(self : str , snake_case_ : str , snake_case_ : int , snake_case_ : int ): __a : Optional[Any] = process_name # process name __a : Optional[Any] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time __a : Union[str, Any] = arrival_time __a : int = burst_time # remaining burst time __a : Dict = 0 # total time of the process wait in ready queue __a : Union[str, Any] = 0 # time from arrival time to completion time class UpperCamelCase__ : def __init__(self : Optional[Any] , snake_case_ : int , snake_case_ : list[int] , snake_case_ : deque[Process] , snake_case_ : int , ): # total number of mlfq's queues __a : Tuple = number_of_queues # time slice of queues that round robin algorithm applied __a : Optional[int] = time_slices # unfinished process is in this ready_queue __a : Optional[int] = queue # current time __a : List[Any] = current_time # finished process is in this sequence queue __a : deque[Process] = deque() def lowerCAmelCase (self : Dict ): __a : Tuple = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def lowerCAmelCase (self : List[Any] , snake_case_ : list[Process] ): __a : Optional[int] = [] for i in range(len(snake_case_ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def lowerCAmelCase (self : Optional[Any] , snake_case_ : list[Process] ): __a : Optional[int] = [] for i in range(len(snake_case_ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def lowerCAmelCase (self : Optional[Any] , snake_case_ : list[Process] ): __a : Any = [] for i in range(len(snake_case_ ) ): completion_times.append(queue[i].stop_time ) return completion_times def lowerCAmelCase (self : List[Any] , snake_case_ : deque[Process] ): return [q.burst_time for q in queue] def lowerCAmelCase (self : int , snake_case_ : Process ): process.waiting_time += self.current_time - process.stop_time return process.waiting_time def lowerCAmelCase (self : Tuple , snake_case_ : deque[Process] ): __a : deque[Process] = deque() # sequence deque of finished process while len(snake_case_ ) != 0: __a : Any = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(snake_case_ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 __a : Dict = 0 # set the process's turnaround time because it is finished __a : Tuple = self.current_time - cp.arrival_time # set the completion time __a : Dict = self.current_time # add the process to queue that has finished queue finished.append(snake_case_ ) self.finish_queue.extend(snake_case_ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def lowerCAmelCase (self : List[Any] , snake_case_ : deque[Process] , snake_case_ : int ): __a : deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(snake_case_ ) ): __a : Optional[Any] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(snake_case_ ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time __a : Dict = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(snake_case_ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished __a : Dict = 0 # set the finish time __a : Union[str, Any] = self.current_time # update the process' turnaround time because it is finished __a : List[Any] = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(snake_case_ ) self.finish_queue.extend(snake_case_ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def lowerCAmelCase (self : Optional[Any] ): # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1 ): __a , __a : str = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest lowercase__ =Process('P1', 0, 53) lowercase__ =Process('P2', 0, 17) lowercase__ =Process('P3', 0, 68) lowercase__ =Process('P4', 0, 24) lowercase__ =3 lowercase__ =[17, 25] lowercase__ =deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'queue': deque([Pa, Pa, Pa, Pa])}) lowercase__ =Process('P1', 0, 53) lowercase__ =Process('P2', 0, 17) lowercase__ =Process('P3', 0, 68) lowercase__ =Process('P4', 0, 24) lowercase__ =3 lowercase__ =[17, 25] lowercase__ =deque([Pa, Pa, Pa, Pa]) lowercase__ =MLFQ(number_of_queues, time_slices, queue, 0) lowercase__ =mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( F"""waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print completion times of processes(P1, P2, P3, P4) print( F"""completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print total turnaround times of processes(P1, P2, P3, P4) print( F"""turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print sequence of finished processes print( F"""sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}""" )
326
from manim import * class UpperCamelCase__ ( __lowercase ): def lowerCAmelCase (self : Any ): __a : Dict = Rectangle(height=0.5 , width=0.5 ) __a : Optional[Any] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __a : List[str] = [mem.copy() for i in range(6 )] __a : str = [mem.copy() for i in range(6 )] __a : List[Any] = VGroup(*snake_case_ ).arrange(snake_case_ , buff=0 ) __a : List[str] = VGroup(*snake_case_ ).arrange(snake_case_ , buff=0 ) __a : Tuple = VGroup(snake_case_ , snake_case_ ).arrange(snake_case_ , buff=0 ) __a : Union[str, Any] = Text('''CPU''' , font_size=2_4 ) __a : Tuple = Group(snake_case_ , snake_case_ ).arrange(snake_case_ , buff=0.5 , aligned_edge=snake_case_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(snake_case_ ) __a : int = [mem.copy() for i in range(4 )] __a : Dict = VGroup(*snake_case_ ).arrange(snake_case_ , buff=0 ) __a : List[str] = Text('''GPU''' , font_size=2_4 ) __a : Union[str, Any] = Group(snake_case_ , snake_case_ ).arrange(snake_case_ , buff=0.5 , aligned_edge=snake_case_ ) gpu.move_to([-1, -1, 0] ) self.add(snake_case_ ) __a : str = [mem.copy() for i in range(6 )] __a : Optional[Any] = VGroup(*snake_case_ ).arrange(snake_case_ , buff=0 ) __a : Optional[Any] = Text('''Model''' , font_size=2_4 ) __a : List[Any] = Group(snake_case_ , snake_case_ ).arrange(snake_case_ , buff=0.5 , aligned_edge=snake_case_ ) model.move_to([3, -1.0, 0] ) self.add(snake_case_ ) __a : Dict = [] for i, rect in enumerate(snake_case_ ): rect.set_stroke(snake_case_ ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) __a : Union[str, Any] = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(snake_case_ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=snake_case_ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=snake_case_ , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=snake_case_ , buff=0.0 ) self.add(snake_case_ ) cpu_targs.append(snake_case_ ) __a : List[str] = [mem.copy() for i in range(6 )] __a : Union[str, Any] = VGroup(*snake_case_ ).arrange(snake_case_ , buff=0 ) __a : Optional[int] = Text('''Loaded Checkpoint''' , font_size=2_4 ) __a : str = Group(snake_case_ , snake_case_ ).arrange(snake_case_ , aligned_edge=snake_case_ , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) __a : int = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __a : str = MarkupText( f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" , font_size=1_8 , ) key_text.move_to([-5, 2.4, 0] ) self.add(snake_case_ , snake_case_ ) __a : Dict = MarkupText( f"<span fgcolor='{BLUE}'>●</span> Checkpoint" , font_size=1_8 , ) blue_text.next_to(snake_case_ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) __a : int = MarkupText( f"Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>." , font_size=2_4 , ) step_a.move_to([2, 2, 0] ) self.play(Write(snake_case_ ) , Write(snake_case_ ) ) self.play(Write(snake_case_ , run_time=1 ) , Create(snake_case_ , run_time=1 ) ) __a : int = [] __a : int = [] for i, rect in enumerate(snake_case_ ): __a : Tuple = fill.copy().set_fill(snake_case_ , opacity=0.7 ) target.move_to(snake_case_ ) first_animations.append(GrowFromCenter(snake_case_ , run_time=1 ) ) __a : Optional[Any] = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(snake_case_ , run_time=1.5 ) ) self.play(*snake_case_ ) self.play(*snake_case_ ) self.wait()
326
1
"""simple docstring""" from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase__ ( __lowerCamelCase ): '''simple docstring''' _lowerCamelCase = """new-model""" if is_tf_available(): class lowerCamelCase__ ( __lowerCamelCase ): '''simple docstring''' _lowerCamelCase = NewModelConfig @require_tf class lowerCamelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase__ ( self ) -> Dict: A = """bert-base-cased""" A = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) A = TFAutoModel.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) @slow def UpperCamelCase__ ( self ) -> str: A = """bert-base-cased""" A = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) A = TFAutoModelForPreTraining.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) @slow def UpperCamelCase__ ( self ) -> Any: for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) A = TFAutoModelForCausalLM.from_pretrained(lowerCamelCase_ ) A , A = TFAutoModelForCausalLM.from_pretrained(lowerCamelCase_ ,output_loading_info=lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) @slow def UpperCamelCase__ ( self ) -> List[Any]: for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) A = TFAutoModelWithLMHead.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) @slow def UpperCamelCase__ ( self ) -> Optional[int]: for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) A = TFAutoModelForMaskedLM.from_pretrained(lowerCamelCase_ ) A , A = TFAutoModelForMaskedLM.from_pretrained(lowerCamelCase_ ,output_loading_info=lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) @slow def UpperCamelCase__ ( self ) -> Optional[int]: for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) A = TFAutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase_ ) A , A = TFAutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase_ ,output_loading_info=lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) @slow def UpperCamelCase__ ( self ) -> List[str]: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: A = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) A = TFAutoModelForSequenceClassification.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) @slow def UpperCamelCase__ ( self ) -> Any: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: A = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) A = TFAutoModelForQuestionAnswering.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) @slow @require_tensorflow_probability def UpperCamelCase__ ( self ) -> Union[str, Any]: for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: A = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) A = TFAutoModelForTableQuestionAnswering.from_pretrained(lowerCamelCase_ ) A , A = TFAutoModelForTableQuestionAnswering.from_pretrained( lowerCamelCase_ ,output_loading_info=lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) def UpperCamelCase__ ( self ) -> Union[str, Any]: A = TFAutoModelWithLMHead.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) self.assertEqual(model.num_parameters() ,1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase_ ) ,1_4_4_1_0 ) def UpperCamelCase__ ( self ) -> int: A = TFAutoModelWithLMHead.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) self.assertEqual(model.num_parameters() ,1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=lowerCamelCase_ ) ,1_4_4_1_0 ) def UpperCamelCase__ ( self ) -> str: # For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel A = TFAutoModel.from_pretrained("""sgugger/funnel-random-tiny""" ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) A = copy.deepcopy(model.config ) A = ["""FunnelBaseModel"""] A = TFAutoModel.from_config(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(lowerCamelCase_ ) A = TFAutoModel.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) def UpperCamelCase__ ( self ) -> Optional[int]: try: AutoConfig.register("""new-model""" ,lowerCamelCase_ ) A = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(lowerCamelCase_ ): auto_class.register(lowerCamelCase_ ,lowerCamelCase_ ) auto_class.register(lowerCamelCase_ ,lowerCamelCase_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase_ ): auto_class.register(lowerCamelCase_ ,lowerCamelCase_ ) # Now that the config is registered, it can be used as any other config with the auto-API A = BertModelTester(self ).get_config() A = NewModelConfig(**tiny_config.to_dict() ) A = auto_class.from_config(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(lowerCamelCase_ ) A = auto_class.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ ,lowerCamelCase_ ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def UpperCamelCase__ ( self ) -> int: with self.assertRaisesRegex( lowerCamelCase_ ,"""bert-base is not a local folder and is not a valid model identifier""" ): A = TFAutoModel.from_pretrained("""bert-base""" ) def UpperCamelCase__ ( self ) -> Dict: with self.assertRaisesRegex( lowerCamelCase_ ,r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): A = TFAutoModel.from_pretrained(lowerCamelCase_ ,revision="""aaaaaa""" ) def UpperCamelCase__ ( self ) -> List[str]: with self.assertRaisesRegex( lowerCamelCase_ ,"""hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin""" ,): A = TFAutoModel.from_pretrained("""hf-internal-testing/config-no-model""" ) def UpperCamelCase__ ( self ) -> List[Any]: with self.assertRaisesRegex(lowerCamelCase_ ,"""Use `from_pt=True` to load this model""" ): A = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-bert-pt-only""" ) def UpperCamelCase__ ( self ) -> str: # Make sure we have cached the model. A = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) with RequestCounter() as counter: A = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(counter.get_request_count ,0 ) self.assertEqual(counter.head_request_count ,1 ) self.assertEqual(counter.other_request_count ,0 ) # With a sharded checkpoint A = TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) with RequestCounter() as counter: A = TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) self.assertEqual(counter.get_request_count ,0 ) self.assertEqual(counter.head_request_count ,1 ) self.assertEqual(counter.other_request_count ,0 )
617
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class A_ : '''simple docstring''' def __init__( self , snake_case , snake_case=13 , snake_case=7 , snake_case=True , snake_case=True , snake_case=False , snake_case=True , snake_case=99 , snake_case=32 , snake_case=5 , snake_case=4 , snake_case=37 , snake_case="gelu" , snake_case=0.1 , snake_case=0.1 , snake_case=512 , snake_case=16 , snake_case=2 , snake_case=0.02 , snake_case=3 , snake_case=4 , snake_case=None , ): lowercase = parent lowercase = batch_size lowercase = seq_length lowercase = is_training lowercase = use_input_mask lowercase = use_token_type_ids lowercase = use_labels lowercase = vocab_size lowercase = hidden_size lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = intermediate_size lowercase = hidden_act lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = max_position_embeddings lowercase = type_vocab_size lowercase = type_sequence_label_size lowercase = initializer_range lowercase = num_labels lowercase = num_choices lowercase = scope def SCREAMING_SNAKE_CASE__ ( self ): lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase = None if self.use_input_mask: lowercase = random_attention_mask([self.batch_size, self.seq_length] ) lowercase = None if self.use_token_type_ids: lowercase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase = None lowercase = None lowercase = None if self.use_labels: lowercase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase = ids_tensor([self.batch_size] , self.num_choices ) lowercase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case ): lowercase = LlamaModel(config=snake_case ) model.to(snake_case ) model.eval() lowercase = model(snake_case , attention_mask=snake_case ) lowercase = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ): lowercase = True lowercase = LlamaModel(snake_case ) model.to(snake_case ) model.eval() lowercase = model( snake_case , attention_mask=snake_case , encoder_hidden_states=snake_case , encoder_attention_mask=snake_case , ) lowercase = model( snake_case , attention_mask=snake_case , encoder_hidden_states=snake_case , ) lowercase = model(snake_case , attention_mask=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ): lowercase = LlamaForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() lowercase = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ): lowercase = True lowercase = True lowercase = LlamaForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() # first forward pass lowercase = model( snake_case , attention_mask=snake_case , encoder_hidden_states=snake_case , encoder_attention_mask=snake_case , use_cache=snake_case , ) lowercase = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids lowercase = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowercase = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and lowercase = torch.cat([input_ids, next_tokens] , dim=-1 ) lowercase = torch.cat([input_mask, next_mask] , dim=-1 ) lowercase = model( snake_case , attention_mask=snake_case , encoder_hidden_states=snake_case , encoder_attention_mask=snake_case , output_hidden_states=snake_case , )['hidden_states'][0] lowercase = model( snake_case , attention_mask=snake_case , encoder_hidden_states=snake_case , encoder_attention_mask=snake_case , past_key_values=snake_case , output_hidden_states=snake_case , )['hidden_states'][0] # select random slice lowercase = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowercase = output_from_no_past[:, -3:, random_slice_idx].detach() lowercase = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1E-3 ) ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.prepare_config_and_inputs() ( ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ) = config_and_inputs lowercase = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): '''simple docstring''' _UpperCamelCase : Tuple = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () _UpperCamelCase : List[Any] = (LlamaForCausalLM,) if is_torch_available() else () _UpperCamelCase : int = ( { """feature-extraction""": LlamaModel, """text-classification""": LlamaForSequenceClassification, """text-generation""": LlamaForCausalLM, """zero-shot""": LlamaForSequenceClassification, } if is_torch_available() else {} ) _UpperCamelCase : int = False _UpperCamelCase : int = False def SCREAMING_SNAKE_CASE__ ( self ): lowercase = LlamaModelTester(self ) lowercase = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowercase = type self.model_tester.create_and_check_model(*snake_case ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase = self.model_tester.prepare_config_and_inputs_for_common() lowercase = 3 lowercase = input_dict['input_ids'] lowercase = input_ids.ne(1 ).to(snake_case ) lowercase = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowercase = LlamaForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() lowercase = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase = self.model_tester.prepare_config_and_inputs_for_common() lowercase = 3 lowercase = 'single_label_classification' lowercase = input_dict['input_ids'] lowercase = input_ids.ne(1 ).to(snake_case ) lowercase = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowercase = LlamaForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() lowercase = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase = self.model_tester.prepare_config_and_inputs_for_common() lowercase = 3 lowercase = 'multi_label_classification' lowercase = input_dict['input_ids'] lowercase = input_ids.ne(1 ).to(snake_case ) lowercase = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) lowercase = LlamaForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() lowercase = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def SCREAMING_SNAKE_CASE__ ( self ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case ): lowercase , lowercase = self.model_tester.prepare_config_and_inputs_for_common() lowercase = ids_tensor([1, 10] , config.vocab_size ) lowercase = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights lowercase = LlamaModel(snake_case ) original_model.to(snake_case ) original_model.eval() lowercase = original_model(snake_case ).last_hidden_state lowercase = original_model(snake_case ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights lowercase = {'type': scaling_type, 'factor': 10.0} lowercase = LlamaModel(snake_case ) scaled_model.to(snake_case ) scaled_model.eval() lowercase = scaled_model(snake_case ).last_hidden_state lowercase = scaled_model(snake_case ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(snake_case , snake_case , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(snake_case , snake_case , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(snake_case , snake_case , atol=1E-5 ) ) @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def SCREAMING_SNAKE_CASE__ ( self ): lowercase = [1, 306, 4658, 278, 6593, 310, 2834, 338] lowercase = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) lowercase = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 lowercase = torch.tensor([[-6.6_550, -4.1_227, -4.9_859, -3.2_406, 0.8_262, -3.0_033, 1.2_964, -3.3_699]] ) torch.testing.assert_close(out.mean(-1 ) , snake_case , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowercase = torch.tensor([-12.8_281, -7.4_453, -0.4_639, -8.0_625, -7.2_500, -8.0_000, -6.4_883, -7.7_695, -7.8_438, -7.0_312, -6.2_188, -7.1_328, -1.8_496, 1.9_961, -8.6_250, -6.7_227, -12.8_281, -6.9_492, -7.0_742, -7.7_852, -7.5_820, -7.9_062, -6.9_375, -7.9_805, -8.3_438, -8.1_562, -8.0_469, -7.6_250, -7.7_422, -7.3_398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , snake_case , atol=1E-5 , rtol=1E-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def SCREAMING_SNAKE_CASE__ ( self ): lowercase = [1, 306, 4658, 278, 6593, 310, 2834, 338] lowercase = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) lowercase = model(torch.tensor(snake_case ) ) # Expected mean on dim = -1 lowercase = torch.tensor([[-2.0_622, -1.2_794, -1.1_638, -0.9_788, -1.4_603, -1.0_238, -1.7_893, -1.4_411]] ) torch.testing.assert_close(out.mean(-1 ) , snake_case , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowercase = torch.tensor([-8.1_406, -8.0_547, 2.7_461, -1.2_344, -0.1_448, -1.8_262, -1.0_020, -1.8_154, -1.6_895, -1.8_516, -2.3_574, -0.9_277, 3.7_598, 6.5_742, -1.2_998, -0.1_177, -8.1_406, -2.9_688, -2.9_199, -3.1_699, -3.5_254, -2.3_555, -2.7_988, -3.4_141, -2.8_262, -4.5_195, -3.3_379, -3.3_164, -2.7_832, -3.0_273] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , snake_case , atol=1E-5 , rtol=1E-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def SCREAMING_SNAKE_CASE__ ( self ): lowercase = [1, 306, 4658, 278, 6593, 310, 2834, 338] lowercase = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) lowercase = model(torch.tensor(snake_case ) ) # Expected mean on dim = -1 lowercase = torch.tensor([[-0.8_562, -1.8_520, -0.7_551, -0.4_162, -1.5_161, -1.2_038, -2.4_823, -2.3_254]] ) torch.testing.assert_close(out.mean(-1 ) , snake_case , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowercase = torch.tensor([-2.2_227, 4.8_828, 0.9_023, -0.4_578, -0.7_871, -0.1_033, -0.6_221, -0.5_786, -0.7_803, -1.0_674, -1.2_920, -0.1_570, 0.8_008, 2.0_723, -0.9_497, 0.2_771, -2.2_227, -0.7_612, -1.4_346, -1.2_061, -1.6_426, -0.3_000, -0.7_139, -1.1_934, -1.8_691, -1.6_973, -1.5_947, -1.2_705, -0.3_523, -0.5_513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , snake_case , atol=1E-2 , rtol=1E-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def SCREAMING_SNAKE_CASE__ ( self ): lowercase = [1, 306, 4658, 278, 6593, 310, 2834, 338] lowercase = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) lowercase = model(torch.tensor(snake_case ) ) lowercase = torch.tensor( [[-4.2_327, -3.3_360, -4.6_665, -4.7_631, -1.8_180, -3.4_170, -1.4_211, -3.1_810]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , snake_case , atol=1E-2 , rtol=1E-2 ) # fmt: off lowercase = torch.tensor([-9.4_922, -3.9_551, 1.7_998, -5.6_758, -5.1_055, -5.8_984, -4.8_320, -6.8_086, -6.5_391, -5.6_172, -5.5_820, -5.5_352, 1.7_881, 3.6_289, -6.5_117, -3.4_785, -9.5_000, -6.0_352, -6.8_125, -6.0_195, -6.6_836, -5.4_727, -6.2_812, -6.0_391, -7.3_398, -7.4_297, -7.4_844, -6.5_820, -5.8_789, -5.5_312] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , snake_case , atol=1E-5 , rtol=1E-5 ) @unittest.skip('Model is curently gated' ) @slow def SCREAMING_SNAKE_CASE__ ( self ): lowercase = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' lowercase = 'Simply put, the theory of relativity states that ' lowercase = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) lowercase = tokenizer.encode(snake_case , return_tensors='pt' ) lowercase = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=snake_case ) # greedy generation outputs lowercase = model.generate(snake_case , max_new_tokens=64 , top_p=snake_case , temperature=1 , do_sample=snake_case ) lowercase = tokenizer.decode(generated_ids[0] , skip_special_tokens=snake_case ) self.assertEqual(snake_case , snake_case )
84
0
"""simple docstring""" from __future__ import annotations def __A ( a_ :int) -> list[int]: __a : int = [True] * limit __a : Tuple = False __a : Dict = False __a : Optional[Any] = True for i in range(3 , int(limit**0.5 + 1) , 2): __a : Union[str, Any] = i * 2 while index < limit: __a : Optional[int] = False __a : Optional[Any] = index + i __a : Dict = [2] for i in range(3 , a_ , 2): if is_prime[i]: primes.append(a_) return primes def __A ( a_ :int = 1_00_00_00) -> int: __a : Optional[Any] = prime_sieve(a_) __a : str = 0 __a : List[Any] = 0 for i in range(len(a_)): for j in range(i + length , len(a_)): __a : str = sum(primes[i:j]) if sol >= ceiling: break if sol in primes: __a : Tuple = j - i __a : List[Any] = sol return largest if __name__ == "__main__": print(F'{solution() = }')
101
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer A = ['''bert-base-uncased''', '''bert-base-cased'''] A = '''hf-internal-testing/tiny-bert-tf-only''' if is_tf_available(): class __lowercase ( tf.keras.Model ): '''simple docstring''' def __init__( self , _UpperCAmelCase ): super().__init__() __a : Any = tokenizer __a : Optional[Any] = AutoConfig.from_pretrained(_UpperCAmelCase ) __a : str = TFAutoModel.from_config(_UpperCAmelCase ) def _lowerCamelCase ( self , _UpperCAmelCase ): __a : Any = self.tokenizer(_UpperCAmelCase ) __a : int = self.bert(**_UpperCAmelCase ) return out["pooler_output"] @require_tf @require_tensorflow_text class __lowercase ( unittest.TestCase ): '''simple docstring''' def _lowerCamelCase ( self ): super().setUp() __a : Any = [ BertTokenizer.from_pretrained(_UpperCAmelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false __a : Union[str, Any] = [TFBertTokenizer.from_pretrained(_UpperCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(_UpperCAmelCase , use_fast_bert_tokenizer=_UpperCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __a : Tuple = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] __a : Any = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _lowerCamelCase ( self ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): __a : List[Any] = tokenizer(_UpperCAmelCase , return_tensors='''tf''' , padding='''longest''' ) __a : List[str] = tf_tokenizer(_UpperCAmelCase ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def _lowerCamelCase ( self ): for tf_tokenizer in self.tf_tokenizers: __a : Dict = tf_tokenizer(self.paired_sentences ) __a : str = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def _lowerCamelCase ( self ): for tf_tokenizer in self.tf_tokenizers: __a : Tuple = tf.function(_UpperCAmelCase ) for test_inputs in (self.test_sentences, self.paired_sentences): __a : List[str] = tf.constant(_UpperCAmelCase ) __a : Tuple = compiled_tokenizer(_UpperCAmelCase ) __a : Union[str, Any] = tf_tokenizer(_UpperCAmelCase ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _lowerCamelCase ( self ): for tf_tokenizer in self.tf_tokenizers: __a : Dict = ModelToSave(tokenizer=_UpperCAmelCase ) __a : Tuple = tf.convert_to_tensor(self.test_sentences ) __a : List[str] = model(_UpperCAmelCase ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __a : Tuple = Path(_UpperCAmelCase ) / '''saved.model''' model.save(_UpperCAmelCase ) __a : Tuple = tf.keras.models.load_model(_UpperCAmelCase ) __a : int = loaded_model(_UpperCAmelCase ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1e-5 )
101
1
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') lowerCAmelCase : List[Any] = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) lowerCAmelCase : List[Any] = requests.get(url, headers={'UserAgent': UserAgent().random}) # res.raise_for_status() with open('project1a.html', 'wb') as out_file: # only for knowing the class for data in res.iter_content(1_00_00): out_file.write(data) lowerCAmelCase : Tuple = BeautifulSoup(res.text, 'html.parser') lowerCAmelCase : List[Any] = list(soup.select('.eZt8xd'))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('href')) else: webbrowser.open(f"""https://google.com{link.get('href')}""")
3
import sys def __UpperCamelCase (lowerCAmelCase : Dict ) -> Dict: A = len(lowerCAmelCase ) A = [[0 for x in range(lowerCAmelCase )] for x in range(lowerCAmelCase )] A = [[0 for x in range(lowerCAmelCase )] for x in range(lowerCAmelCase )] for chain_length in range(2, lowerCAmelCase ): for a in range(1, n - chain_length + 1 ): A = a + chain_length - 1 A = sys.maxsize for c in range(lowerCAmelCase, lowerCAmelCase ): A = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: A = cost A = c return matrix, sol def __UpperCamelCase (lowerCAmelCase : Optional[Any], lowerCAmelCase : Union[str, Any], lowerCAmelCase : Union[str, Any] ) -> List[str]: if i == j: print('A' + str(lowerCAmelCase ), end=' ' ) else: print('(', end=' ' ) print_optiomal_solution(lowerCAmelCase, lowerCAmelCase, optimal_solution[i][j] ) print_optiomal_solution(lowerCAmelCase, optimal_solution[i][j] + 1, lowerCAmelCase ) print(')', end=' ' ) def __UpperCamelCase () -> List[str]: A = [30, 35, 15, 5, 10, 20, 25] A = len(lowerCAmelCase ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 A , A = matrix_chain_order(lowerCAmelCase ) print('No. of Operation required: ' + str(matrix[1][n - 1] ) ) print_optiomal_solution(lowerCAmelCase, 1, n - 1 ) if __name__ == "__main__": main()
699
0
'''simple docstring''' import json import os import unittest from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class a__( lowerCamelCase__ , unittest.TestCase ): lowercase__ = XLMTokenizer lowercase__ = False def lowercase_ ( self : List[str] ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt a : Dict = [ '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 : List[Any] = dict(zip(__snake_case , range(len(__snake_case ) ) ) ) a : Any = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] a : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) a : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' ) as fp: fp.write(json.dumps(__snake_case ) ) with open(self.merges_file , 'w' ) as fp: fp.write('\n'.join(__snake_case ) ) def lowercase_ ( self : int , __snake_case : str ): a : Dict = 'lower newer' a : Optional[int] = 'lower newer' return input_text, output_text def lowercase_ ( self : Optional[int] ): a : Dict = XLMTokenizer(self.vocab_file , self.merges_file ) a : Union[str, Any] = 'lower' a : Any = ['low', 'er</w>'] a : str = tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) a : List[str] = tokens + ['<unk>'] a : Optional[Any] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , __snake_case ) @slow def lowercase_ ( self : Any ): a : Optional[Any] = XLMTokenizer.from_pretrained('xlm-mlm-en-2048' ) a : Tuple = tokenizer.encode('sequence builders' , add_special_tokens=__snake_case ) a : Dict = tokenizer.encode('multi-sequence build' , add_special_tokens=__snake_case ) a : Any = tokenizer.build_inputs_with_special_tokens(__snake_case ) a : Tuple = tokenizer.build_inputs_with_special_tokens(__snake_case , __snake_case ) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
709
'''simple docstring''' import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class a__( lowerCamelCase__ , unittest.TestCase ): lowercase__ = """hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline""" def lowercase_ ( self : Dict , __snake_case : Union[str, Any]=0 ): a : List[str] = floats_tensor((1, 3, 1_28, 1_28) , rng=random.Random(__snake_case ) ) a : Optional[Any] = np.random.RandomState(__snake_case ) a : List[str] = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def lowercase_ ( self : Union[str, Any] ): a : Dict = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=__snake_case ) a : Any = self.get_dummy_inputs() a : int = pipe(**__snake_case ).images a : List[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 1_28, 1_28, 3) a : Dict = np.array([0.69643, 0.58484, 0.50314, 0.58760, 0.55368, 0.59643, 0.51529, 0.41217, 0.49087] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def lowercase_ ( self : str ): a : List[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a : Dict = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) a : Any = self.get_dummy_inputs() a : str = pipe(**__snake_case ).images a : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) a : int = np.array([0.61737, 0.54642, 0.53183, 0.54465, 0.52742, 0.60525, 0.49969, 0.40655, 0.48154] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def lowercase_ ( self : List[str] ): a : Optional[int] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a : List[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__snake_case ) # warmup pass to apply optimizations a : Any = pipe(**self.get_dummy_inputs() ) a : Optional[int] = self.get_dummy_inputs() a : Optional[int] = pipe(**__snake_case ).images a : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) a : Any = np.array([0.52761, 0.59977, 0.49033, 0.49619, 0.54282, 0.50311, 0.47600, 0.40918, 0.45203] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def lowercase_ ( self : List[Any] ): a : Dict = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a : Any = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__snake_case ) a : List[str] = self.get_dummy_inputs() a : Optional[int] = pipe(**__snake_case ).images a : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) a : Dict = np.array([0.52911, 0.60004, 0.49229, 0.49805, 0.54502, 0.50680, 0.47777, 0.41028, 0.45304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def lowercase_ ( self : Tuple ): a : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a : Optional[Any] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__snake_case ) a : Dict = self.get_dummy_inputs() a : Union[str, Any] = pipe(**__snake_case ).images a : int = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) a : int = np.array([0.52911, 0.60004, 0.49229, 0.49805, 0.54502, 0.50680, 0.47777, 0.41028, 0.45304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def lowercase_ ( self : Optional[Any] ): a : Optional[int] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a : Optional[int] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__snake_case ) a : Tuple = self.get_dummy_inputs() a : Optional[Any] = pipe(**__snake_case ).images a : str = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) a : Optional[int] = np.array([0.65331, 0.58277, 0.48204, 0.56059, 0.53665, 0.56235, 0.50969, 0.40009, 0.46552] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class a__( unittest.TestCase ): @property def lowercase_ ( self : List[Any] ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowercase_ ( self : Dict ): a : Tuple = ort.SessionOptions() a : Optional[Any] = False return options def lowercase_ ( self : List[str] ): a : Dict = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) a : Optional[int] = init_image.resize((7_68, 5_12) ) # using the PNDM scheduler by default a : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=__snake_case , feature_extractor=__snake_case , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__snake_case ) a : Union[str, Any] = 'A fantasy landscape, trending on artstation' a : Dict = np.random.RandomState(0 ) a : Optional[int] = pipe( prompt=__snake_case , image=__snake_case , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=__snake_case , output_type='np' , ) a : str = output.images a : Optional[int] = images[0, 2_55:2_58, 3_83:3_86, -1] assert images.shape == (1, 5_12, 7_68, 3) a : List[str] = np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def lowercase_ ( self : str ): a : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) a : List[str] = init_image.resize((7_68, 5_12) ) a : Union[str, Any] = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) a : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=__snake_case , safety_checker=__snake_case , feature_extractor=__snake_case , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__snake_case ) a : Optional[int] = 'A fantasy landscape, trending on artstation' a : str = np.random.RandomState(0 ) a : List[str] = pipe( prompt=__snake_case , image=__snake_case , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=__snake_case , output_type='np' , ) a : str = output.images a : Tuple = images[0, 2_55:2_58, 3_83:3_86, -1] assert images.shape == (1, 5_12, 7_68, 3) a : Union[str, Any] = np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
195
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, 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_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _A ( __lowercase , __lowercase , unittest.TestCase ): lowercase__: List[Any] = StableDiffusionXLImgaImgPipeline lowercase__: Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} lowercase__: Optional[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} lowercase__: Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowercase__: Dict = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase__: int = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowercase__ ( self : List[str] ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) __snake_case : List[str] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , attention_head_dim=(2, 4) , use_linear_projection=__magic_name__ , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) __snake_case : List[Any] = EulerDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) __snake_case : List[Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=1_28 , ) torch.manual_seed(0 ) __snake_case : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act="""gelu""" , projection_dim=32 , ) __snake_case : Tuple = CLIPTextModel(__magic_name__ ) __snake_case : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__magic_name__ ) __snake_case : Dict = CLIPTextModelWithProjection(__magic_name__ ) __snake_case : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__magic_name__ ) __snake_case : Any = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def lowercase__ ( self : Dict , __magic_name__ : Any , __magic_name__ : Any=0 ) -> Any: """simple docstring""" __snake_case : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__magic_name__ ) ).to(__magic_name__ ) __snake_case : Dict = image / 2 + 0.5 if str(__magic_name__ ).startswith("""mps""" ): __snake_case : Tuple = torch.manual_seed(__magic_name__ ) else: __snake_case : List[str] = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) __snake_case : Dict = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.75, } return inputs def lowercase__ ( self : str ) -> List[str]: """simple docstring""" __snake_case : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator __snake_case : Any = self.get_dummy_components() __snake_case : Tuple = StableDiffusionXLImgaImgPipeline(**__magic_name__ ) __snake_case : List[str] = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) __snake_case : Tuple = self.get_dummy_inputs(__magic_name__ ) __snake_case : Union[str, Any] = sd_pipe(**__magic_name__ ).images __snake_case : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __snake_case : str = np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowercase__ ( self : Dict ) -> Dict: """simple docstring""" super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def lowercase__ ( self : List[str] ) -> Any: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def lowercase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" pass def lowercase__ ( self : str ) -> Tuple: """simple docstring""" __snake_case : List[str] = self.get_dummy_components() __snake_case : Union[str, Any] = StableDiffusionXLImgaImgPipeline(**__magic_name__ ) __snake_case : Optional[Any] = sd_pipe.to(__magic_name__ ) __snake_case : int = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) # forward without prompt embeds __snake_case : Optional[int] = self.get_dummy_inputs(__magic_name__ ) __snake_case : int = 3 * ["""this is a negative prompt"""] __snake_case : Union[str, Any] = negative_prompt __snake_case : str = 3 * [inputs["""prompt"""]] __snake_case : List[str] = sd_pipe(**__magic_name__ ) __snake_case : int = output.images[0, -3:, -3:, -1] # forward with prompt embeds __snake_case : int = self.get_dummy_inputs(__magic_name__ ) __snake_case : List[Any] = 3 * ["""this is a negative prompt"""] __snake_case : Optional[Any] = 3 * [inputs.pop("""prompt""" )] ( ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ) : int = sd_pipe.encode_prompt(__magic_name__ , negative_prompt=__magic_name__ ) __snake_case : Any = sd_pipe( **__magic_name__ , prompt_embeds=__magic_name__ , negative_prompt_embeds=__magic_name__ , pooled_prompt_embeds=__magic_name__ , negative_pooled_prompt_embeds=__magic_name__ , ) __snake_case : str = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class _A ( unittest.TestCase ): def lowercase__ ( self : int ) -> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase__ ( self : Dict , __magic_name__ : Optional[int] , __magic_name__ : str="cpu" , __magic_name__ : List[str]=torch.floataa , __magic_name__ : str=0 ) -> str: """simple docstring""" __snake_case : Dict = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) __snake_case : Union[str, Any] = np.random.RandomState(__magic_name__ ).standard_normal((1, 4, 64, 64) ) __snake_case : Dict = torch.from_numpy(__magic_name__ ).to(device=__magic_name__ , dtype=__magic_name__ ) __snake_case : Tuple = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def lowercase__ ( self : Any ) -> Optional[Any]: """simple docstring""" __snake_case : str = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) __snake_case : Optional[Any] = self.get_inputs(__magic_name__ ) __snake_case : str = pipe(**__magic_name__ ).images __snake_case : Any = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) __snake_case : List[Any] = np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
26
"""simple docstring""" from scipy.stats import spearmanr import datasets A = """ The Spearman rank-order correlation coefficient is a measure of the relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Positive correlations imply that as data in dataset x increases, so does data in dataset y. Negative correlations imply that as x increases, y decreases. Correlations of -1 or +1 imply an exact monotonic relationship. Unlike the Pearson correlation, the Spearman correlation does not assume that both datasets are normally distributed. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Spearman correlation at least as extreme as the one computed from these datasets. The p-values are not entirely reliable but are probably reasonable for datasets larger than 500 or so. """ A = """ Args: predictions (`List[float]`): Predicted labels, as returned by a model. references (`List[float]`): Ground truth labels. return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns only the spearmanr score. Defaults to `False`. Returns: spearmanr (`float`): Spearman correlation coefficient. p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input. Examples: Example 1: >>> spearmanr_metric = datasets.load_metric(\"spearmanr\") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4]) >>> print(results) {'spearmanr': -0.7} Example 2: >>> spearmanr_metric = datasets.load_metric(\"spearmanr\") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], ... predictions=[10, 9, 2.5, 6, 4], ... return_pvalue=True) >>> print(results['spearmanr']) -0.7 >>> print(round(results['spearmanr_pvalue'], 2)) 0.19 """ A = r"""\ @book{kokoska2000crc, title={CRC standard probability and statistics tables and formulae}, author={Kokoska, Stephen and Zwillinger, Daniel}, year={2000}, publisher={Crc Press} } @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__ ( datasets.Metric ): def a_ ( self : Any): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("float"), "references": datasets.Value("float"), }) , reference_urls=["https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"] , ) def a_ ( self : Union[str, Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : int=False): """simple docstring""" __UpperCAmelCase : List[str] = spearmanr(UpperCamelCase_ , UpperCamelCase_) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
77
0
"""simple docstring""" import argparse import os # New Code # 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 import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ = 16 a_ = 32 def a__ ( __lowercase , __lowercase = 16 ) -> Tuple: _A = AutoTokenizer.from_pretrained("bert-base-cased" ) _A = load_dataset("glue" , "mrpc" ) def tokenize_function(__lowercase ): # max_length=None => use the model max length (it's actually the default) _A = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=__lowercase , max_length=__lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _A = datasets.map( __lowercase , batched=__lowercase , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _A = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(__lowercase ): # On TPU it's best to pad everything to the same length or training will be very slow. _A = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _A = 16 elif accelerator.mixed_precision != "no": _A = 8 else: _A = None return tokenizer.pad( __lowercase , padding="longest" , max_length=__lowercase , pad_to_multiple_of=__lowercase , return_tensors="pt" , ) # Instantiate dataloaders. _A = DataLoader( tokenized_datasets["train"] , shuffle=__lowercase , collate_fn=__lowercase , batch_size=__lowercase ) _A = DataLoader( tokenized_datasets["validation"] , shuffle=__lowercase , collate_fn=__lowercase , batch_size=__lowercase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a_ = mocked_dataloaders # noqa: F811 def a__ ( __lowercase , __lowercase ) -> str: # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS" , __lowercase ) == "1": _A = 2 # Initialize accelerator _A = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _A = config["lr"] _A = int(config["num_epochs"] ) _A = int(config["seed"] ) _A = int(config["batch_size"] ) _A = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=__lowercase ) def inner_training_loop(__lowercase ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(__lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _A = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=__lowercase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _A = model.to(accelerator.device ) # Instantiate optimizer _A = AdamW(params=model.parameters() , lr=__lowercase ) _A , _A = get_dataloaders(__lowercase , __lowercase ) # Instantiate scheduler _A = get_linear_schedule_with_warmup( optimizer=__lowercase , num_warmup_steps=100 , num_training_steps=(len(__lowercase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _A , _A , _A , _A , _A = accelerator.prepare( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) # Now we train the model for epoch in range(__lowercase ): model.train() for step, batch in enumerate(__lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _A = model(**__lowercase ) _A = outputs.loss accelerator.backward(__lowercase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _A = model(**__lowercase ) _A = outputs.logits.argmax(dim=-1 ) _A , _A = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=__lowercase , references=__lowercase , ) _A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __lowercase ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def a__ ( ) -> int: _A = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=__lowercase , default=__lowercase , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) _A = parser.parse_args() _A = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(__lowercase , __lowercase ) if __name__ == "__main__": main()
716
"""simple docstring""" import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ = logging.get_logger(__name__) class snake_case ( _UpperCamelCase): def __init__( self : str , *a__ : Dict , **a__ : Optional[int] ) -> None: '''simple docstring''' warnings.warn( "The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use GLPNImageProcessor instead." , a__ , ) super().__init__(*a__ , **a__ )
621
0
import collections import inspect import unittest from transformers import FocalNetConfig 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_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self , a , a=13 , a=32 , a=2 , a=3 , a=16 , a=[32, 64, 128] , a=[1, 2, 1] , a=[2, 2, 4] , a=2 , a=2.0 , a=True , a=0.0 , a=0.0 , a=0.1 , a="gelu" , a=False , a=True , a=0.02 , a=1e-5 , a=True , a=None , a=True , a=10 , a=8 , a=["stage1", "stage2"] , a=[1, 2] , ): lowercase__ : int = parent lowercase__ : str = batch_size lowercase__ : str = image_size lowercase__ : Tuple = patch_size lowercase__ : List[Any] = num_channels lowercase__ : List[Any] = embed_dim lowercase__ : Any = hidden_sizes lowercase__ : Optional[Any] = depths lowercase__ : Union[str, Any] = num_heads lowercase__ : List[Any] = window_size lowercase__ : List[Any] = mlp_ratio lowercase__ : int = qkv_bias lowercase__ : Any = hidden_dropout_prob lowercase__ : int = attention_probs_dropout_prob lowercase__ : str = drop_path_rate lowercase__ : Dict = hidden_act lowercase__ : List[str] = use_absolute_embeddings lowercase__ : Tuple = patch_norm lowercase__ : int = layer_norm_eps lowercase__ : Union[str, Any] = initializer_range lowercase__ : Union[str, Any] = is_training lowercase__ : Dict = scope lowercase__ : Optional[Any] = use_labels lowercase__ : List[Any] = type_sequence_label_size lowercase__ : int = encoder_stride lowercase__ : Union[str, Any] = out_features lowercase__ : int = out_indices def snake_case_ ( self): lowercase__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) lowercase__ : Optional[int] = None if self.use_labels: lowercase__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size) lowercase__ : str = self.get_config() return config, pixel_values, labels def snake_case_ ( self): return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def snake_case_ ( self , a , a , a): lowercase__ : Tuple = FocalNetModel(config=__UpperCamelCase) model.to(__UpperCamelCase) model.eval() lowercase__ : str = model(__UpperCamelCase) lowercase__ : Any = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1)) lowercase__ : List[Any] = int(config.embed_dim * 2 ** (len(config.depths) - 1)) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim)) def snake_case_ ( self , a , a , a): lowercase__ : List[Any] = FocalNetBackbone(config=__UpperCamelCase) model.to(__UpperCamelCase) model.eval() lowercase__ : Optional[Any] = model(__UpperCamelCase) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , len(config.out_features)) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.image_size, 8, 8]) # verify channels self.parent.assertEqual(len(model.channels) , len(config.out_features)) self.parent.assertListEqual(model.channels , config.hidden_sizes[:-1]) # verify backbone works with out_features=None lowercase__ : Union[str, Any] = None lowercase__ : Dict = FocalNetBackbone(config=__UpperCamelCase) model.to(__UpperCamelCase) model.eval() lowercase__ : int = model(__UpperCamelCase) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , 1) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.image_size * 2, 4, 4]) # verify channels self.parent.assertEqual(len(model.channels) , 1) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]]) def snake_case_ ( self , a , a , a): lowercase__ : Any = FocalNetForMaskedImageModeling(config=__UpperCamelCase) model.to(__UpperCamelCase) model.eval() lowercase__ : str = model(__UpperCamelCase) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size)) # test greyscale images lowercase__ : Optional[int] = 1 lowercase__ : int = FocalNetForMaskedImageModeling(__UpperCamelCase) model.to(__UpperCamelCase) model.eval() lowercase__ : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) lowercase__ : Union[str, Any] = model(__UpperCamelCase) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size)) def snake_case_ ( self , a , a , a): lowercase__ : Dict = self.type_sequence_label_size lowercase__ : int = FocalNetForImageClassification(__UpperCamelCase) model.to(__UpperCamelCase) model.eval() lowercase__ : Any = model(__UpperCamelCase , labels=__UpperCamelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images lowercase__ : int = 1 lowercase__ : str = FocalNetForImageClassification(__UpperCamelCase) model.to(__UpperCamelCase) model.eval() lowercase__ : Union[str, Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) lowercase__ : List[Any] = model(__UpperCamelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def snake_case_ ( self): lowercase__ : List[Any] = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ : Union[str, Any] = config_and_inputs lowercase__ : Any = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ (_UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): __lowerCamelCase : int = ( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) __lowerCamelCase : Any = ( {'feature-extraction': FocalNetModel, 'image-classification': FocalNetForImageClassification} if is_torch_available() else {} ) __lowerCamelCase : int = False __lowerCamelCase : int = False __lowerCamelCase : Any = False __lowerCamelCase : Any = False __lowerCamelCase : Tuple = False def snake_case_ ( self): lowercase__ : List[str] = FocalNetModelTester(self) lowercase__ : str = ConfigTester(self , config_class=__UpperCamelCase , embed_dim=37 , has_text_modality=__UpperCamelCase) def snake_case_ ( self): 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 snake_case_ ( self): return def snake_case_ ( self): lowercase__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCamelCase) def snake_case_ ( self): lowercase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__UpperCamelCase) def snake_case_ ( self): lowercase__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__UpperCamelCase) def snake_case_ ( self): lowercase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase) @unittest.skip(reason='FocalNet does not use inputs_embeds') def snake_case_ ( self): pass @unittest.skip(reason='FocalNet does not use feedforward chunking') def snake_case_ ( self): pass def snake_case_ ( self): lowercase__ , lowercase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: lowercase__ : str = model_class(__UpperCamelCase) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) lowercase__ : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__UpperCamelCase , nn.Linear)) def snake_case_ ( self): lowercase__ , lowercase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: lowercase__ : List[Any] = model_class(__UpperCamelCase) lowercase__ : str = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : Union[str, Any] = [*signature.parameters.keys()] lowercase__ : Tuple = ['pixel_values'] self.assertListEqual(arg_names[:1] , __UpperCamelCase) def snake_case_ ( self , a , a , a , a): lowercase__ : Any = model_class(__UpperCamelCase) model.to(__UpperCamelCase) model.eval() with torch.no_grad(): lowercase__ : Tuple = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase)) lowercase__ : Tuple = outputs.hidden_states lowercase__ : Optional[int] = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths) + 1) self.assertEqual(len(__UpperCamelCase) , __UpperCamelCase) # FocalNet has a different seq_length lowercase__ : Optional[int] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable) else (config.patch_size, config.patch_size) ) lowercase__ : Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [num_patches, self.model_tester.embed_dim] , ) lowercase__ : Union[str, Any] = outputs.reshaped_hidden_states self.assertEqual(len(__UpperCamelCase) , __UpperCamelCase) lowercase__ , lowercase__ , lowercase__ , lowercase__ : List[Any] = reshaped_hidden_states[0].shape lowercase__ : str = ( reshaped_hidden_states[0].view(__UpperCamelCase , __UpperCamelCase , height * width).permute(0 , 2 , 1) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:]) , [num_patches, self.model_tester.embed_dim] , ) def snake_case_ ( self): lowercase__ , lowercase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Union[str, Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: lowercase__ : Optional[Any] = True self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : Optional[int] = True self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase) def snake_case_ ( self): lowercase__ , lowercase__ : str = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Any = 3 lowercase__ : Optional[int] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable) else (self.model_tester.image_size, self.model_tester.image_size) ) lowercase__ : Tuple = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable) else (config.patch_size, config.patch_size) ) lowercase__ : str = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) lowercase__ : int = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: lowercase__ : Any = True self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , (padded_height, padded_width)) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : Union[str, Any] = True self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , (padded_height, padded_width)) @slow def snake_case_ ( self): for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ : Dict = FocalNetModel.from_pretrained(__UpperCamelCase) self.assertIsNotNone(__UpperCamelCase) def snake_case_ ( self): lowercase__ , lowercase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : str = _config_zero_init(__UpperCamelCase) for model_class in self.all_model_classes: lowercase__ : Optional[Any] = model_class(config=__UpperCamelCase) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @require_vision @require_torch class SCREAMING_SNAKE_CASE__ (unittest.TestCase ): @cached_property def snake_case_ ( self): return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny') if is_vision_available() else None @slow def snake_case_ ( self): lowercase__ : Dict = FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny').to(__UpperCamelCase) lowercase__ : List[Any] = self.default_image_processor lowercase__ : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') lowercase__ : Optional[Any] = image_processor(images=__UpperCamelCase , return_tensors='pt').to(__UpperCamelCase) # forward pass with torch.no_grad(): lowercase__ : Union[str, Any] = model(**__UpperCamelCase) # verify the logits lowercase__ : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , __UpperCamelCase) lowercase__ : str = torch.tensor([0.2_166, -0.4_368, 0.2_191]).to(__UpperCamelCase) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCamelCase , atol=1e-4)) self.assertTrue(outputs.logits.argmax(dim=-1).item() , 281) @require_torch class SCREAMING_SNAKE_CASE__ (_UpperCAmelCase , unittest.TestCase ): __lowerCamelCase : Optional[Any] = (FocalNetBackbone,) if is_torch_available() else () __lowerCamelCase : Optional[Any] = FocalNetConfig __lowerCamelCase : Optional[int] = False def snake_case_ ( self): lowercase__ : Dict = FocalNetModelTester(self)
164
"""simple docstring""" import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig a : List[str] = logging.get_logger(__name__) class a_ : def __init__( self : List[str] , __UpperCamelCase : Any , __UpperCamelCase : Tuple ) ->Tuple: '''simple docstring''' _UpperCAmelCase = question_encoder _UpperCAmelCase = generator _UpperCAmelCase = self.question_encoder def _snake_case ( self : int , __UpperCamelCase : str ) ->Dict: '''simple docstring''' if os.path.isfile(__UpperCamelCase ): raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) _UpperCAmelCase = os.path.join(__UpperCamelCase , """question_encoder_tokenizer""" ) _UpperCAmelCase = os.path.join(__UpperCamelCase , """generator_tokenizer""" ) self.question_encoder.save_pretrained(__UpperCamelCase ) self.generator.save_pretrained(__UpperCamelCase ) @classmethod def _snake_case ( cls : Optional[Any] , __UpperCamelCase : Tuple , **__UpperCamelCase : Optional[Any] ) ->Tuple: '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer _UpperCAmelCase = kwargs.pop("""config""" , __UpperCamelCase ) if config is None: _UpperCAmelCase = RagConfig.from_pretrained(__UpperCamelCase ) _UpperCAmelCase = AutoTokenizer.from_pretrained( __UpperCamelCase , config=config.question_encoder , subfolder="""question_encoder_tokenizer""" ) _UpperCAmelCase = AutoTokenizer.from_pretrained( __UpperCamelCase , config=config.generator , subfolder="""generator_tokenizer""" ) return cls(question_encoder=__UpperCamelCase , generator=__UpperCamelCase ) def __call__( self : Any , *__UpperCamelCase : List[Any] , **__UpperCamelCase : Optional[Any] ) ->Optional[Any]: '''simple docstring''' return self.current_tokenizer(*__UpperCamelCase , **__UpperCamelCase ) def _snake_case ( self : Union[str, Any] , *__UpperCamelCase : List[Any] , **__UpperCamelCase : Tuple ) ->Any: '''simple docstring''' return self.generator.batch_decode(*__UpperCamelCase , **__UpperCamelCase ) def _snake_case ( self : Optional[int] , *__UpperCamelCase : Optional[int] , **__UpperCamelCase : List[str] ) ->Union[str, Any]: '''simple docstring''' return self.generator.decode(*__UpperCamelCase , **__UpperCamelCase ) def _snake_case ( self : Union[str, Any] ) ->Dict: '''simple docstring''' _UpperCAmelCase = self.question_encoder def _snake_case ( self : Tuple ) ->Optional[int]: '''simple docstring''' _UpperCAmelCase = self.generator def _snake_case ( self : List[Any] , __UpperCamelCase : List[str] , __UpperCamelCase : Optional[List[str]] = None , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : str = "longest" , __UpperCamelCase : str = None , __UpperCamelCase : bool = True , **__UpperCamelCase : Tuple , ) ->BatchEncoding: '''simple docstring''' warnings.warn( """`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the """ """regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` """ """context manager to prepare your targets. See the documentation of your specific tokenizer for more """ """details""" , __UpperCamelCase , ) if max_length is None: _UpperCAmelCase = self.current_tokenizer.model_max_length _UpperCAmelCase = self( __UpperCamelCase , add_special_tokens=__UpperCamelCase , return_tensors=__UpperCamelCase , max_length=__UpperCamelCase , padding=__UpperCamelCase , truncation=__UpperCamelCase , **__UpperCamelCase , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: _UpperCAmelCase = self.current_tokenizer.model_max_length _UpperCAmelCase = self( text_target=__UpperCamelCase , add_special_tokens=__UpperCamelCase , return_tensors=__UpperCamelCase , padding=__UpperCamelCase , max_length=__UpperCamelCase , truncation=__UpperCamelCase , **__UpperCamelCase , ) _UpperCAmelCase = labels["""input_ids"""] return model_inputs
555
0
from math import factorial def _A ( lowerCamelCase , lowerCamelCase ): # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("Please enter positive integers for n and k where n >= k" ) return factorial(lowerCamelCase ) // (factorial(lowerCamelCase ) * factorial(n - k )) if __name__ == "__main__": print( """The number of five-card hands possible from a standard""", f'fifty-two card deck is: {combinations(5_2, 5)}\n', ) print( """If a class of 40 students must be arranged into groups of""", f'4 for group projects, there are {combinations(4_0, 4)} ways', """to arrange them.\n""", ) print( """If 10 teams are competing in a Formula One race, there""", f'are {combinations(1_0, 3)} ways that first, second and', """third place can be awarded.""", )
629
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin SCREAMING_SNAKE_CASE__ : Dict = """ Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning. In March 2021, Hugging Face raised $40 million in a Series B funding round.[3] On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5] """ class __lowerCAmelCase ( unittest.TestCase ,_UpperCamelCase ): def _snake_case ( self ) -> str: """simple docstring""" a__ : Optional[int] = load_tool("text-question-answering" ) self.tool.setup() a__ : Dict = load_tool("text-question-answering" , remote=snake_case ) def _snake_case ( self ) -> Dict: """simple docstring""" a__ : Optional[Any] = self.tool(snake_case , "What did Hugging Face do in April 2021?" ) self.assertEqual(snake_case , "launched the BigScience Research Workshop" ) def _snake_case ( self ) -> Tuple: """simple docstring""" a__ : List[Any] = self.remote_tool(snake_case , "What did Hugging Face do in April 2021?" ) self.assertEqual(snake_case , "launched the BigScience Research Workshop" ) def _snake_case ( self ) -> Any: """simple docstring""" a__ : Any = self.tool(text=snake_case , question="What did Hugging Face do in April 2021?" ) self.assertEqual(snake_case , "launched the BigScience Research Workshop" ) def _snake_case ( self ) -> int: """simple docstring""" a__ : List[str] = self.remote_tool(text=snake_case , question="What did Hugging Face do in April 2021?" ) self.assertEqual(snake_case , "launched the BigScience Research Workshop" )
629
1
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __UpperCamelCase ( _a ,_a ): '''simple docstring''' @register_to_config def __init__( self , *, lowerCamelCase__ = 4 , lowerCamelCase__ = 7_6_8 , lowerCamelCase__ , lowerCamelCase__ , ): super().__init__() UpperCAmelCase__: int = nn.Parameter(torch.zeros(lowerCamelCase__ ) ) # parameters for additional clip time embeddings UpperCAmelCase__: Optional[Any] = nn.Linear(lowerCamelCase__ , lowerCamelCase__ ) UpperCAmelCase__: str = nn.Linear(lowerCamelCase__ , lowerCamelCase__ ) # parameters for encoder hidden states UpperCAmelCase__: Tuple = clip_extra_context_tokens UpperCAmelCase__: List[str] = nn.Linear( lowerCamelCase__ , self.clip_extra_context_tokens * cross_attention_dim ) UpperCAmelCase__: Union[str, Any] = nn.Linear(lowerCamelCase__ , lowerCamelCase__ ) UpperCAmelCase__: str = nn.LayerNorm(lowerCamelCase__ ) def _UpperCAmelCase ( self , *, lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings UpperCAmelCase__: Any = image_embeddings.shape[0] UpperCAmelCase__: Optional[Any] = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) UpperCAmelCase__: Union[str, Any] = classifier_free_guidance_embeddings.expand( lowerCamelCase__ , -1 ) UpperCAmelCase__: Tuple = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] UpperCAmelCase__: str = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... UpperCAmelCase__: List[str] = self.embedding_proj(lowerCamelCase__ ) UpperCAmelCase__: Optional[int] = self.clip_image_embeddings_project_to_time_embeddings(lowerCamelCase__ ) UpperCAmelCase__: Any = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" UpperCAmelCase__: Dict = self.clip_extra_context_tokens_proj(lowerCamelCase__ ) UpperCAmelCase__: Optional[Any] = clip_extra_context_tokens.reshape(lowerCamelCase__ , -1 , self.clip_extra_context_tokens ) UpperCAmelCase__: Dict = clip_extra_context_tokens.permute(0 , 2 , 1 ) UpperCAmelCase__: Any = self.encoder_hidden_states_proj(lowerCamelCase__ ) UpperCAmelCase__: List[str] = self.text_encoder_hidden_states_norm(lowerCamelCase__ ) UpperCAmelCase__: Optional[int] = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
113
def _A ( SCREAMING_SNAKE_CASE ): # noqa: E741 UpperCAmelCase__: int = len(SCREAMING_SNAKE_CASE ) UpperCAmelCase__: Dict = 0 UpperCAmelCase__: Optional[int] = [0] * n UpperCAmelCase__: List[str] = [False] * n UpperCAmelCase__: List[str] = [False] * n def dfs(SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ): if parent == root: out_edge_count += 1 UpperCAmelCase__: List[str] = True UpperCAmelCase__: List[Any] = at for to in l[at]: if to == parent: pass elif not visited[to]: UpperCAmelCase__: str = dfs(SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ) UpperCAmelCase__: Optional[Any] = min(low[at] ,low[to] ) # AP found via bridge if at < low[to]: UpperCAmelCase__: List[Any] = True # AP found via cycle if at == low[to]: UpperCAmelCase__: str = True else: UpperCAmelCase__: Union[str, Any] = min(low[at] ,SCREAMING_SNAKE_CASE ) return out_edge_count for i in range(SCREAMING_SNAKE_CASE ): if not visited[i]: UpperCAmelCase__: Optional[Any] = 0 UpperCAmelCase__: Union[str, Any] = dfs(SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,-1 ,SCREAMING_SNAKE_CASE ) UpperCAmelCase__: Tuple = out_edge_count > 1 for x in range(len(SCREAMING_SNAKE_CASE ) ): if is_art[x] is True: print(SCREAMING_SNAKE_CASE ) # Adjacency list of graph _lowerCAmelCase : Any ={ 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
113
1
'''simple docstring''' import operator as op UpperCamelCase_ = '''scaler.pt''' UpperCamelCase_ = '''pytorch_model''' UpperCamelCase_ = '''random_states''' UpperCamelCase_ = '''optimizer''' UpperCamelCase_ = '''scheduler''' UpperCamelCase_ = '''pytorch_model.bin''' UpperCamelCase_ = '''pytorch_model.bin.index.json''' UpperCamelCase_ = '''model.safetensors''' UpperCamelCase_ = '''model.safetensors.index.json''' UpperCamelCase_ = '''1.10.2''' UpperCamelCase_ = '''py38''' UpperCamelCase_ = '''4.17.0''' UpperCamelCase_ = ['''ml.p3.16xlarge''', '''ml.p3dn.24xlarge''', '''ml.p4dn.24xlarge'''] UpperCamelCase_ = ['''FULL_SHARD''', '''SHARD_GRAD_OP''', '''NO_SHARD''', '''HYBRID_SHARD''', '''HYBRID_SHARD_ZERO2'''] UpperCamelCase_ = ['''TRANSFORMER_BASED_WRAP''', '''SIZE_BASED_WRAP''', '''NO_WRAP'''] UpperCamelCase_ = ['''BACKWARD_PRE''', '''BACKWARD_POST''', '''NO_PREFETCH'''] UpperCamelCase_ = ['''FULL_STATE_DICT''', '''LOCAL_STATE_DICT''', '''SHARDED_STATE_DICT'''] UpperCamelCase_ = '''2.0.1''' UpperCamelCase_ = ['''pdsh''', '''standard''', '''openmpi''', '''mvapich'''] UpperCamelCase_ = ['''default''', '''reduce-overhead''', '''max-autotune'''] UpperCamelCase_ = {'''>''': op.gt, '''>=''': op.ge, '''==''': op.eq, '''!=''': op.ne, '''<=''': op.le, '''<''': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase_ = [ '''nnodes''', '''nproc_per_node''', '''rdzv_backend''', '''rdzv_endpoint''', '''rdzv_id''', '''rdzv_conf''', '''standalone''', '''max_restarts''', '''monitor_interval''', '''start_method''', '''role''', '''module''', '''m''', '''no_python''', '''run_path''', '''log_dir''', '''r''', '''redirects''', '''t''', '''tee''', '''node_rank''', '''master_addr''', '''master_port''', ] UpperCamelCase_ = ['''DEEPSPEED''', '''MULTI_GPU''', '''FSDP''', '''MEGATRON_LM'''] UpperCamelCase_ = ['''DEEPSPEED''', '''MULTI_XPU''', '''FSDP''']
721
'''simple docstring''' from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class _SCREAMING_SNAKE_CASE( _SCREAMING_SNAKE_CASE ): def __init__( self : Tuple , UpperCamelCase_ : NestedDataStructureLike[PathLike] , UpperCamelCase_ : Optional[NamedSplit] = None , UpperCamelCase_ : Optional[Features] = None , UpperCamelCase_ : str = None , UpperCamelCase_ : bool = False , UpperCamelCase_ : bool = False , UpperCamelCase_ : Optional[int] = None , **UpperCamelCase_ : List[str] , ) -> str: super().__init__( UpperCamelCase_ , split=UpperCamelCase_ , features=UpperCamelCase_ , cache_dir=UpperCamelCase_ , keep_in_memory=UpperCamelCase_ , streaming=UpperCamelCase_ , num_proc=UpperCamelCase_ , **UpperCamelCase_ , ) SCREAMING_SNAKE_CASE__ :int = path_or_paths if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE__ :List[Any] = Text( cache_dir=UpperCamelCase_ , data_files=UpperCamelCase_ , features=UpperCamelCase_ , **UpperCamelCase_ , ) def __lowerCamelCase ( self : Optional[Any] ) -> Optional[Any]: # Build iterable dataset if self.streaming: SCREAMING_SNAKE_CASE__ :int = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: SCREAMING_SNAKE_CASE__ :str = None SCREAMING_SNAKE_CASE__ :Union[str, Any] = None SCREAMING_SNAKE_CASE__ :Optional[int] = None SCREAMING_SNAKE_CASE__ :Tuple = None self.builder.download_and_prepare( download_config=UpperCamelCase_ , download_mode=UpperCamelCase_ , verification_mode=UpperCamelCase_ , base_path=UpperCamelCase_ , num_proc=self.num_proc , ) SCREAMING_SNAKE_CASE__ :int = self.builder.as_dataset( split=self.split , verification_mode=UpperCamelCase_ , in_memory=self.keep_in_memory ) return dataset
320
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class snake_case__ ( UpperCamelCase): a_ = "openai/whisper-base" a_ = ( "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the " "transcribed text." ) a_ = "transcriber" a_ = WhisperProcessor a_ = WhisperForConditionalGeneration a_ = ["audio"] a_ = ["text"] def A ( self : int , _A : Dict ) -> Any: return self.pre_processor(_A , return_tensors='''pt''' ).input_features def A ( self : Optional[int] , _A : Tuple ) -> int: return self.model.generate(inputs=_A ) def A ( self : Union[str, Any] , _A : Union[str, Any] ) -> int: return self.pre_processor.batch_decode(_A , skip_special_tokens=_A )[0]
541
'''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 snake_case__ ( UpperCamelCase): a_ = ["image_processor", "tokenizer"] a_ = "LayoutLMv2ImageProcessor" a_ = ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__( self : Optional[int] , _A : str=None , _A : Optional[Any]=None , **_A : Any ) -> Tuple: if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _A , ) UpperCAmelCase_ : int = kwargs.pop('''feature_extractor''' ) UpperCAmelCase_ : 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__(_A , _A ) def __call__( self : str , _A : Optional[int] , _A : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , _A : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , _A : Union[List[List[int]], List[List[List[int]]]] = None , _A : Optional[Union[List[int], List[List[int]]]] = None , _A : bool = True , _A : Union[bool, str, PaddingStrategy] = False , _A : Union[bool, str, TruncationStrategy] = None , _A : Optional[int] = None , _A : int = 0 , _A : Optional[int] = None , _A : Optional[bool] = None , _A : Optional[bool] = None , _A : bool = False , _A : bool = False , _A : bool = False , _A : bool = False , _A : bool = True , _A : Optional[Union[str, TensorType]] = None , **_A : Dict , ) -> BatchEncoding: # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes ''' '''if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) 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 UpperCAmelCase_ : int = self.image_processor(images=_A , return_tensors=_A ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_A , _A ): UpperCAmelCase_ : int = [text] # add batch dimension (as the image processor always adds a batch dimension) UpperCAmelCase_ : int = features['''words'''] UpperCAmelCase_ : str = 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=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_token_type_ids=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , ) # add pixel values UpperCAmelCase_ : int = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: UpperCAmelCase_ : List[Any] = self.get_overflowing_images(_A , encoded_inputs['''overflow_to_sample_mapping'''] ) UpperCAmelCase_ : Optional[int] = images return encoded_inputs def A ( self : Union[str, Any] , _A : int , _A : Tuple ) -> Dict: # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image UpperCAmelCase_ : Tuple = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_A ) != len(_A ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' F" {len(_A )} and {len(_A )}" ) return images_with_overflow def A ( self : Optional[Any] , *_A : Union[str, Any] , **_A : Union[str, Any] ) -> Tuple: return self.tokenizer.batch_decode(*_A , **_A ) def A ( self : Any , *_A : Optional[Any] , **_A : Tuple ) -> Tuple: return self.tokenizer.decode(*_A , **_A ) @property def A ( self : Union[str, Any] ) -> List[Any]: return ["input_ids", "bbox", "attention_mask", "image"] @property def A ( self : Tuple ) -> Optional[int]: warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _A , ) return self.image_processor_class @property def A ( self : Tuple ) -> str: warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _A , ) return self.image_processor
541
1
UpperCamelCase__ = { "joule": 1.0, "kilojoule": 1_000, "megajoule": 1_000_000, "gigajoule": 1_000_000_000, "wattsecond": 1.0, "watthour": 3_600, "kilowatthour": 3_600_000, "newtonmeter": 1.0, "calorie_nutr": 4_186.8, "kilocalorie_nutr": 4_186_800.00, "electronvolt": 1.6_02_17_66_34e-19, "britishthermalunit_it": 1_055.05_585, "footpound": 1.35_58_18, } def _UpperCamelCase (a__ :str , a__ :str , a__ :float ): """simple docstring""" if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: UpperCamelCase__ = ( f"""Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n""" f"""Valid values are: {", ".join(a__ )}""" ) raise ValueError(a__ ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
704
import math def _UpperCamelCase (a__ :int ): """simple docstring""" UpperCamelCase__ = [True] * n UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): UpperCamelCase__ = i * 2 while index < n: UpperCamelCase__ = False UpperCamelCase__ = index + i UpperCamelCase__ = [2] for i in range(3 , a__ , 2 ): if is_prime[i]: primes.append(a__ ) return primes def _UpperCamelCase (a__ :int = 9999_6666_3333 ): """simple docstring""" UpperCamelCase__ = math.floor(math.sqrt(a__ ) ) + 100 UpperCamelCase__ = prime_sieve(a__ ) UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = primes[prime_index] while (last_prime**2) <= limit: UpperCamelCase__ = primes[prime_index + 1] UpperCamelCase__ = last_prime**2 UpperCamelCase__ = next_prime**2 # Get numbers divisible by lps(current) UpperCamelCase__ = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) UpperCamelCase__ = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps UpperCamelCase__ = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair UpperCamelCase__ = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
548
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ : Optional[Any] = { "configuration_git": ["GIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GitConfig", "GitVisionConfig"], "processing_git": ["GitProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Union[str, Any] = [ "GIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GitForCausalLM", "GitModel", "GitPreTrainedModel", "GitVisionModel", ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
'''simple docstring''' from __future__ import annotations from functools import lru_cache from math import ceil UpperCAmelCase__ : Optional[Any] = 1_00 UpperCAmelCase__ : Any = set(range(3, NUM_PRIMES, 2)) primes.add(2) UpperCAmelCase__ : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=1_00 ) def A ( UpperCamelCase_ : int ) -> set[int]: '''simple docstring''' if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} lowerCAmelCase__ = set() lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def A ( UpperCamelCase_ : int = 50_00 ) -> int | None: '''simple docstring''' for number_to_partition in range(1 , UpperCamelCase_ ): if len(partition(UpperCamelCase_ ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(F"{solution() = }")
48
1
from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration _UpperCamelCase: Tuple ='facebook/wmt19-en-de' _UpperCamelCase: Union[str, Any] =FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model _UpperCamelCase: int =FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) _UpperCamelCase: str =FSMTForConditionalGeneration(config) print(F"num of params {tiny_model.num_parameters()}") # Test _UpperCamelCase: Optional[Any] =tokenizer(['Making tiny model'], return_tensors='pt') _UpperCamelCase: List[str] =tiny_model(**batch) print('test output:', len(outputs.logits[0])) # Save _UpperCamelCase: int ='tiny-wmt19-en-de' tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-de
710
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def _a ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : float | Decimal , __SCREAMING_SNAKE_CASE : float = 10**-10 ): """simple docstring""" _lowerCAmelCase = a while True: _lowerCAmelCase = Decimal(__SCREAMING_SNAKE_CASE ) - ( Decimal(eval(__SCREAMING_SNAKE_CASE ) ) / Decimal(eval(str(diff(__SCREAMING_SNAKE_CASE ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__SCREAMING_SNAKE_CASE ) ) < precision: # noqa: S307 return float(__SCREAMING_SNAKE_CASE ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}") # Find root of polynomial print(F"The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}") # Find Square Root of 5 print(F"The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}") # Exponential Roots print(F"The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}")
585
0