code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib lowerCAmelCase__ : List[str] =threading.Lock() lowerCAmelCase__ : Optional[logging.Handler] =None lowerCAmelCase__ : List[Any] ={ 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } lowerCAmelCase__ : Tuple =logging.WARNING lowerCAmelCase__ : Dict =True def a__ ( ): SCREAMING_SNAKE_CASE_ : Optional[int] = os.getenv('TRANSFORMERS_VERBOSITY', A__ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F'''Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ''' F'''has to be one of: { ', '.join(log_levels.keys() ) }''' ) return _default_log_level def a__ ( ): return __name__.split('.' )[0] def a__ ( ): return logging.getLogger(_get_library_name() ) def a__ ( ): global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return SCREAMING_SNAKE_CASE_ : Optional[int] = logging.StreamHandler() # Set sys.stderr as stream. SCREAMING_SNAKE_CASE_ : Any = sys.stderr.flush # Apply our default configuration to the library root logger. SCREAMING_SNAKE_CASE_ : Union[str, Any] = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) SCREAMING_SNAKE_CASE_ : int = False def a__ ( ): global _default_handler with _lock: if not _default_handler: return SCREAMING_SNAKE_CASE_ : List[str] = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) SCREAMING_SNAKE_CASE_ : int = None def a__ ( ): return log_levels def a__ ( A__ = None ): if name is None: SCREAMING_SNAKE_CASE_ : List[str] = _get_library_name() _configure_library_root_logger() return logging.getLogger(A__ ) def a__ ( ): _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def a__ ( A__ ): _configure_library_root_logger() _get_library_root_logger().setLevel(A__ ) def a__ ( ): return set_verbosity(A__ ) def a__ ( ): return set_verbosity(A__ ) def a__ ( ): return set_verbosity(A__ ) def a__ ( ): return set_verbosity(A__ ) def a__ ( ): _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def a__ ( ): _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def a__ ( A__ ): _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(A__ ) def a__ ( A__ ): _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(A__ ) def a__ ( ): _configure_library_root_logger() SCREAMING_SNAKE_CASE_ : str = False def a__ ( ): _configure_library_root_logger() SCREAMING_SNAKE_CASE_ : str = True def a__ ( ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = _get_library_root_logger().handlers for handler in handlers: SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s' ) handler.setFormatter(A__ ) def a__ ( ): SCREAMING_SNAKE_CASE_ : Optional[Any] = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(A__ ) def a__ ( self, *A__, **A__ ): SCREAMING_SNAKE_CASE_ : Dict = os.getenv('TRANSFORMERS_NO_ADVISORY_WARNINGS', A__ ) if no_advisory_warnings: return self.warning(*A__, **A__ ) lowerCAmelCase__ : Optional[Any] =warning_advice @functools.lru_cache(A__ ) def a__ ( self, *A__, **A__ ): self.warning(*A__, **A__ ) lowerCAmelCase__ : List[str] =warning_once class __lowercase : """simple docstring""" def __init__( self , *lowerCAmelCase__ , **lowerCAmelCase__ ): # pylint: disable=unused-argument """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = args[0] if args else None def __iter__( self ): """simple docstring""" return iter(self._iterator ) def __getattr__( self , lowerCAmelCase__ ): """simple docstring""" def empty_fn(*lowerCAmelCase__ , **lowerCAmelCase__ ): # pylint: disable=unused-argument return return empty_fn def __enter__( self ): """simple docstring""" return self def __exit__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" return class __lowercase : """simple docstring""" def __call__( self , *lowerCAmelCase__ , **lowerCAmelCase__ ): """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm(*lowerCAmelCase__ , **lowerCAmelCase__ ) else: return EmptyTqdm(*lowerCAmelCase__ , **lowerCAmelCase__ ) def UpperCamelCase__ ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*lowerCAmelCase__ , **lowerCAmelCase__ ) def UpperCamelCase__ ( self ): """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm.get_lock() lowerCAmelCase__ : str =_tqdm_cls() def a__ ( ): global _tqdm_active return bool(_tqdm_active ) def a__ ( ): global _tqdm_active SCREAMING_SNAKE_CASE_ : Any = True hf_hub_utils.enable_progress_bars() def a__ ( ): global _tqdm_active SCREAMING_SNAKE_CASE_ : Optional[int] = False hf_hub_utils.disable_progress_bars()
101
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int=13 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : str=224 , UpperCAmelCase__ : str=30 , UpperCAmelCase__ : Tuple=400 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Union[str, Any]=[0.5, 0.5, 0.5] , UpperCAmelCase__ : Tuple=[0.5, 0.5, 0.5] , ) ->str: '''simple docstring''' A__ = size if size is not None else {'''height''': 18, '''width''': 18} A__ = parent A__ = batch_size A__ = num_channels A__ = image_size A__ = min_resolution A__ = max_resolution A__ = do_resize A__ = size A__ = do_normalize A__ = image_mean A__ = image_std def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = ViTImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE ( self : List[str]) ->str: '''simple docstring''' A__ = EfficientFormerImageProcessorTester(self) @property def SCREAMING_SNAKE_CASE ( self : Dict) ->int: '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Dict: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_mean''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_std''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_normalize''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''')) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Dict: '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self : str) ->Optional[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random PIL images A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , torch.Tensor) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
87
0
"""simple docstring""" import argparse import math import os from copy import deepcopy import torch from audio_diffusion.models import DiffusionAttnUnetaD from diffusion import sampling from torch import nn from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel __magic_name__ : Any = { """gwf-440k""": { """url""": """https://model-server.zqevans2.workers.dev/gwf-440k.ckpt""", """sample_rate""": 4_8_0_0_0, """sample_size""": 6_5_5_3_6, }, """jmann-small-190k""": { """url""": """https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt""", """sample_rate""": 4_8_0_0_0, """sample_size""": 6_5_5_3_6, }, """jmann-large-580k""": { """url""": """https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt""", """sample_rate""": 4_8_0_0_0, """sample_size""": 1_3_1_0_7_2, }, """maestro-uncond-150k""": { """url""": """https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt""", """sample_rate""": 1_6_0_0_0, """sample_size""": 6_5_5_3_6, }, """unlocked-uncond-250k""": { """url""": """https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt""", """sample_rate""": 1_6_0_0_0, """sample_size""": 6_5_5_3_6, }, """honk-140k""": { """url""": """https://model-server.zqevans2.workers.dev/honk-140k.ckpt""", """sample_rate""": 1_6_0_0_0, """sample_size""": 6_5_5_3_6, }, } def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return torch.atana(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) / math.pi * 2 def UpperCamelCase (SCREAMING_SNAKE_CASE ): UpperCamelCase : Optional[Any] = torch.sin(t * math.pi / 2 ) ** 2 UpperCamelCase : Dict = (1 - sigma**2) ** 0.5 return alpha_sigma_to_t(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) class lowercase__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" pass class lowercase__ ( nn.Module ): """simple docstring""" def __init__( self , _A ): '''simple docstring''' super().__init__() UpperCamelCase : List[str] = DiffusionAttnUnetaD(_A , n_attn_layers=4 ) UpperCamelCase : Tuple = deepcopy(self.diffusion ) UpperCamelCase : Dict = torch.quasirandom.SobolEngine(1 , scramble=_A ) def UpperCamelCase (SCREAMING_SNAKE_CASE ): UpperCamelCase : Optional[int] = MODELS_MAP[model_name]["""url"""] os.system(f"""wget {url} ./""" ) return f"""./{model_name}.ckpt""" __magic_name__ : str = { """1""": """resnets.0""", """2""": """attentions.0""", """3""": """resnets.1""", """4""": """attentions.1""", """5""": """resnets.2""", """6""": """attentions.2""", } __magic_name__ : Dict = { """8""": """resnets.0""", """9""": """attentions.0""", """10""": """resnets.1""", """11""": """attentions.1""", """12""": """resnets.2""", """13""": """attentions.2""", } __magic_name__ : Any = { """1""": """resnets.0""", """2""": """attentions.0""", """3""": """resnets.1""", """4""": """attentions.1""", """5""": """resnets.2""", """6""": """attentions.2""", """8""": """resnets.3""", """9""": """attentions.3""", """10""": """resnets.4""", """11""": """attentions.4""", """12""": """resnets.5""", """13""": """attentions.5""", } __magic_name__ : Dict = { """0""": """resnets.0""", """1""": """resnets.1""", """2""": """resnets.2""", """4""": """resnets.0""", """5""": """resnets.1""", """6""": """resnets.2""", } __magic_name__ : Any = { """skip""": """conv_skip""", """main.0""": """conv_1""", """main.1""": """group_norm_1""", """main.3""": """conv_2""", """main.4""": """group_norm_2""", } __magic_name__ : Any = { """norm""": """group_norm""", """qkv_proj""": ["""query""", """key""", """value"""], """out_proj""": ["""proj_attn"""], } def UpperCamelCase (SCREAMING_SNAKE_CASE ): if name.startswith("""skip""" ): return name.replace("""skip""" , RES_CONV_MAP["""skip"""] ) # name has to be of format main.{digit} if not name.startswith("""main.""" ): raise ValueError(f"""ResConvBlock error with {name}""" ) return name.replace(name[:6] , RES_CONV_MAP[name[:6]] ) def UpperCamelCase (SCREAMING_SNAKE_CASE ): for key, value in ATTN_MAP.items(): if name.startswith(SCREAMING_SNAKE_CASE ) and not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return name.replace(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) elif name.startswith(SCREAMING_SNAKE_CASE ): return [name.replace(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for v in value] raise ValueError(f"""Attn error with {name}""" ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 ): UpperCamelCase : Optional[Any] = input_string if string.split(""".""" )[0] == "timestep_embed": return string.replace("""timestep_embed""" , """time_proj""" ) UpperCamelCase : int = 0 if string.startswith("""net.3.""" ): depth += 1 UpperCamelCase : List[str] = string[6:] elif string.startswith("""net.""" ): UpperCamelCase : List[Any] = string[4:] while string.startswith("""main.7.""" ): depth += 1 UpperCamelCase : List[Any] = string[7:] if string.startswith("""main.""" ): UpperCamelCase : Union[str, Any] = string[5:] # mid block if string[:2].isdigit(): UpperCamelCase : List[Any] = string[:2] UpperCamelCase : Optional[Any] = string[2:] else: UpperCamelCase : str = string[0] UpperCamelCase : int = string[1:] if depth == max_depth: UpperCamelCase : List[str] = MID_NUM_TO_LAYER[layer_num] UpperCamelCase : Optional[Any] = """mid_block""" elif depth > 0 and int(SCREAMING_SNAKE_CASE ) < 7: UpperCamelCase : List[str] = DOWN_NUM_TO_LAYER[layer_num] UpperCamelCase : Dict = f"""down_blocks.{depth}""" elif depth > 0 and int(SCREAMING_SNAKE_CASE ) > 7: UpperCamelCase : Any = UP_NUM_TO_LAYER[layer_num] UpperCamelCase : Optional[int] = f"""up_blocks.{max_depth - depth - 1}""" elif depth == 0: UpperCamelCase : str = DEPTH_0_TO_LAYER[layer_num] UpperCamelCase : int = f"""up_blocks.{max_depth - 1}""" if int(SCREAMING_SNAKE_CASE ) > 3 else """down_blocks.0""" if not string_left.startswith(""".""" ): raise ValueError(f"""Naming error with {input_string} and string_left: {string_left}.""" ) UpperCamelCase : Dict = string_left[1:] if "resnets" in new_layer: UpperCamelCase : Optional[Any] = convert_resconv_naming(SCREAMING_SNAKE_CASE ) elif "attentions" in new_layer: UpperCamelCase : Tuple = convert_attn_naming(SCREAMING_SNAKE_CASE ) UpperCamelCase : Union[str, Any] = new_string_left if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : Dict = prefix + """.""" + new_layer + """.""" + string_left else: UpperCamelCase : Tuple = [prefix + """.""" + new_layer + """.""" + s for s in string_left] return new_string def UpperCamelCase (SCREAMING_SNAKE_CASE ): UpperCamelCase : List[str] = {} for k, v in state_dict.items(): if k.endswith("""kernel""" ): # up- and downsample layers, don't have trainable weights continue UpperCamelCase : List[Any] = rename(SCREAMING_SNAKE_CASE ) # check if we need to transform from Conv => Linear for attention if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : Any = transform_conv_attns(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: UpperCamelCase : int = v return new_state_dict def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): if len(SCREAMING_SNAKE_CASE ) == 1: if len(v.shape ) == 3: # weight UpperCamelCase : Any = v[:, :, 0] else: # bias UpperCamelCase : List[str] = v else: # qkv matrices UpperCamelCase : Union[str, Any] = v.shape[0] UpperCamelCase : int = trippled_shape // 3 for i in range(3 ): if len(v.shape ) == 3: UpperCamelCase : Tuple = v[i * single_shape : (i + 1) * single_shape, :, 0] else: UpperCamelCase : str = v[i * single_shape : (i + 1) * single_shape] return new_state_dict def UpperCamelCase (SCREAMING_SNAKE_CASE ): UpperCamelCase : List[str] = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) UpperCamelCase : Any = args.model_path.split("""/""" )[-1].split(""".""" )[0] if not os.path.isfile(args.model_path ): assert ( model_name == args.model_path ), f"""Make sure to provide one of the official model names {MODELS_MAP.keys()}""" UpperCamelCase : Union[str, Any] = download(SCREAMING_SNAKE_CASE ) UpperCamelCase : Dict = MODELS_MAP[model_name]["""sample_rate"""] UpperCamelCase : Tuple = MODELS_MAP[model_name]["""sample_size"""] UpperCamelCase : List[str] = Object() UpperCamelCase : Union[str, Any] = sample_size UpperCamelCase : Dict = sample_rate UpperCamelCase : Any = 0 UpperCamelCase : int = UNetaDModel(sample_size=SCREAMING_SNAKE_CASE , sample_rate=SCREAMING_SNAKE_CASE ) UpperCamelCase : Any = diffusers_model.state_dict() UpperCamelCase : Optional[Any] = DiffusionUncond(SCREAMING_SNAKE_CASE ) orig_model.load_state_dict(torch.load(args.model_path , map_location=SCREAMING_SNAKE_CASE )["""state_dict"""] ) UpperCamelCase : Optional[Any] = orig_model.diffusion_ema.eval() UpperCamelCase : Optional[int] = orig_model.state_dict() UpperCamelCase : str = rename_orig_weights(SCREAMING_SNAKE_CASE ) UpperCamelCase : Optional[Any] = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() ) UpperCamelCase : Optional[Any] = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() ) assert len(SCREAMING_SNAKE_CASE ) == 0, f"""Problem with {renamed_minus_diffusers}""" assert all(k.endswith("""kernel""" ) for k in list(SCREAMING_SNAKE_CASE ) ), f"""Problem with {diffusers_minus_renamed}""" for key, value in renamed_state_dict.items(): assert ( diffusers_state_dict[key].squeeze().shape == value.squeeze().shape ), f"""Shape for {key} doesn't match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}""" if key == "time_proj.weight": UpperCamelCase : int = value.squeeze() UpperCamelCase : str = value diffusers_model.load_state_dict(SCREAMING_SNAKE_CASE ) UpperCamelCase : Optional[int] = 100 UpperCamelCase : List[Any] = 33 UpperCamelCase : Tuple = IPNDMScheduler(num_train_timesteps=SCREAMING_SNAKE_CASE ) UpperCamelCase : Optional[int] = torch.manual_seed(SCREAMING_SNAKE_CASE ) UpperCamelCase : List[str] = torch.randn([1, 2, config.sample_size] , generator=SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ) UpperCamelCase : str = torch.linspace(1 , 0 , steps + 1 , device=SCREAMING_SNAKE_CASE )[:-1] UpperCamelCase : Tuple = get_crash_schedule(SCREAMING_SNAKE_CASE ) UpperCamelCase : Union[str, Any] = DanceDiffusionPipeline(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) UpperCamelCase : Optional[Any] = torch.manual_seed(33 ) UpperCamelCase : Dict = pipe(num_inference_steps=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE ).audios UpperCamelCase : Optional[Any] = sampling.iplms_sample(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , {} ) UpperCamelCase : Any = generated.clamp(-1 , 1 ) UpperCamelCase : List[Any] = (generated - audio).abs().sum() UpperCamelCase : Optional[int] = (generated - audio).abs().max() if args.save: pipe.save_pretrained(args.checkpoint_path ) print("""Diff sum""" , SCREAMING_SNAKE_CASE ) print("""Diff max""" , SCREAMING_SNAKE_CASE ) assert diff_max < 1E-3, f"""Diff max: {diff_max} is too much :-/""" print(f"""Conversion for {model_name} successful!""" ) if __name__ == "__main__": __magic_name__ : Tuple = argparse.ArgumentParser() parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""") parser.add_argument( """--save""", default=True, type=bool, required=False, help="""Whether to save the converted model or not.""" ) parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""") __magic_name__ : List[str] = parser.parse_args() main(args)
102
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance _lowerCamelCase : Dict = 6_378_137.0 _lowerCamelCase : Union[str, Any] = 6_356_752.314_245 _lowerCamelCase : List[Any] = 6378137 def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> float: """simple docstring""" A__ = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude A__ = atan((1 - flattening) * tan(radians(lowercase_ ) ) ) A__ = atan((1 - flattening) * tan(radians(lowercase_ ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius A__ = haversine_distance(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) / EQUATORIAL_RADIUS # Intermediate P and Q values A__ = (b_lata + b_lata) / 2 A__ = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) A__ = (sin(lowercase_ ) ** 2) * (cos(lowercase_ ) ** 2) A__ = cos(sigma / 2 ) ** 2 A__ = (sigma - sin(lowercase_ )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) A__ = (cos(lowercase_ ) ** 2) * (sin(lowercase_ ) ** 2) A__ = sin(sigma / 2 ) ** 2 A__ = (sigma + sin(lowercase_ )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
87
0
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel snake_case = logging.getLogger(__name__) def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Optional[Any]: # save results if os.path.exists(lowerCAmelCase_ ): if os.path.exists(os.path.join(lowerCAmelCase_ , '''config.json''' ) ) and os.path.isfile( os.path.join(lowerCAmelCase_ , '''config.json''' ) ): os.remove(os.path.join(lowerCAmelCase_ , '''config.json''' ) ) if os.path.exists(os.path.join(lowerCAmelCase_ , '''pytorch_model.bin''' ) ) and os.path.isfile( os.path.join(lowerCAmelCase_ , '''pytorch_model.bin''' ) ): os.remove(os.path.join(lowerCAmelCase_ , '''pytorch_model.bin''' ) ) else: os.makedirs(lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) def snake_case ( lowerCAmelCase_ , lowerCAmelCase_=False ) -> Union[str, Any]: _snake_case = 2 if unlogit: _snake_case = torch.pow(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = p * torch.log(lowerCAmelCase_ ) _snake_case = 0 return -plogp.sum(dim=-1 ) def snake_case ( lowerCAmelCase_ ) -> List[Any]: logger.info('''lv, h >\t''' + '''\t'''.join(f"""{x + 1}""" for x in range(len(lowerCAmelCase_ ) ) ) ) for row in range(len(lowerCAmelCase_ ) ): if tensor.dtype != torch.long: logger.info(f"""layer {row + 1}:\t""" + '''\t'''.join(f"""{x:.5f}""" for x in tensor[row].cpu().data ) ) else: logger.info(f"""layer {row + 1}:\t""" + '''\t'''.join(f"""{x:d}""" for x in tensor[row].cpu().data ) ) def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=None , lowerCAmelCase_=False ) -> List[str]: _snake_case , _snake_case = model.config.num_hidden_layers, model.config.num_attention_heads _snake_case = torch.zeros(lowerCAmelCase_ , lowerCAmelCase_ ).to(args.device ) _snake_case = torch.zeros(lowerCAmelCase_ , lowerCAmelCase_ ).to(args.device ) if head_mask is None: _snake_case = torch.ones(lowerCAmelCase_ , lowerCAmelCase_ ).to(args.device ) head_mask.requires_grad_(requires_grad=lowerCAmelCase_ ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: _snake_case = None _snake_case = 0.0 _snake_case = 0.0 for step, inputs in enumerate(tqdm(lowerCAmelCase_ , desc='''Iteration''' , disable=args.local_rank not in [-1, 0] ) ): _snake_case = tuple(t.to(args.device ) for t in inputs ) ((_snake_case) , ) = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) _snake_case = model(lowerCAmelCase_ , labels=lowerCAmelCase_ , head_mask=lowerCAmelCase_ ) # (loss), lm_logits, presents, (all hidden_states), (attentions) _snake_case , _snake_case , _snake_case = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(lowerCAmelCase_ ): _snake_case = entropy(attn.detach() , lowerCAmelCase_ ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(lowerCAmelCase_ ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: _snake_case = 2 _snake_case = torch.pow(torch.pow(lowerCAmelCase_ , lowerCAmelCase_ ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1E-20 if not args.dont_normalize_global_importance: _snake_case = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('''Attention entropies''' ) print_ad_tensor(lowerCAmelCase_ ) if compute_importance: logger.info('''Head importance scores''' ) print_ad_tensor(lowerCAmelCase_ ) logger.info('''Head ranked by importance scores''' ) _snake_case = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) _snake_case = torch.arange( head_importance.numel() , device=args.device ) _snake_case = head_ranks.view_as(lowerCAmelCase_ ) print_ad_tensor(lowerCAmelCase_ ) return attn_entropy, head_importance, total_loss def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> List[Any]: _snake_case , _snake_case , _snake_case = compute_heads_importance(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , compute_entropy=lowerCAmelCase_ ) _snake_case = 1 / loss # instead of downsteam score use the LM loss logger.info('''Pruning: original score: %f, threshold: %f''' , lowerCAmelCase_ , original_score * args.masking_threshold ) _snake_case = torch.ones_like(lowerCAmelCase_ ) _snake_case = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) _snake_case = original_score while current_score >= original_score * args.masking_threshold: _snake_case = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads _snake_case = float('''Inf''' ) _snake_case = head_importance.view(-1 ).sort()[1] if len(lowerCAmelCase_ ) <= num_to_mask: print('''BREAK BY num_to_mask''' ) break # mask heads _snake_case = current_heads_to_mask[:num_to_mask] logger.info('''Heads to mask: %s''' , str(current_heads_to_mask.tolist() ) ) _snake_case = new_head_mask.view(-1 ) _snake_case = 0.0 _snake_case = new_head_mask.view_as(lowerCAmelCase_ ) _snake_case = new_head_mask.clone().detach() print_ad_tensor(lowerCAmelCase_ ) # Compute metric and head importance again _snake_case , _snake_case , _snake_case = compute_heads_importance( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , compute_entropy=lowerCAmelCase_ , head_mask=lowerCAmelCase_ ) _snake_case = 1 / loss logger.info( '''Masking: current score: %f, remaining heads %d (%.1f percents)''' , lowerCAmelCase_ , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('''Final head mask''' ) print_ad_tensor(lowerCAmelCase_ ) np.save(os.path.join(args.output_dir , '''head_mask.npy''' ) , head_mask.detach().cpu().numpy() ) return head_mask def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> List[str]: _snake_case = datetime.now() _snake_case , _snake_case , _snake_case = compute_heads_importance( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , compute_entropy=lowerCAmelCase_ , compute_importance=lowerCAmelCase_ , head_mask=lowerCAmelCase_ ) _snake_case = 1 / loss _snake_case = datetime.now() - before_time _snake_case = sum(p.numel() for p in model.parameters() ) _snake_case = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowerCAmelCase_ ) ) } for k, v in heads_to_prune.items(): if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _snake_case = [ v, ] assert sum(len(lowerCAmelCase_ ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(lowerCAmelCase_ ) _snake_case = sum(p.numel() for p in model.parameters() ) _snake_case = datetime.now() _snake_case , _snake_case , _snake_case = compute_heads_importance( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , compute_entropy=lowerCAmelCase_ , compute_importance=lowerCAmelCase_ , head_mask=lowerCAmelCase_ , actually_pruned=lowerCAmelCase_ , ) _snake_case = 1 / loss _snake_case = datetime.now() - before_time logger.info( '''Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)''' , lowerCAmelCase_ , lowerCAmelCase_ , pruned_num_params / original_num_params * 100 , ) logger.info('''Pruning: score with masking: %f score with pruning: %f''' , lowerCAmelCase_ , lowerCAmelCase_ ) logger.info('''Pruning: speed ratio (original timing / new timing): %f percents''' , original_time / new_time * 100 ) save_model(lowerCAmelCase_ , args.output_dir ) def snake_case ( ) -> Dict: _snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--data_dir''' , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help='''The input data dir. Should contain the .tsv files (or other data files) for the task.''' , ) parser.add_argument( '''--model_name_or_path''' , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help='''Path to pretrained model or model identifier from huggingface.co/models''' , ) parser.add_argument( '''--output_dir''' , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help='''The output directory where the model predictions and checkpoints will be written.''' , ) # Other parameters parser.add_argument( '''--config_name''' , default='''''' , type=lowerCAmelCase_ , help='''Pretrained config name or path if not the same as model_name_or_path''' , ) parser.add_argument( '''--tokenizer_name''' , default='''''' , type=lowerCAmelCase_ , help='''Pretrained tokenizer name or path if not the same as model_name_or_path''' , ) parser.add_argument( '''--cache_dir''' , default=lowerCAmelCase_ , type=lowerCAmelCase_ , help='''Where do you want to store the pre-trained models downloaded from s3''' , ) parser.add_argument( '''--data_subset''' , type=lowerCAmelCase_ , default=-1 , help='''If > 0: limit the data to a subset of data_subset instances.''' ) parser.add_argument( '''--overwrite_output_dir''' , action='''store_true''' , help='''Whether to overwrite data in output directory''' ) parser.add_argument( '''--overwrite_cache''' , action='''store_true''' , help='''Overwrite the cached training and evaluation sets''' ) parser.add_argument( '''--dont_normalize_importance_by_layer''' , action='''store_true''' , help='''Don\'t normalize importance score by layers''' ) parser.add_argument( '''--dont_normalize_global_importance''' , action='''store_true''' , help='''Don\'t normalize all importance scores between 0 and 1''' , ) parser.add_argument( '''--try_masking''' , action='''store_true''' , help='''Whether to try to mask head until a threshold of accuracy.''' ) parser.add_argument( '''--masking_threshold''' , default=0.9 , type=lowerCAmelCase_ , help='''masking threshold in term of metrics (stop masking when metric < threshold * original metric value).''' , ) parser.add_argument( '''--masking_amount''' , default=0.1 , type=lowerCAmelCase_ , help='''Amount to heads to masking at each masking step.''' ) parser.add_argument('''--metric_name''' , default='''acc''' , type=lowerCAmelCase_ , help='''Metric to use for head masking.''' ) parser.add_argument( '''--max_seq_length''' , default=128 , type=lowerCAmelCase_ , help=( '''The maximum total input sequence length after WordPiece tokenization. \n''' '''Sequences longer than this will be truncated, sequences shorter padded.''' ) , ) parser.add_argument('''--batch_size''' , default=1 , type=lowerCAmelCase_ , help='''Batch size.''' ) parser.add_argument('''--seed''' , type=lowerCAmelCase_ , default=42 ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase_ , default=-1 , help='''local_rank for distributed training on gpus''' ) parser.add_argument('''--no_cuda''' , action='''store_true''' , help='''Whether not to use CUDA when available''' ) parser.add_argument('''--server_ip''' , type=lowerCAmelCase_ , default='''''' , help='''Can be used for distant debugging.''' ) parser.add_argument('''--server_port''' , type=lowerCAmelCase_ , default='''''' , help='''Can be used for distant debugging.''' ) _snake_case = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('''Waiting for debugger attach''' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=lowerCAmelCase_ ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: _snake_case = torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu''' ) _snake_case = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) _snake_case = torch.device('''cuda''' , args.local_rank ) _snake_case = 1 torch.distributed.init_process_group(backend='''nccl''' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('''device: {} n_gpu: {}, distributed: {}'''.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) _snake_case = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: _snake_case = nn.parallel.DistributedDataParallel( lowerCAmelCase_ , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=lowerCAmelCase_ ) elif args.n_gpu > 1: _snake_case = nn.DataParallel(lowerCAmelCase_ ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=lowerCAmelCase_ ) torch.save(lowerCAmelCase_ , os.path.join(args.output_dir , '''run_args.bin''' ) ) logger.info('''Training/evaluation parameters %s''' , lowerCAmelCase_ ) # Prepare dataset _snake_case = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) _snake_case = (torch.from_numpy(lowerCAmelCase_ ),) _snake_case = TensorDataset(*lowerCAmelCase_ ) _snake_case = RandomSampler(lowerCAmelCase_ ) _snake_case = DataLoader(lowerCAmelCase_ , sampler=lowerCAmelCase_ , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: _snake_case = mask_heads(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) prune_heads(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
103
import heapq import sys import numpy as np _lowerCamelCase : Any = tuple[int, int] class UpperCamelCase_ : '''simple docstring''' def __init__( self : Any) ->str: '''simple docstring''' A__ = [] A__ = set() def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' if not self.empty(): return self.elements[0][0] else: return float('''inf''') def SCREAMING_SNAKE_CASE ( self : Tuple) ->str: '''simple docstring''' return len(self.elements) == 0 def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any]) ->List[str]: '''simple docstring''' if item not in self.set: heapq.heappush(self.elements , (priority, item)) self.set.add(UpperCAmelCase__) else: # update # print("update", item) A__ = [] ((A__) , (A__)) = heapq.heappop(self.elements) while x != item: temp.append((pri, x)) ((A__) , (A__)) = heapq.heappop(self.elements) temp.append((priority, item)) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx)) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : List[Any]) ->Union[str, Any]: '''simple docstring''' if item in self.set: self.set.remove(UpperCAmelCase__) A__ = [] ((A__) , (A__)) = heapq.heappop(self.elements) while x != item: temp.append((pro, x)) ((A__) , (A__)) = heapq.heappop(self.elements) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy)) def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[str]: '''simple docstring''' return self.elements[0][1] def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->int: '''simple docstring''' ((A__) , (A__)) = heapq.heappop(self.elements) self.set.remove(UpperCAmelCase__) return (priority, item) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = np.array(lowercase_ ) A__ = np.array(lowercase_ ) return np.linalg.norm(a - b ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" return consistent_heuristic(lowercase_ , lowercase_ ) // t def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Union[str, Any]: """simple docstring""" return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> Optional[int]: """simple docstring""" A__ = g_function[start] + Wa * heuristics[i](lowercase_ , lowercase_ ) return ans def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = np.chararray((n, n) ) for i in range(lowercase_ ): for j in range(lowercase_ ): A__ = '''*''' for i in range(lowercase_ ): for j in range(lowercase_ ): if (j, (n - 1) - i) in blocks: A__ = '''#''' A__ = '''-''' A__ = back_pointer[goal] while x != start: ((A__) , (A__)) = x # print(x) A__ = '''-''' A__ = back_pointer[x] A__ = '''-''' for i in range(lowercase_ ): for j in range(lowercase_ ): if (i, j) == (0, n - 1): print(grid[i][j] , end=''' ''' ) print('''<-- End position''' , end=''' ''' ) else: print(grid[i][j] , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) print('''PATH TAKEN BY THE ALGORITHM IS:-''' ) A__ = back_pointer[goal] while x != start: print(lowercase_ , end=''' ''' ) A__ = back_pointer[x] print(lowercase_ ) sys.exit() def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) -> Union[str, Any]: """simple docstring""" for itera in range(lowercase_ ): open_list[itera].remove_element(lowercase_ ) # print("s", s) # print("j", j) ((A__) , (A__)) = s A__ = (x - 1, y) A__ = (x + 1, y) A__ = (x, y + 1) A__ = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(lowercase_ ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(lowercase_ ) A__ = -1 A__ = float('''inf''' ) if valid(lowercase_ ) and g_function[neighbours] > g_function[s] + 1: A__ = g_function[s] + 1 A__ = s if neighbours not in close_list_anchor: open_list[0].put(lowercase_ , key(lowercase_ , 0 , lowercase_ , lowercase_ ) ) if neighbours not in close_list_inad: for var in range(1 , lowercase_ ): if key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) <= Wa * key( lowercase_ , 0 , lowercase_ , lowercase_ ): open_list[j].put( lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) def SCREAMING_SNAKE_CASE ( ) -> Optional[int]: """simple docstring""" A__ = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list _lowerCamelCase : Dict = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} _lowerCamelCase : Optional[Any] = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] _lowerCamelCase : Optional[int] = make_common_ground() _lowerCamelCase : Optional[Any] = blocks_blk # hyper parameters _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : List[Any] = 20 _lowerCamelCase : Any = 3 # one consistent and two other inconsistent # start and end destination _lowerCamelCase : str = (0, 0) _lowerCamelCase : Tuple = (n - 1, n - 1) _lowerCamelCase : int = 1 def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = {start: 0, goal: float('''inf''' )} A__ = {start: -1, goal: -1} A__ = [] A__ = set() for i in range(lowercase_ ): open_list.append(PriorityQueue() ) open_list[i].put(lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) A__ = [] A__ = [] while open_list[0].minkey() < float('''inf''' ): for i in range(1 , lowercase_ ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float('''inf''' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: A__ , A__ = open_list[i].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_inad.append(lowercase_ ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('''inf''' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: A__ = open_list[0].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , 0 , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_anchor.append(lowercase_ ) print('''No path found to goal''' ) print() for i in range(n - 1 , -1 , -1 ): for j in range(lowercase_ ): if (j, i) in blocks: print('''#''' , end=''' ''' ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print('''*''' , end=''' ''' ) else: print('''-''' , end=''' ''' ) else: print('''*''' , end=''' ''' ) if (j, i) == (n - 1, n - 1): print('''<-- End position''' , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
87
0
"""simple docstring""" import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging UpperCamelCase = """\ """ UpperCamelCase = """ Perplexity (PPL) is one of the most common metrics for evaluating language models. It is defined as the exponentiated average negative log-likelihood of a sequence. For more information, see https://huggingface.co/docs/transformers/perplexity """ UpperCamelCase = """ Args: model_id (str): model used for calculating Perplexity NOTE: Perplexity can only be calculated for causal language models. This includes models such as gpt2, causal variations of bert, causal versions of t5, and more (the full list can be found in the AutoModelForCausalLM documentation here: https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM ) input_texts (list of str): input text, each separate text snippet is one list entry. batch_size (int): the batch size to run texts through the model. Defaults to 16. add_start_token (bool): whether to add the start token to the texts, so the perplexity can include the probability of the first word. Defaults to True. device (str): device to run on, defaults to 'cuda' when available Returns: perplexity: dictionary containing the perplexity scores for the texts in the input list, as well as the mean perplexity. If one of the input texts is longer than the max input length of the model, then it is truncated to the max length for the perplexity computation. Examples: Example 1: >>> perplexity = datasets.load_metric(\"perplexity\") >>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"] >>> results = perplexity.compute(model_id='gpt2', ... add_start_token=False, ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) ['perplexities', 'mean_perplexity'] >>> print(round(results[\"mean_perplexity\"], 2)) 78.22 >>> print(round(results[\"perplexities\"][0], 2)) 11.11 Example 2: >>> perplexity = datasets.load_metric(\"perplexity\") >>> input_texts = datasets.load_dataset(\"wikitext\", ... \"wikitext-2-raw-v1\", ... split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS [...] >>> input_texts = [s for s in input_texts if s!=''] >>> results = perplexity.compute(model_id='gpt2', ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) ['perplexities', 'mean_perplexity'] >>> print(round(results[\"mean_perplexity\"], 2)) 60.35 >>> print(round(results[\"perplexities\"][0], 2)) 81.12 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase__ ( datasets.Metric ): """simple docstring""" def snake_case__ ( self ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "input_texts": datasets.Value("string" ), } ) , reference_urls=["https://huggingface.co/docs/transformers/perplexity"] , ) def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 16 , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__=None ) -> List[str]: if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": A__ = "cuda" else: A__ = "cuda" if torch.cuda.is_available() else "cpu" A__ = AutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ ) A__ = model.to(SCREAMING_SNAKE_CASE__ ) A__ = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: A__ = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(SCREAMING_SNAKE_CASE__ ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" A__ = model.config.max_length - 1 else: A__ = model.config.max_length A__ = tokenizer( SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , return_tensors="pt" , return_attention_mask=SCREAMING_SNAKE_CASE__ , ).to(SCREAMING_SNAKE_CASE__ ) A__ = encodings["input_ids"] A__ = encodings["attention_mask"] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." A__ = [] A__ = CrossEntropyLoss(reduction="none" ) for start_index in logging.tqdm(range(0 , len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) ): A__ = min(start_index + batch_size , len(SCREAMING_SNAKE_CASE__ ) ) A__ = encoded_texts[start_index:end_index] A__ = attn_masks[start_index:end_index] if add_start_token: A__ = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(SCREAMING_SNAKE_CASE__ ) A__ = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) A__ = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(SCREAMING_SNAKE_CASE__ ), attn_mask] , dim=1 ) A__ = encoded_batch with torch.no_grad(): A__ = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ).logits A__ = out_logits[..., :-1, :].contiguous() A__ = labels[..., 1:].contiguous() A__ = attn_mask[..., 1:].contiguous() A__ = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , SCREAMING_SNAKE_CASE__ ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(SCREAMING_SNAKE_CASE__ )}
104
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowerCamelCase : Optional[Any] = """Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine""" def SCREAMING_SNAKE_CASE ( ) -> Dict: """simple docstring""" A__ = _ask_options( '''In which compute environment are you running?''' , ['''This machine''', '''AWS (Amazon SageMaker)'''] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A__ = get_sagemaker_input() else: A__ = get_cluster_input() return config def SCREAMING_SNAKE_CASE ( lowercase_=None ) -> List[Any]: """simple docstring""" if subparsers is not None: A__ = subparsers.add_parser('''config''' , description=lowercase_ ) else: A__ = argparse.ArgumentParser('''Accelerate config command''' , description=lowercase_ ) parser.add_argument( '''--config_file''' , default=lowercase_ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=lowercase_ ) return parser def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Any: """simple docstring""" A__ = get_user_input() if args.config_file is not None: A__ = args.config_file else: if not os.path.isdir(lowercase_ ): os.makedirs(lowercase_ ) A__ = default_yaml_config_file if config_file.endswith('''.json''' ): config.to_json_file(lowercase_ ) else: config.to_yaml_file(lowercase_ ) print(f"""accelerate configuration saved at {config_file}""" ) def SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: """simple docstring""" A__ = config_command_parser() A__ = parser.parse_args() config_command(lowercase_ ) if __name__ == "__main__": main()
87
0
from math import pow def __UpperCAmelCase ( lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : int , ) -> tuple[int, int]: """simple docstring""" if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count SCREAMING_SNAKE_CASE_ : List[Any] = int(pow(lowerCamelCase_ , lowerCamelCase_ ) ) if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = backtrack( lowerCamelCase_ , lowerCamelCase_ , current_number + 1 , lowerCamelCase_ , lowerCamelCase_ ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = backtrack( lowerCamelCase_ , lowerCamelCase_ , current_number + 1 , lowerCamelCase_ , lowerCamelCase_ ) return current_sum, solutions_count def __UpperCAmelCase ( lowerCamelCase_ : int , lowerCamelCase_ : int ) -> int: """simple docstring""" if not (1 <= needed_sum <= 10_00 and 2 <= power <= 10): raise ValueError( 'Invalid input\n' 'needed_sum must be between 1 and 1000, power between 2 and 10.' ) return backtrack(lowerCamelCase_ , lowerCamelCase_ , 1 , 0 , 0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
105
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _lowerCamelCase : int = logging.get_logger("""transformers.models.speecht5""") def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Tuple: """simple docstring""" hf_model.apply_weight_norm() A__ = checkpoint['''input_conv.weight_g'''] A__ = checkpoint['''input_conv.weight_v'''] A__ = checkpoint['''input_conv.bias'''] for i in range(len(config.upsample_rates ) ): A__ = checkpoint[f"""upsamples.{i}.1.weight_g"""] A__ = checkpoint[f"""upsamples.{i}.1.weight_v"""] A__ = checkpoint[f"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_g"""] A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_v"""] A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.bias"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_g"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_v"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.bias"""] A__ = checkpoint['''output_conv.1.weight_g'''] A__ = checkpoint['''output_conv.1.weight_v'''] A__ = checkpoint['''output_conv.1.bias'''] hf_model.remove_weight_norm() @torch.no_grad() def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , ) -> str: """simple docstring""" if config_path is not None: A__ = SpeechTaHifiGanConfig.from_pretrained(lowercase_ ) else: A__ = SpeechTaHifiGanConfig() A__ = SpeechTaHifiGan(lowercase_ ) A__ = torch.load(lowercase_ ) load_weights(orig_checkpoint['''model''']['''generator'''] , lowercase_ , lowercase_ ) A__ = np.load(lowercase_ ) A__ = stats[0].reshape(-1 ) A__ = stats[1].reshape(-1 ) A__ = torch.from_numpy(lowercase_ ).float() A__ = torch.from_numpy(lowercase_ ).float() model.save_pretrained(lowercase_ ) if repo_id: print('''Pushing to the hub...''' ) model.push_to_hub(lowercase_ ) if __name__ == "__main__": _lowerCamelCase : Any = argparse.ArgumentParser() parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--stats_path""", required=True, default=None, type=str, help="""Path to stats.npy file""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) _lowerCamelCase : List[str] = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
87
0
import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : def __init__( self : Optional[int] , __UpperCamelCase : Optional[int] , __UpperCamelCase : int=13 , __UpperCamelCase : List[Any]=7 , __UpperCamelCase : Any=True , __UpperCamelCase : Tuple=True , __UpperCamelCase : int=True , __UpperCamelCase : List[Any]=True , __UpperCamelCase : Optional[int]=99 , __UpperCamelCase : str=32 , __UpperCamelCase : Tuple=5 , __UpperCamelCase : str=4 , __UpperCamelCase : Any=37 , __UpperCamelCase : Tuple="gelu" , __UpperCamelCase : Optional[int]=0.1 , __UpperCamelCase : str=0.1 , __UpperCamelCase : Optional[Any]=512 , __UpperCamelCase : List[str]=16 , __UpperCamelCase : str=2 , __UpperCamelCase : Dict=0.0_2 , __UpperCamelCase : Optional[Any]=3 , __UpperCamelCase : int=4 , __UpperCamelCase : Any=None , ) -> List[Any]: A = parent A = batch_size A = seq_length A = is_training A = use_input_mask A = use_token_type_ids A = use_labels A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = scope def __UpperCamelCase ( self : int ) -> int: A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A = ids_tensor([self.batch_size] , self.num_choices ) A = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase ( self : Optional[int] ) -> Any: return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__UpperCamelCase , initializer_range=self.initializer_range , ) def __UpperCamelCase ( self : Any , __UpperCamelCase : Any , __UpperCamelCase : List[str] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : str , __UpperCamelCase : Optional[int] , __UpperCamelCase : Optional[Any] ) -> str: A = NystromformerModel(config=__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() A = model(__UpperCamelCase , attention_mask=__UpperCamelCase , token_type_ids=__UpperCamelCase ) A = model(__UpperCamelCase , token_type_ids=__UpperCamelCase ) A = model(__UpperCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self : List[Any] , __UpperCamelCase : List[Any] , __UpperCamelCase : Dict , __UpperCamelCase : Optional[int] , __UpperCamelCase : List[str] , __UpperCamelCase : int , __UpperCamelCase : List[Any] , __UpperCamelCase : Union[str, Any] ) -> Optional[Any]: A = NystromformerForMaskedLM(config=__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() A = model(__UpperCamelCase , attention_mask=__UpperCamelCase , token_type_ids=__UpperCamelCase , labels=__UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase ( self : int , __UpperCamelCase : str , __UpperCamelCase : Tuple , __UpperCamelCase : Dict , __UpperCamelCase : str , __UpperCamelCase : Any , __UpperCamelCase : int , __UpperCamelCase : Dict ) -> Optional[int]: A = NystromformerForQuestionAnswering(config=__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() A = model( __UpperCamelCase , attention_mask=__UpperCamelCase , token_type_ids=__UpperCamelCase , start_positions=__UpperCamelCase , end_positions=__UpperCamelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase ( self : Any , __UpperCamelCase : Any , __UpperCamelCase : Any , __UpperCamelCase : Optional[Any] , __UpperCamelCase : List[str] , __UpperCamelCase : List[Any] , __UpperCamelCase : Optional[int] , __UpperCamelCase : str ) -> Tuple: A = self.num_labels A = NystromformerForSequenceClassification(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() A = model(__UpperCamelCase , attention_mask=__UpperCamelCase , token_type_ids=__UpperCamelCase , labels=__UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase ( self : List[Any] , __UpperCamelCase : str , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Dict , __UpperCamelCase : Optional[int] , __UpperCamelCase : List[Any] , __UpperCamelCase : Optional[int] , __UpperCamelCase : List[str] ) -> Dict: A = self.num_labels A = NystromformerForTokenClassification(config=__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() A = model(__UpperCamelCase , attention_mask=__UpperCamelCase , token_type_ids=__UpperCamelCase , labels=__UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase ( self : Union[str, Any] , __UpperCamelCase : List[str] , __UpperCamelCase : Tuple , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : str , __UpperCamelCase : List[str] ) -> str: A = self.num_choices A = NystromformerForMultipleChoice(config=__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A = model( __UpperCamelCase , attention_mask=__UpperCamelCase , token_type_ids=__UpperCamelCase , labels=__UpperCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase ( self : Tuple ) -> str: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase ): A_ : Optional[Any] = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) A_ : Optional[Any] = ( { 'feature-extraction': NystromformerModel, 'fill-mask': NystromformerForMaskedLM, 'question-answering': NystromformerForQuestionAnswering, 'text-classification': NystromformerForSequenceClassification, 'token-classification': NystromformerForTokenClassification, 'zero-shot': NystromformerForSequenceClassification, } if is_torch_available() else {} ) A_ : Dict = False A_ : int = False def __UpperCamelCase ( self : Dict ) -> int: A = NystromformerModelTester(self ) A = ConfigTester(self , config_class=__UpperCamelCase , hidden_size=37 ) def __UpperCamelCase ( self : List[Any] ) -> Tuple: self.config_tester.run_common_tests() def __UpperCamelCase ( self : Tuple ) -> str: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCamelCase ) def __UpperCamelCase ( self : str ) -> Any: A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A = type self.model_tester.create_and_check_model(*__UpperCamelCase ) def __UpperCamelCase ( self : Optional[Any] ) -> Dict: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__UpperCamelCase ) def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__UpperCamelCase ) def __UpperCamelCase ( self : Dict ) -> List[str]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__UpperCamelCase ) def __UpperCamelCase ( self : Tuple ) -> str: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__UpperCamelCase ) def __UpperCamelCase ( self : List[str] ) -> Optional[int]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__UpperCamelCase ) @slow def __UpperCamelCase ( self : int ) -> Optional[int]: for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = NystromformerModel.from_pretrained(__UpperCamelCase ) self.assertIsNotNone(__UpperCamelCase ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): @slow def __UpperCamelCase ( self : int ) -> Dict: A = NystromformerModel.from_pretrained('uw-madison/nystromformer-512' ) A = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): A = model(__UpperCamelCase )[0] A = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , __UpperCamelCase ) A = torch.tensor( [[[-0.4_5_3_2, -0.0_9_3_6, 0.5_1_3_7], [-0.2_6_7_6, 0.0_6_2_8, 0.6_1_8_6], [-0.3_6_2_9, -0.1_7_2_6, 0.4_7_1_6]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __UpperCamelCase , atol=1e-4 ) ) @slow def __UpperCamelCase ( self : List[Any] ) -> int: A = 'the [MASK] of Belgium is Brussels' A = AutoTokenizer.from_pretrained('uw-madison/nystromformer-512' ) A = NystromformerForMaskedLM.from_pretrained('uw-madison/nystromformer-512' ) A = tokenizer(__UpperCamelCase , return_tensors='pt' ) with torch.no_grad(): A = model(encoding.input_ids ).logits A = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(__UpperCamelCase ) , 'capital' )
106
import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class UpperCamelCase_ : '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict=13 , UpperCAmelCase__ : Dict=7 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=99 , UpperCAmelCase__ : Union[str, Any]=32 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : List[Any]=37 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=50 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : List[str]=None , ) ->Union[str, Any]: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = initializer_range A__ = use_labels A__ = scope def SCREAMING_SNAKE_CASE ( self : int) ->Any: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) if self.use_labels: A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = self.get_config() return config, input_ids, input_mask, token_labels def SCREAMING_SNAKE_CASE ( self : int) ->int: '''simple docstring''' return BertGenerationConfig( 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 , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Union[str, Any]: '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = self.prepare_config_and_inputs() A__ = True A__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) A__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , **UpperCAmelCase__ : List[Any] , ) ->Dict: '''simple docstring''' A__ = BertGenerationEncoder(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__) A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[Any] , ) ->Dict: '''simple docstring''' A__ = True A__ = BertGenerationEncoder(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Optional[int] , ) ->Any: '''simple docstring''' A__ = True A__ = True A__ = BertGenerationDecoder(config=UpperCAmelCase__).to(UpperCAmelCase__).eval() # first forward pass A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ , ) A__ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size) A__ = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and A__ = torch.cat([input_ids, next_tokens] , dim=-1) A__ = torch.cat([input_mask, next_mask] , dim=-1) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] # select random slice A__ = ids_tensor((1,) , output_from_past.shape[-1]).item() A__ = output_from_no_past[:, -3:, random_slice_idx].detach() A__ = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3)) def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , *UpperCAmelCase__ : List[str] , ) ->List[Any]: '''simple docstring''' A__ = BertGenerationDecoder(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->List[str]: '''simple docstring''' A__ , A__ , A__ , A__ = self.prepare_config_and_inputs() A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () UpperCAmelCase__ = (BertGenerationDecoder,) if is_torch_available() else () UpperCAmelCase__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Dict: '''simple docstring''' A__ = BertGenerationEncoderTester(self) A__ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any]) ->int: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Optional[Any]: '''simple docstring''' A__ , A__ , A__ , A__ = self.model_tester.prepare_config_and_inputs() A__ = '''bert''' self.model_tester.create_and_check_model(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any: '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() A__ = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*UpperCAmelCase__) @slow def SCREAMING_SNAKE_CASE ( self : Dict) ->List[Any]: '''simple docstring''' A__ = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') self.assertIsNotNone(UpperCAmelCase__) @require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Any) ->Union[str, Any]: '''simple docstring''' A__ = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') A__ = torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]) with torch.no_grad(): A__ = model(UpperCAmelCase__)[0] A__ = torch.Size([1, 8, 1_024]) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4)) @require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' A__ = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') A__ = torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]) with torch.no_grad(): A__ = model(UpperCAmelCase__)[0] A__ = torch.Size([1, 8, 50_358]) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4))
87
0
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. _UpperCAmelCase : Any = 10 def _SCREAMING_SNAKE_CASE ( __snake_case : int , __snake_case : int , __snake_case : list[int] , __snake_case : int ): for i in range(__snake_case , __snake_case ): if array[i] == target: return i return -1 def _SCREAMING_SNAKE_CASE ( __snake_case : list[int] , __snake_case : int ): _A = 0 _A = len(__snake_case ) while left <= right: if right - left < precision: return lin_search(__snake_case , __snake_case , __snake_case , __snake_case ) _A = (left + right) // 3 + 1 _A = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: _A = one_third - 1 elif array[two_third] < target: _A = two_third + 1 else: _A = one_third + 1 _A = two_third - 1 else: return -1 def _SCREAMING_SNAKE_CASE ( __snake_case : int , __snake_case : int , __snake_case : list[int] , __snake_case : int ): if left < right: if right - left < precision: return lin_search(__snake_case , __snake_case , __snake_case , __snake_case ) _A = (left + right) // 3 + 1 _A = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(__snake_case , one_third - 1 , __snake_case , __snake_case ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , __snake_case , __snake_case , __snake_case ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , __snake_case , __snake_case ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase : int = input('''Enter numbers separated by comma:\n''').strip() _UpperCAmelCase : List[Any] = [int(item.strip()) for item in user_input.split(''',''')] assert collection == sorted(collection), F"List must be ordered.\n{collection}." _UpperCAmelCase : Tuple = int(input('''Enter the number to be found in the list:\n''').strip()) _UpperCAmelCase : str = ite_ternary_search(collection, target) _UpperCAmelCase : List[str] = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(F'''Iterative search: {target} found at positions: {resulta}''') print(F'''Recursive search: {target} found at positions: {resulta}''') else: print('''Not found''')
107
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 _lowerCamelCase : int = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Dict: """simple docstring""" A__ = set() A__ = [] def parse_line(lowercase_ ): for line in fp: if isinstance(lowercase_ , lowercase_ ): A__ = 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(lowercase_ ) > 0: A__ = '''\n'''.join(lowercase_ ) # Only keep the warnings specified in `targets` if any(f""": {x}: """ in warning for x in targets ): selected_warnings.add(lowercase_ ) buffer.clear() continue else: A__ = line.strip() buffer.append(lowercase_ ) if from_gh: for filename in os.listdir(lowercase_ ): A__ = os.path.join(lowercase_ , lowercase_ ) if not os.path.isdir(lowercase_ ): # read the file if filename != "warnings.txt": continue with open(lowercase_ ) as fp: parse_line(lowercase_ ) else: try: with zipfile.ZipFile(lowercase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowercase_ ): # read the file if filename != "warnings.txt": continue with z.open(lowercase_ ) as fp: parse_line(lowercase_ ) 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 SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = set() A__ = [os.path.join(lowercase_ , lowercase_ ) for p in os.listdir(lowercase_ ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(lowercase_ , lowercase_ ) ) return selected_warnings if __name__ == "__main__": def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" return values.split(''',''' ) _lowerCamelCase : int = 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.""", ) _lowerCamelCase : List[Any] = parser.parse_args() _lowerCamelCase : List[str] = 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 _lowerCamelCase : 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("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts _lowerCamelCase : Any = extract_warnings(args.output_dir, args.targets) _lowerCamelCase : Optional[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)
87
0
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase = AutoencoderKL _lowerCamelCase = '''sample''' _lowerCamelCase = 1E-2 @property def lowerCamelCase ( self : str ) -> Tuple: """simple docstring""" _UpperCAmelCase = 4 _UpperCAmelCase = 3 _UpperCAmelCase = (32, 32) _UpperCAmelCase = floats_tensor((batch_size, num_channels) + sizes ).to(lowerCamelCase ) return {"sample": image} @property def lowerCamelCase ( self : Optional[Any] ) -> List[str]: """simple docstring""" return (3, 32, 32) @property def lowerCamelCase ( self : List[Any] ) -> Tuple: """simple docstring""" return (3, 32, 32) def lowerCamelCase ( self : Optional[Any] ) -> Any: """simple docstring""" _UpperCAmelCase = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } _UpperCAmelCase = self.dummy_input return init_dict, inputs_dict def lowerCamelCase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" pass def lowerCamelCase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" pass @unittest.skipIf(torch_device == """mps""" , """Gradient checkpointing skipped on MPS""" ) def lowerCamelCase ( self : Optional[Any] ) -> Any: """simple docstring""" # enable deterministic behavior for gradient checkpointing _UpperCAmelCase , _UpperCAmelCase = self.prepare_init_args_and_inputs_for_common() _UpperCAmelCase = self.model_class(**lowerCamelCase ) model.to(lowerCamelCase ) assert not model.is_gradient_checkpointing and model.training _UpperCAmelCase = model(**lowerCamelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() _UpperCAmelCase = torch.randn_like(lowerCamelCase ) _UpperCAmelCase = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing _UpperCAmelCase = self.model_class(**lowerCamelCase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowerCamelCase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training _UpperCAmelCase = model_a(**lowerCamelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() _UpperCAmelCase = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) _UpperCAmelCase = dict(model.named_parameters() ) _UpperCAmelCase = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def lowerCamelCase ( self : int ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = AutoencoderKL.from_pretrained("""fusing/autoencoder-kl-dummy""" , output_loading_info=lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(lowerCamelCase ) _UpperCAmelCase = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def lowerCamelCase ( self : Optional[int] ) -> Dict: """simple docstring""" _UpperCAmelCase = AutoencoderKL.from_pretrained("""fusing/autoencoder-kl-dummy""" ) _UpperCAmelCase = model.to(lowerCamelCase ) model.eval() if torch_device == "mps": _UpperCAmelCase = torch.manual_seed(0 ) else: _UpperCAmelCase = torch.Generator(device=lowerCamelCase ).manual_seed(0 ) _UpperCAmelCase = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) _UpperCAmelCase = image.to(lowerCamelCase ) with torch.no_grad(): _UpperCAmelCase = model(lowerCamelCase , sample_posterior=lowerCamelCase , generator=lowerCamelCase ).sample _UpperCAmelCase = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": _UpperCAmelCase = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": _UpperCAmelCase = torch.tensor( [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026] ) else: _UpperCAmelCase = torch.tensor( [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485] ) self.assertTrue(torch_all_close(lowerCamelCase , lowerCamelCase , rtol=1E-2 ) ) @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase ( self : Union[str, Any] , lowerCamelCase : int , lowerCamelCase : Tuple ) -> Optional[int]: """simple docstring""" return f"""gaussian_noise_s={seed}_shape={"_".join([str(lowerCamelCase ) for s in shape] )}.npy""" def lowerCamelCase ( self : Dict ) -> Dict: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase ( self : str , lowerCamelCase : Dict=0 , lowerCamelCase : Optional[Any]=(4, 3, 512, 512) , lowerCamelCase : str=False ) -> Any: """simple docstring""" _UpperCAmelCase = torch.floataa if fpaa else torch.floataa _UpperCAmelCase = torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCamelCase , lowerCamelCase ) ) ).to(lowerCamelCase ).to(lowerCamelCase ) return image def lowerCamelCase ( self : Dict , lowerCamelCase : Optional[int]="CompVis/stable-diffusion-v1-4" , lowerCamelCase : Any=False ) -> List[Any]: """simple docstring""" _UpperCAmelCase = """fp16""" if fpaa else None _UpperCAmelCase = torch.floataa if fpaa else torch.floataa _UpperCAmelCase = AutoencoderKL.from_pretrained( lowerCamelCase , subfolder="""vae""" , torch_dtype=lowerCamelCase , revision=lowerCamelCase , ) model.to(lowerCamelCase ).eval() return model def lowerCamelCase ( self : Dict , lowerCamelCase : Union[str, Any]=0 ) -> str: """simple docstring""" if torch_device == "mps": return torch.manual_seed(lowerCamelCase ) return torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) @parameterized.expand( [ # fmt: off [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def lowerCamelCase ( self : List[str] , lowerCamelCase : List[str] , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = self.get_sd_vae_model() _UpperCAmelCase = self.get_sd_image(lowerCamelCase ) _UpperCAmelCase = self.get_generator(lowerCamelCase ) with torch.no_grad(): _UpperCAmelCase = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape _UpperCAmelCase = sample[-1, -2:, -2:, :2].flatten().float().cpu() _UpperCAmelCase = torch.tensor(expected_slice_mps if torch_device == """mps""" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]], [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]], # fmt: on ] ) @require_torch_gpu def lowerCamelCase ( self : int , lowerCamelCase : Union[str, Any] , lowerCamelCase : List[str] ) -> str: """simple docstring""" _UpperCAmelCase = self.get_sd_vae_model(fpaa=lowerCamelCase ) _UpperCAmelCase = self.get_sd_image(lowerCamelCase , fpaa=lowerCamelCase ) _UpperCAmelCase = self.get_generator(lowerCamelCase ) with torch.no_grad(): _UpperCAmelCase = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape _UpperCAmelCase = sample[-1, -2:, :2, -2:].flatten().float().cpu() _UpperCAmelCase = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def lowerCamelCase ( self : Tuple , lowerCamelCase : Tuple , lowerCamelCase : str , lowerCamelCase : Optional[Any] ) -> List[str]: """simple docstring""" _UpperCAmelCase = self.get_sd_vae_model() _UpperCAmelCase = self.get_sd_image(lowerCamelCase ) with torch.no_grad(): _UpperCAmelCase = model(lowerCamelCase ).sample assert sample.shape == image.shape _UpperCAmelCase = sample[-1, -2:, -2:, :2].flatten().float().cpu() _UpperCAmelCase = torch.tensor(expected_slice_mps if torch_device == """mps""" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]], [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]], # fmt: on ] ) @require_torch_gpu def lowerCamelCase ( self : Optional[Any] , lowerCamelCase : Dict , lowerCamelCase : List[Any] ) -> int: """simple docstring""" _UpperCAmelCase = self.get_sd_vae_model() _UpperCAmelCase = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): _UpperCAmelCase = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] _UpperCAmelCase = sample[-1, -2:, :2, -2:].flatten().cpu() _UpperCAmelCase = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]], [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]], # fmt: on ] ) @require_torch_gpu def lowerCamelCase ( self : Tuple , lowerCamelCase : Optional[Any] , lowerCamelCase : int ) -> Dict: """simple docstring""" _UpperCAmelCase = self.get_sd_vae_model(fpaa=lowerCamelCase ) _UpperCAmelCase = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): _UpperCAmelCase = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] _UpperCAmelCase = sample[-1, -2:, :2, -2:].flatten().float().cpu() _UpperCAmelCase = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="""xformers is not required when using PyTorch 2.0.""" ) def lowerCamelCase ( self : Union[str, Any] , lowerCamelCase : str ) -> str: """simple docstring""" _UpperCAmelCase = self.get_sd_vae_model(fpaa=lowerCamelCase ) _UpperCAmelCase = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): _UpperCAmelCase = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): _UpperCAmelCase = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="""xformers is not required when using PyTorch 2.0.""" ) def lowerCamelCase ( self : Tuple , lowerCamelCase : Dict ) -> str: """simple docstring""" _UpperCAmelCase = self.get_sd_vae_model() _UpperCAmelCase = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): _UpperCAmelCase = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): _UpperCAmelCase = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ] ) def lowerCamelCase ( self : List[str] , lowerCamelCase : List[Any] , lowerCamelCase : Any ) -> List[Any]: """simple docstring""" _UpperCAmelCase = self.get_sd_vae_model() _UpperCAmelCase = self.get_sd_image(lowerCamelCase ) _UpperCAmelCase = self.get_generator(lowerCamelCase ) with torch.no_grad(): _UpperCAmelCase = model.encode(lowerCamelCase ).latent_dist _UpperCAmelCase = dist.sample(generator=lowerCamelCase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] _UpperCAmelCase = sample[0, -1, -3:, -3:].flatten().cpu() _UpperCAmelCase = torch.tensor(lowerCamelCase ) _UpperCAmelCase = 3E-3 if torch_device != """mps""" else 1E-2 assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=lowerCamelCase )
108
class UpperCamelCase_ : # Public class to implement a graph '''simple docstring''' def __init__( self : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->None: '''simple docstring''' A__ = row A__ = col A__ = graph def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->bool: '''simple docstring''' return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->None: '''simple docstring''' A__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order A__ = [-1, 0, 1, -1, 1, -1, 0, 1] A__ = True # Make those cells visited for k in range(8): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__): self.diffs(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->int: # And finally, count all islands. '''simple docstring''' A__ = [[False for j in range(self.COL)] for i in range(self.ROW)] A__ = 0 for i in range(self.ROW): for j in range(self.COL): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) count += 1 return count
87
0
'''simple docstring''' import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 a = sys.version_info >= (3, 10) def __magic_name__ ( __UpperCAmelCase=None , __UpperCAmelCase=None ) -> str: '''simple docstring''' return field(default_factory=lambda: default , metadata=__UpperCAmelCase ) @dataclass class __a : __UpperCamelCase : int __UpperCamelCase : float __UpperCamelCase : str __UpperCamelCase : bool @dataclass class __a : __UpperCamelCase : int = 42 __UpperCamelCase : str = field(default='toto', metadata={'help': 'help message'} ) @dataclass class __a : __UpperCamelCase : bool = False __UpperCamelCase : bool = True __UpperCamelCase : Optional[bool] = None class __a ( _snake_case ): __UpperCamelCase : Any = 'titi' __UpperCamelCase : Union[str, Any] = 'toto' class __a ( _snake_case ): __UpperCamelCase : Optional[int] = 'titi' __UpperCamelCase : int = 'toto' __UpperCamelCase : Optional[Any] = 42 @dataclass class __a : __UpperCamelCase : BasicEnum = "toto" def UpperCAmelCase__ ( self : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE = BasicEnum(self.foo ) @dataclass class __a : __UpperCamelCase : MixedTypeEnum = "toto" def UpperCAmelCase__ ( self : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE = MixedTypeEnum(self.foo ) @dataclass class __a : __UpperCamelCase : Optional[int] = None __UpperCamelCase : Optional[float] = field(default=_snake_case, metadata={'help': 'help message'} ) __UpperCamelCase : Optional[str] = None __UpperCamelCase : Optional[List[str]] = list_field(default=[] ) __UpperCamelCase : Optional[List[int]] = list_field(default=[] ) @dataclass class __a : __UpperCamelCase : List[int] = list_field(default=[] ) __UpperCamelCase : List[int] = list_field(default=[1, 2, 3] ) __UpperCamelCase : List[str] = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) __UpperCamelCase : List[float] = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class __a : __UpperCamelCase : List[int] = field() __UpperCamelCase : str = field() __UpperCamelCase : BasicEnum = field() def UpperCAmelCase__ ( self : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE = BasicEnum(self.required_enum ) @dataclass class __a : __UpperCamelCase : int __UpperCamelCase : "BasicEnum" = field() __UpperCamelCase : "Optional[bool]" = None __UpperCamelCase : "str" = field(default='toto', metadata={'help': 'help message'} ) __UpperCamelCase : "List[str]" = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) if is_python_no_less_than_3_10: @dataclass class __a : __UpperCamelCase : bool = False __UpperCamelCase : bool = True __UpperCamelCase : bool | None = None @dataclass class __a : __UpperCamelCase : int | None = None __UpperCamelCase : float | None = field(default=_snake_case, metadata={'help': 'help message'} ) __UpperCamelCase : str | None = None __UpperCamelCase : list[str] | None = list_field(default=[] ) __UpperCamelCase : list[int] | None = list_field(default=[] ) class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self : List[str] ,lowerCamelCase : argparse.ArgumentParser ,lowerCamelCase : argparse.ArgumentParser ): '''simple docstring''' self.assertEqual(len(a._actions ) ,len(b._actions ) ) for x, y in zip(a._actions ,b._actions ): __SCREAMING_SNAKE_CASE = {k: v for k, v in vars(lowerCamelCase ).items() if k != """container"""} __SCREAMING_SNAKE_CASE = {k: v for k, v in vars(lowerCamelCase ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" ,lowerCamelCase ) and yy.get("""choices""" ,lowerCamelCase ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](lowerCamelCase ) ,yy["""type"""](lowerCamelCase ) ) del xx["type"], yy["type"] self.assertEqual(lowerCamelCase ,lowerCamelCase ) def UpperCAmelCase__ ( self : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() expected.add_argument("""--foo""" ,type=lowerCamelCase ,required=lowerCamelCase ) expected.add_argument("""--bar""" ,type=lowerCamelCase ,required=lowerCamelCase ) expected.add_argument("""--baz""" ,type=lowerCamelCase ,required=lowerCamelCase ) expected.add_argument("""--flag""" ,type=lowerCamelCase ,default=lowerCamelCase ,const=lowerCamelCase ,nargs="""?""" ) self.argparsersEqual(lowerCamelCase ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] ((__SCREAMING_SNAKE_CASE) , ) = parser.parse_args_into_dataclasses(lowerCamelCase ,look_for_args_file=lowerCamelCase ) self.assertFalse(example.flag ) def UpperCAmelCase__ ( self : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() expected.add_argument("""--foo""" ,default=42 ,type=lowerCamelCase ) expected.add_argument("""--baz""" ,default="""toto""" ,type=lowerCamelCase ,help="""help message""" ) self.argparsersEqual(lowerCamelCase ,lowerCamelCase ) def UpperCAmelCase__ ( self : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() expected.add_argument("""--foo""" ,type=lowerCamelCase ,default=lowerCamelCase ,const=lowerCamelCase ,nargs="""?""" ) expected.add_argument("""--baz""" ,type=lowerCamelCase ,default=lowerCamelCase ,const=lowerCamelCase ,nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" ,action="""store_false""" ,default=lowerCamelCase ,dest="""baz""" ) expected.add_argument("""--opt""" ,type=lowerCamelCase ,default=lowerCamelCase ) __SCREAMING_SNAKE_CASE = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(lowerCamelCase ) for dataclass_type in dataclass_types: __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) self.argparsersEqual(lowerCamelCase ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = parser.parse_args([] ) self.assertEqual(lowerCamelCase ,Namespace(foo=lowerCamelCase ,baz=lowerCamelCase ,opt=lowerCamelCase ) ) __SCREAMING_SNAKE_CASE = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(lowerCamelCase ,Namespace(foo=lowerCamelCase ,baz=lowerCamelCase ,opt=lowerCamelCase ) ) __SCREAMING_SNAKE_CASE = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(lowerCamelCase ,Namespace(foo=lowerCamelCase ,baz=lowerCamelCase ,opt=lowerCamelCase ) ) __SCREAMING_SNAKE_CASE = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(lowerCamelCase ,Namespace(foo=lowerCamelCase ,baz=lowerCamelCase ,opt=lowerCamelCase ) ) __SCREAMING_SNAKE_CASE = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(lowerCamelCase ,Namespace(foo=lowerCamelCase ,baz=lowerCamelCase ,opt=lowerCamelCase ) ) def UpperCAmelCase__ ( self : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() expected.add_argument( """--foo""" ,default="""toto""" ,choices=["""titi""", """toto""", 42] ,type=make_choice_type_function(["""titi""", """toto""", 42] ) ,) self.argparsersEqual(lowerCamelCase ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = parser.parse_args([] ) self.assertEqual(args.foo ,"""toto""" ) __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo ,MixedTypeEnum.toto ) __SCREAMING_SNAKE_CASE = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo ,"""titi""" ) __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo ,MixedTypeEnum.titi ) __SCREAMING_SNAKE_CASE = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo ,42 ) __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo ,MixedTypeEnum.fourtytwo ) def UpperCAmelCase__ ( self : Any ): '''simple docstring''' @dataclass class __a : __UpperCamelCase : Literal["titi", "toto", 42] = "toto" __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() expected.add_argument( """--foo""" ,default="""toto""" ,choices=("""titi""", """toto""", 42) ,type=make_choice_type_function(["""titi""", """toto""", 42] ) ,) self.argparsersEqual(lowerCamelCase ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = parser.parse_args([] ) self.assertEqual(args.foo ,"""toto""" ) __SCREAMING_SNAKE_CASE = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo ,"""titi""" ) __SCREAMING_SNAKE_CASE = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo ,42 ) def UpperCAmelCase__ ( self : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() expected.add_argument("""--foo_int""" ,nargs="""+""" ,default=[] ,type=lowerCamelCase ) expected.add_argument("""--bar_int""" ,nargs="""+""" ,default=[1, 2, 3] ,type=lowerCamelCase ) expected.add_argument("""--foo_str""" ,nargs="""+""" ,default=["""Hallo""", """Bonjour""", """Hello"""] ,type=lowerCamelCase ) expected.add_argument("""--foo_float""" ,nargs="""+""" ,default=[0.1, 0.2, 0.3] ,type=lowerCamelCase ) self.argparsersEqual(lowerCamelCase ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = parser.parse_args([] ) self.assertEqual( lowerCamelCase ,Namespace(foo_int=[] ,bar_int=[1, 2, 3] ,foo_str=["""Hallo""", """Bonjour""", """Hello"""] ,foo_float=[0.1, 0.2, 0.3] ) ,) __SCREAMING_SNAKE_CASE = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(lowerCamelCase ,Namespace(foo_int=[1] ,bar_int=[2, 3] ,foo_str=["""a""", """b""", """c"""] ,foo_float=[0.1, 0.7] ) ) def UpperCAmelCase__ ( self : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() expected.add_argument("""--foo""" ,default=lowerCamelCase ,type=lowerCamelCase ) expected.add_argument("""--bar""" ,default=lowerCamelCase ,type=lowerCamelCase ,help="""help message""" ) expected.add_argument("""--baz""" ,default=lowerCamelCase ,type=lowerCamelCase ) expected.add_argument("""--ces""" ,nargs="""+""" ,default=[] ,type=lowerCamelCase ) expected.add_argument("""--des""" ,nargs="""+""" ,default=[] ,type=lowerCamelCase ) __SCREAMING_SNAKE_CASE = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(lowerCamelCase ) for dataclass_type in dataclass_types: __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) self.argparsersEqual(lowerCamelCase ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = parser.parse_args([] ) self.assertEqual(lowerCamelCase ,Namespace(foo=lowerCamelCase ,bar=lowerCamelCase ,baz=lowerCamelCase ,ces=[] ,des=[] ) ) __SCREAMING_SNAKE_CASE = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(lowerCamelCase ,Namespace(foo=12 ,bar=3.14 ,baz="""42""" ,ces=["""a""", """b""", """c"""] ,des=[1, 2, 3] ) ) def UpperCAmelCase__ ( self : Union[str, Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() expected.add_argument("""--required_list""" ,nargs="""+""" ,type=lowerCamelCase ,required=lowerCamelCase ) expected.add_argument("""--required_str""" ,type=lowerCamelCase ,required=lowerCamelCase ) expected.add_argument( """--required_enum""" ,type=make_choice_type_function(["""titi""", """toto"""] ) ,choices=["""titi""", """toto"""] ,required=lowerCamelCase ,) self.argparsersEqual(lowerCamelCase ,lowerCamelCase ) def UpperCAmelCase__ ( self : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() expected.add_argument("""--foo""" ,type=lowerCamelCase ,required=lowerCamelCase ) expected.add_argument( """--required_enum""" ,type=make_choice_type_function(["""titi""", """toto"""] ) ,choices=["""titi""", """toto"""] ,required=lowerCamelCase ,) expected.add_argument("""--opt""" ,type=lowerCamelCase ,default=lowerCamelCase ) expected.add_argument("""--baz""" ,default="""toto""" ,type=lowerCamelCase ,help="""help message""" ) expected.add_argument("""--foo_str""" ,nargs="""+""" ,default=["""Hallo""", """Bonjour""", """Hello"""] ,type=lowerCamelCase ) self.argparsersEqual(lowerCamelCase ,lowerCamelCase ) def UpperCAmelCase__ ( self : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) __SCREAMING_SNAKE_CASE = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } __SCREAMING_SNAKE_CASE = parser.parse_dict(lowerCamelCase )[0] __SCREAMING_SNAKE_CASE = BasicExample(**lowerCamelCase ) self.assertEqual(lowerCamelCase ,lowerCamelCase ) def UpperCAmelCase__ ( self : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) __SCREAMING_SNAKE_CASE = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(lowerCamelCase ,parser.parse_dict ,lowerCamelCase ,allow_extra_keys=lowerCamelCase ) def UpperCAmelCase__ ( self : Union[str, Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) __SCREAMING_SNAKE_CASE = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: __SCREAMING_SNAKE_CASE = os.path.join(lowerCamelCase ,"""temp_json""" ) os.mkdir(lowerCamelCase ) with open(temp_local_path + """.json""" ,"""w+""" ) as f: json.dump(lowerCamelCase ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] __SCREAMING_SNAKE_CASE = BasicExample(**lowerCamelCase ) self.assertEqual(lowerCamelCase ,lowerCamelCase ) def UpperCAmelCase__ ( self : List[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) __SCREAMING_SNAKE_CASE = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: __SCREAMING_SNAKE_CASE = os.path.join(lowerCamelCase ,"""temp_yaml""" ) os.mkdir(lowerCamelCase ) with open(temp_local_path + """.yaml""" ,"""w+""" ) as f: yaml.dump(lowerCamelCase ,lowerCamelCase ) __SCREAMING_SNAKE_CASE = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] __SCREAMING_SNAKE_CASE = BasicExample(**lowerCamelCase ) self.assertEqual(lowerCamelCase ,lowerCamelCase ) def UpperCAmelCase__ ( self : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfArgumentParser(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase )
109
from __future__ import annotations import requests _lowerCamelCase : str = set( """approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod_post category clicked content_categories created_utc downs edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta is_original_content is_reddit_media_domain is_video link_flair_css_class link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title name permalink pwls quarantine saved score secure_media secure_media_embed selftext subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type total_awards_received ups upvote_ratio url user_reports""".split() ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = 1 , lowercase_ = "new" , lowercase_ = None ) -> dict: """simple docstring""" A__ = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(lowercase_ ) - valid_terms ) ): A__ = f"""Invalid search term: {invalid_search_terms}""" raise ValueError(lowercase_ ) A__ = requests.get( f"""https://reddit.com/r/{subreddit}/{age}.json?limit={limit}""" , headers={'''User-agent''': '''A random string'''} , ) if response.status_code == 429: raise requests.HTTPError A__ = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(lowercase_ )} A__ = {} for id_ in range(lowercase_ ): A__ = { item: data['''data''']['''children'''][id_]['''data'''][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("""learnpython""", wanted_data=["""title""", """url""", """selftext"""]))
87
0
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class a ( lowercase ): UpperCamelCase : Tuple = ["""image_processor""", """tokenizer"""] UpperCamelCase : List[str] = """LayoutLMv2ImageProcessor""" UpperCamelCase : Optional[int] = ("""LayoutXLMTokenizer""", """LayoutXLMTokenizerFast""") def __init__( self , UpperCamelCase_=None , UpperCamelCase_=None , **UpperCamelCase_ ): if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , UpperCamelCase_ , ) UpperCAmelCase__ : Tuple = kwargs.pop('feature_extractor' ) UpperCAmelCase__ : 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__(UpperCamelCase_ , UpperCamelCase_ ) def __call__( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = True , UpperCamelCase_ = False , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = 0 , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = True , UpperCamelCase_ = None , **UpperCamelCase_ , ): # 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__ : List[Any] = self.image_processor(images=UpperCamelCase_ , return_tensors=UpperCamelCase_ ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(UpperCamelCase_ , UpperCamelCase_ ): UpperCAmelCase__ : Any = [text] # add batch dimension (as the image processor always adds a batch dimension) UpperCAmelCase__ : Union[str, Any] = features['words'] UpperCAmelCase__ : List[Any] = self.tokenizer( text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=UpperCamelCase_ , add_special_tokens=UpperCamelCase_ , padding=UpperCamelCase_ , truncation=UpperCamelCase_ , max_length=UpperCamelCase_ , stride=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , return_overflowing_tokens=UpperCamelCase_ , return_special_tokens_mask=UpperCamelCase_ , return_offsets_mapping=UpperCamelCase_ , return_length=UpperCamelCase_ , verbose=UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ , ) # add pixel values UpperCAmelCase__ : List[Any] = features.pop('pixel_values' ) if return_overflowing_tokens is True: UpperCAmelCase__ : int = self.get_overflowing_images(UpperCamelCase_ , encoded_inputs['overflow_to_sample_mapping'] ) UpperCAmelCase__ : Dict = images return encoded_inputs def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image UpperCAmelCase__ : Dict = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(UpperCamelCase_ ) != len(UpperCamelCase_ ): raise ValueError( 'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got' F''' {len(UpperCamelCase_ )} and {len(UpperCamelCase_ )}''' ) return images_with_overflow def __snake_case ( self , *UpperCamelCase_ , **UpperCamelCase_ ): return self.tokenizer.batch_decode(*UpperCamelCase_ , **UpperCamelCase_ ) def __snake_case ( self , *UpperCamelCase_ , **UpperCamelCase_ ): return self.tokenizer.decode(*UpperCamelCase_ , **UpperCamelCase_ ) @property def __snake_case ( self ): return ["input_ids", "bbox", "attention_mask", "image"] @property def __snake_case ( self ): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , UpperCamelCase_ , ) return self.image_processor_class @property def __snake_case ( self ): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , UpperCamelCase_ , ) return self.image_processor
110
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = JukeboxTokenizer UpperCAmelCase__ = { '''artist''': '''Zac Brown Band''', '''genres''': '''Country''', '''lyrics''': '''I met a traveller from an antique land, Who said "Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away ''', } @require_torch def SCREAMING_SNAKE_CASE ( self : Dict) ->int: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''') A__ = tokenizer(**self.metas)['''input_ids'''] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 7_169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]]), torch.tensor([[0, 0, 0, 1_069, 11]]), torch.tensor([[0, 0, 0, 1_069, 11]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2])) @require_torch def SCREAMING_SNAKE_CASE ( self : List[str]) ->Optional[int]: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''') A__ = tokenizer(**self.metas)['''input_ids'''] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 1_069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]]), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]]), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2]))
87
0
'''simple docstring''' import unittest from transformers import XLMConfig, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class _snake_case : def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=True , a__=False , a__=False , a__=False , a__=2 , a__=99 , a__=0 , a__=32 , a__=5 , a__=4 , a__=0.1 , a__=0.1 , a__=512 , a__=2 , a__=0.0_2 , a__=2 , a__=4 , a__="last" , a__=True , a__=None , a__=0 , ) -> List[Any]: '''simple docstring''' snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_lengths snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = gelu_activation snake_case_ = sinusoidal_embeddings snake_case_ = causal snake_case_ = asm snake_case_ = n_langs snake_case_ = vocab_size snake_case_ = n_special snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = num_choices snake_case_ = summary_type snake_case_ = use_proj snake_case_ = scope snake_case_ = bos_token_id def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = None if self.use_input_lengths: snake_case_ = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) snake_case_ = None snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = ids_tensor([self.batch_size] , 2 ).float() snake_case_ = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' return XLMConfig( 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 , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) -> Union[str, Any]: '''simple docstring''' snake_case_ = XLMModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case_ = model(UpperCAmelCase__ , lengths=UpperCAmelCase__ , langs=UpperCAmelCase__ ) snake_case_ = model(UpperCAmelCase__ , langs=UpperCAmelCase__ ) snake_case_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) -> Any: '''simple docstring''' snake_case_ = XLMWithLMHeadModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case_ = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) -> List[Any]: '''simple docstring''' snake_case_ = XLMForQuestionAnsweringSimple(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case_ = model(UpperCAmelCase__ ) snake_case_ = model(UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ ) snake_case_ = outputs 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 , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) -> Optional[Any]: '''simple docstring''' snake_case_ = XLMForQuestionAnswering(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case_ = model(UpperCAmelCase__ ) snake_case_ = model( UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , cls_index=UpperCAmelCase__ , is_impossible=UpperCAmelCase__ , p_mask=UpperCAmelCase__ , ) snake_case_ = model( UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , cls_index=UpperCAmelCase__ , is_impossible=UpperCAmelCase__ , ) ((snake_case_ ) , ) = result_with_labels.to_tuple() snake_case_ = model(UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ ) ((snake_case_ ) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) -> int: '''simple docstring''' snake_case_ = XLMForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case_ = model(UpperCAmelCase__ ) snake_case_ = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) -> str: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = XLMForTokenClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case_ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) -> List[str]: '''simple docstring''' snake_case_ = self.num_choices snake_case_ = XLMForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case_ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths} return config, inputs_dict @require_torch class _snake_case ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): lowerCAmelCase_ : List[str] = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowerCAmelCase_ : Optional[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowerCAmelCase_ : Any = ( { "feature-extraction": XLMModel, "fill-mask": XLMWithLMHeadModel, "question-answering": XLMForQuestionAnsweringSimple, "text-classification": XLMForSequenceClassification, "text-generation": XLMWithLMHeadModel, "token-classification": XLMForTokenClassification, "zero-shot": XLMForSequenceClassification, } if is_torch_available() else {} ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ ) -> str: '''simple docstring''' 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 lowerCAmelCase__ ( self , a__ , a__ , a__=False ) -> Tuple: '''simple docstring''' snake_case_ = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": snake_case_ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) snake_case_ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = XLMModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase__ , emb_dim=37 ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*UpperCAmelCase__ ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*UpperCAmelCase__ ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*UpperCAmelCase__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*UpperCAmelCase__ ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*UpperCAmelCase__ ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*UpperCAmelCase__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*UpperCAmelCase__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__=False , a__=1 ) -> int: '''simple docstring''' self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual( [isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for iter_attentions in attentions] , [True] * len(UpperCAmelCase__ ) ) self.assertEqual(len(UpperCAmelCase__ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(UpperCAmelCase__ ): # adds PAD dummy token snake_case_ = min_length + idx + 1 snake_case_ = min_length + idx + 1 snake_case_ = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(UpperCAmelCase__ ) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__=False , a__=1 ) -> Dict: '''simple docstring''' self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual( [isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for iter_hidden_states in hidden_states] , [True] * len(UpperCAmelCase__ ) , ) self.assertEqual(len(UpperCAmelCase__ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(UpperCAmelCase__ ): # adds PAD dummy token snake_case_ = min_length + idx + 1 snake_case_ = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(UpperCAmelCase__ ) , ) pass @slow def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = XLMModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @require_torch class _snake_case ( unittest.TestCase ): @slow def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = XLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048" ) model.to(UpperCAmelCase__ ) snake_case_ = torch.tensor([[14, 447]] , dtype=torch.long , device=UpperCAmelCase__ ) # the president snake_case_ = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference snake_case_ = model.generate(UpperCAmelCase__ , do_sample=UpperCAmelCase__ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , UpperCAmelCase__ )
400
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : str = logging.get_logger(__name__) _lowerCamelCase : List[str] = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''openai-gpt''' UpperCAmelCase__ = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict=40_478 , UpperCAmelCase__ : str=512 , UpperCAmelCase__ : Union[str, Any]=768 , UpperCAmelCase__ : Optional[Any]=12 , UpperCAmelCase__ : Any=12 , UpperCAmelCase__ : Optional[Any]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : List[str]=1e-5 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Any="cls_index" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Optional[Any]=0.1 , **UpperCAmelCase__ : Dict , ) ->Any: '''simple docstring''' A__ = vocab_size A__ = n_positions A__ = n_embd A__ = n_layer A__ = n_head A__ = afn A__ = resid_pdrop A__ = embd_pdrop A__ = attn_pdrop A__ = layer_norm_epsilon A__ = initializer_range A__ = summary_type A__ = summary_use_proj A__ = summary_activation A__ = summary_first_dropout A__ = summary_proj_to_labels super().__init__(**UpperCAmelCase__)
87
0
'''simple docstring''' def lowercase__( _UpperCamelCase : Tuple )-> Union[str, Any]: """simple docstring""" _UpperCamelCase = len(lowercase_ ) while cur > 1: # Find the maximum number in arr _UpperCamelCase = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi _UpperCamelCase = arr[mi::-1] + arr[mi + 1 : len(lowercase_ )] # Reverse whole list _UpperCamelCase = arr[cur - 1 :: -1] + arr[cur : len(lowercase_ )] cur -= 1 return arr if __name__ == "__main__": snake_case_ : Optional[Any] = input('''Enter numbers separated by a comma:\n''').strip() snake_case_ : Any = [int(item) for item in user_input.split(''',''')] print(pancake_sort(unsorted))
138
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
__magic_name__: Optional[int] = { """Pillow""": """Pillow""", """accelerate""": """accelerate>=0.11.0""", """compel""": """compel==0.1.8""", """black""": """black~=23.1""", """datasets""": """datasets""", """filelock""": """filelock""", """flax""": """flax>=0.4.1""", """hf-doc-builder""": """hf-doc-builder>=0.3.0""", """huggingface-hub""": """huggingface-hub>=0.13.2""", """requests-mock""": """requests-mock==1.10.0""", """importlib_metadata""": """importlib_metadata""", """invisible-watermark""": """invisible-watermark""", """isort""": """isort>=5.5.4""", """jax""": """jax>=0.2.8,!=0.3.2""", """jaxlib""": """jaxlib>=0.1.65""", """Jinja2""": """Jinja2""", """k-diffusion""": """k-diffusion>=0.0.12""", """torchsde""": """torchsde""", """note_seq""": """note_seq""", """librosa""": """librosa""", """numpy""": """numpy""", """omegaconf""": """omegaconf""", """parameterized""": """parameterized""", """protobuf""": """protobuf>=3.20.3,<4""", """pytest""": """pytest""", """pytest-timeout""": """pytest-timeout""", """pytest-xdist""": """pytest-xdist""", """ruff""": """ruff>=0.0.241""", """safetensors""": """safetensors""", """sentencepiece""": """sentencepiece>=0.1.91,!=0.1.92""", """scipy""": """scipy""", """onnx""": """onnx""", """regex""": """regex!=2019.12.17""", """requests""": """requests""", """tensorboard""": """tensorboard""", """torch""": """torch>=1.4""", """torchvision""": """torchvision""", """transformers""": """transformers>=4.25.1""", """urllib3""": """urllib3<=2.0.0""", }
324
import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None ) -> Dict: """simple docstring""" if "." in tensor_name: A__ = tensor_name.split('''.''' ) for split in splits[:-1]: A__ = getattr(lowercase_ , lowercase_ ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) A__ = new_module A__ = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(f"""{module} does not have a parameter or a buffer named {tensor_name}.""" ) A__ = tensor_name in module._buffers A__ = getattr(lowercase_ , lowercase_ ) if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None: raise ValueError(f"""{tensor_name} is on the meta device, we need a `value` to put in on {device}.""" ) A__ = False A__ = False if is_buffer or not is_bitsandbytes_available(): A__ = False A__ = False else: A__ = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) A__ = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: A__ = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to('''cpu''' ) if value.dtype == torch.inta: A__ = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse( '''0.37.2''' ) if not is_abit_serializable: raise ValueError( '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ''' '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' ) else: A__ = torch.tensor(lowercase_ , device='''cpu''' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , lowercase_ ) and fpaa_statistics is None: A__ = new_value.T A__ = old_value.__dict__ if is_abit: A__ = bnb.nn.IntaParams(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) elif is_abit: A__ = bnb.nn.Paramsabit(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) A__ = new_value if fpaa_statistics is not None: setattr(module.weight , '''SCB''' , fpaa_statistics.to(lowercase_ ) ) else: if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to(lowercase_ ) else: A__ = torch.tensor(lowercase_ , device=lowercase_ ) if is_buffer: A__ = new_value else: A__ = nn.Parameter(lowercase_ , requires_grad=old_value.requires_grad ) A__ = new_value def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=False ) -> Dict: """simple docstring""" for name, module in model.named_children(): if current_key_name is None: A__ = [] current_key_name.append(lowercase_ ) if (isinstance(lowercase_ , nn.Linear ) or isinstance(lowercase_ , lowercase_ )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '''.'''.join(lowercase_ ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(lowercase_ , lowercase_ ): A__ , A__ = module.weight.shape else: A__ = module.in_features A__ = module.out_features if quantization_config.quantization_method() == "llm_int8": A__ = bnb.nn.LinearabitLt( lowercase_ , lowercase_ , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) A__ = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: A__ = bnb.nn.Linearabit( lowercase_ , lowercase_ , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) A__ = True # Store the module class in case we need to transpose the weight later A__ = type(lowercase_ ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(lowercase_ ) if len(list(module.children() ) ) > 0: A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ , has_been_replaced=lowercase_ , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None ) -> Tuple: """simple docstring""" A__ = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Dict: """simple docstring""" warnings.warn( '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , lowercase_ , ) return replace_with_bnb_linear(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Optional[Any]: """simple docstring""" warnings.warn( '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , lowercase_ , ) return set_module_quantized_tensor_to_device(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]: """simple docstring""" A__ = deepcopy(lowercase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() A__ = find_tied_parameters(lowercase_ ) # For compatibility with Accelerate < 0.18 if isinstance(lowercase_ , lowercase_ ): A__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: A__ = sum(lowercase_ , [] ) A__ = len(lowercase_ ) > 0 # Check if it is a base model A__ = not hasattr(lowercase_ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head A__ = list(model.named_children() ) A__ = [list_modules[-1][0]] # add last module together with tied weights A__ = set(lowercase_ ) - set(lowercase_ ) A__ = list(set(lowercase_ ) ) + list(lowercase_ ) # remove ".weight" from the keys A__ = ['''.weight''', '''.bias'''] A__ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: A__ = name.replace(lowercase_ , '''''' ) filtered_module_names.append(lowercase_ ) return filtered_module_names
87
0
import string def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = "" for i in sequence: SCREAMING_SNAKE_CASE_ = ord(lowercase_ ) if 6_5 <= extract <= 9_0: output += chr(1_5_5 - extract ) elif 9_7 <= extract <= 1_2_2: output += chr(2_1_9 - extract ) else: output += i return output def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = string.ascii_letters SCREAMING_SNAKE_CASE_ = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(lowercase_ )] if c in letters else c for c in sequence ) def a__ ( ): from timeit import timeit print("Running performance benchmarks..." ) SCREAMING_SNAKE_CASE_ = "from string import printable ; from __main__ import atbash, atbash_slow" print(F'''> atbash_slow(): {timeit("atbash_slow(printable)" , setup=lowercase_ )} seconds''' ) print(F'''> atbash(): {timeit("atbash(printable)" , setup=lowercase_ )} seconds''' ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"{example} encrypted in atbash: {atbash(example)}") benchmark()
140
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) _lowerCamelCase : str = 299792458 # Symbols _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = symbols("""ct x y z""") def SCREAMING_SNAKE_CASE ( lowercase_ ) -> float: """simple docstring""" 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 ( lowercase_ ) -> float: """simple docstring""" return 1 / sqrt(1 - beta(lowercase_ ) ** 2 ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> np.ndarray: """simple docstring""" return np.array( [ [gamma(lowercase_ ), -gamma(lowercase_ ) * beta(lowercase_ ), 0, 0], [-gamma(lowercase_ ) * beta(lowercase_ ), gamma(lowercase_ ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = None ) -> np.ndarray: """simple docstring""" if event is None: A__ = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(lowercase_ ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: _lowerCamelCase : Tuple = transform(29979245) 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 _lowerCamelCase : int = {ct: c, x: 1, y: 1, z: 1} _lowerCamelCase : Any = [four_vector[i].subs(sub_dict) for i in range(4)] print(F'''\n{numerical_vector}''')
87
0
"""simple docstring""" import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def A_ ( snake_case__ ) -> Any: _UpperCamelCase :List[str] = args.pruning_method _UpperCamelCase :Union[str, Any] = args.threshold _UpperCamelCase :int = args.model_name_or_path.rstrip('''/''' ) _UpperCamelCase :int = args.target_model_path print(f"Load fine-pruned model from {model_name_or_path}" ) _UpperCamelCase :Tuple = torch.load(os.path.join(lowercase_ , '''pytorch_model.bin''' ) ) _UpperCamelCase :Union[str, Any] = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: _UpperCamelCase :Dict = tensor print(f"Copied layer {name}" ) elif "classifier" in name or "qa_output" in name: _UpperCamelCase :Optional[int] = tensor print(f"Copied layer {name}" ) elif "bias" in name: _UpperCamelCase :Tuple = tensor print(f"Copied layer {name}" ) else: if pruning_method == "magnitude": _UpperCamelCase :Tuple = MagnitudeBinarizer.apply(inputs=lowercase_ , threshold=lowercase_ ) _UpperCamelCase :str = tensor * mask print(f"Pruned layer {name}" ) elif pruning_method == "topK": if "mask_scores" in name: continue _UpperCamelCase :List[str] = name[:-6] _UpperCamelCase :int = model[f"{prefix_}mask_scores"] _UpperCamelCase :Dict = TopKBinarizer.apply(lowercase_ , lowercase_ ) _UpperCamelCase :Dict = tensor * mask print(f"Pruned layer {name}" ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue _UpperCamelCase :Tuple = name[:-6] _UpperCamelCase :Optional[Any] = model[f"{prefix_}mask_scores"] _UpperCamelCase :List[Any] = ThresholdBinarizer.apply(lowercase_ , lowercase_ , lowercase_ ) _UpperCamelCase :str = tensor * mask print(f"Pruned layer {name}" ) elif pruning_method == "l0": if "mask_scores" in name: continue _UpperCamelCase :Dict = name[:-6] _UpperCamelCase :Tuple = model[f"{prefix_}mask_scores"] _UpperCamelCase , _UpperCamelCase :Any = -0.1, 1.1 _UpperCamelCase :List[str] = torch.sigmoid(lowercase_ ) _UpperCamelCase :Optional[int] = s * (r - l) + l _UpperCamelCase :Tuple = s_bar.clamp(min=0.0 , max=1.0 ) _UpperCamelCase :Tuple = tensor * mask print(f"Pruned layer {name}" ) else: raise ValueError('''Unknown pruning method''' ) if target_model_path is None: _UpperCamelCase :int = os.path.join( os.path.dirname(lowercase_ ) , f"bertarized_{os.path.basename(lowercase_ )}" ) if not os.path.isdir(lowercase_ ): shutil.copytree(lowercase_ , lowercase_ ) print(f"\nCreated folder {target_model_path}" ) torch.save(lowercase_ , os.path.join(lowercase_ , '''pytorch_model.bin''' ) ) print('''\nPruned model saved! See you later!''' ) if __name__ == "__main__": UpperCamelCase__ :Optional[Any] = argparse.ArgumentParser() parser.add_argument( """--pruning_method""", choices=["""l0""", """magnitude""", """topK""", """sigmoied_threshold"""], type=str, required=True, help=( """Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,""" """ sigmoied_threshold = Soft movement pruning)""" ), ) parser.add_argument( """--threshold""", type=float, required=False, help=( """For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.""" """For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.""" """Not needed for `l0`""" ), ) parser.add_argument( """--model_name_or_path""", type=str, required=True, help="""Folder containing the model that was previously fine-pruned""", ) parser.add_argument( """--target_model_path""", default=None, type=str, required=False, help="""Folder containing the model that was previously fine-pruned""", ) UpperCamelCase__ :int = parser.parse_args() main(args)
355
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> list: """simple docstring""" if len(lowercase_ ) <= 1: return [tuple(lowercase_ )] A__ = [] def generate(lowercase_ , lowercase_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , lowercase_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even A__ , A__ = arr[k - 1], arr[i] else: # k is odd A__ , A__ = arr[k - 1], arr[0] generate(k - 1 , lowercase_ ) generate(len(lowercase_ ) , lowercase_ ) return res if __name__ == "__main__": _lowerCamelCase : int = input("""Enter numbers separated by a comma:\n""").strip() _lowerCamelCase : str = [int(item) for item in user_input.split(""",""")] print(heaps(arr))
87
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase__ = { """configuration_bert""": ["""BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BertConfig""", """BertOnnxConfig"""], """tokenization_bert""": ["""BasicTokenizer""", """BertTokenizer""", """WordpieceTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ["""BertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BertForMaskedLM""", """BertForMultipleChoice""", """BertForNextSentencePrediction""", """BertForPreTraining""", """BertForQuestionAnswering""", """BertForSequenceClassification""", """BertForTokenClassification""", """BertLayer""", """BertLMHeadModel""", """BertModel""", """BertPreTrainedModel""", """load_tf_weights_in_bert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBertEmbeddings""", """TFBertForMaskedLM""", """TFBertForMultipleChoice""", """TFBertForNextSentencePrediction""", """TFBertForPreTraining""", """TFBertForQuestionAnswering""", """TFBertForSequenceClassification""", """TFBertForTokenClassification""", """TFBertLMHeadModel""", """TFBertMainLayer""", """TFBertModel""", """TFBertPreTrainedModel""", ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ["""TFBertTokenizer"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """FlaxBertForCausalLM""", """FlaxBertForMaskedLM""", """FlaxBertForMultipleChoice""", """FlaxBertForNextSentencePrediction""", """FlaxBertForPreTraining""", """FlaxBertForQuestionAnswering""", """FlaxBertForSequenceClassification""", """FlaxBertForTokenClassification""", """FlaxBertModel""", """FlaxBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
322
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Union[str, Any]: """simple docstring""" A__ = np.max(_outputs , axis=-1 , keepdims=lowercase_ ) A__ = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowercase_ ) class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''sigmoid''' UpperCAmelCase__ = '''softmax''' UpperCAmelCase__ = '''none''' @add_end_docstrings( UpperCAmelCase__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = False UpperCAmelCase__ = ClassificationFunction.NONE def __init__( self : Any , **UpperCAmelCase__ : Optional[Any]) ->str: '''simple docstring''' super().__init__(**UpperCAmelCase__) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int="" , **UpperCAmelCase__ : Any) ->int: '''simple docstring''' A__ = tokenizer_kwargs A__ = {} if hasattr(self.model.config , '''return_all_scores''') and return_all_scores is None: A__ = self.model.config.return_all_scores if isinstance(UpperCAmelCase__ , UpperCAmelCase__) or top_k is None: A__ = top_k A__ = False elif return_all_scores is not None: warnings.warn( '''`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of''' ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.''' , UpperCAmelCase__ , ) if return_all_scores: A__ = None else: A__ = 1 if isinstance(UpperCAmelCase__ , UpperCAmelCase__): A__ = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: A__ = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self : str , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : Optional[int]) ->Union[str, Any]: '''simple docstring''' A__ = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__) # TODO try and retrieve it in a nicer way from _sanitize_parameters. A__ = '''top_k''' not in kwargs if isinstance(args[0] , UpperCAmelCase__) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : Any , **UpperCAmelCase__ : str) ->Dict[str, GenericTensor]: '''simple docstring''' A__ = self.framework if isinstance(UpperCAmelCase__ , UpperCAmelCase__): return self.tokenizer(**UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__) and len(UpperCAmelCase__) == 1 and isinstance(inputs[0] , UpperCAmelCase__) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a''' ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.''') return self.tokenizer(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : Tuple) ->Tuple: '''simple docstring''' return self.model(**UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : str=True) ->Dict: '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: A__ = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: A__ = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''') and function_to_apply is None: A__ = self.model.config.function_to_apply else: A__ = ClassificationFunction.NONE A__ = model_outputs['''logits'''][0] A__ = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: A__ = sigmoid(UpperCAmelCase__) elif function_to_apply == ClassificationFunction.SOFTMAX: A__ = softmax(UpperCAmelCase__) elif function_to_apply == ClassificationFunction.NONE: A__ = outputs else: raise ValueError(f"""Unrecognized `function_to_apply` argument: {function_to_apply}""") if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} A__ = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(UpperCAmelCase__) ] if not _legacy: dict_scores.sort(key=lambda UpperCAmelCase__: x["score"] , reverse=UpperCAmelCase__) if top_k is not None: A__ = dict_scores[:top_k] return dict_scores
87
0
"""simple docstring""" def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0 , __SCREAMING_SNAKE_CASE = 0 ) -> int: __lowerCAmelCase: int = right or len(lowercase_ ) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(lowercase_ , lowercase_ , left + 1 , right - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
346
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase : Any = {"""configuration_xlnet""": ["""XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : int = ["""XLNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : int = ["""XLNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Union[str, Any] = [ """XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLNetForMultipleChoice""", """XLNetForQuestionAnswering""", """XLNetForQuestionAnsweringSimple""", """XLNetForSequenceClassification""", """XLNetForTokenClassification""", """XLNetLMHeadModel""", """XLNetModel""", """XLNetPreTrainedModel""", """load_tf_weights_in_xlnet""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Dict = [ """TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLNetForMultipleChoice""", """TFXLNetForQuestionAnsweringSimple""", """TFXLNetForSequenceClassification""", """TFXLNetForTokenClassification""", """TFXLNetLMHeadModel""", """TFXLNetMainLayer""", """TFXLNetModel""", """TFXLNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys _lowerCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
87
0
"""simple docstring""" import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def lowercase__ ( lowerCAmelCase : int ) -> int: """simple docstring""" return EnvironmentCommand() class _UpperCAmelCase ( UpperCAmelCase__ ): @staticmethod def a_ ( lowercase_ ) -> int: UpperCAmelCase = parser.add_parser('env' ) download_parser.set_defaults(func=UpperCAmelCase__ ) def a_ ( self ) -> Tuple: UpperCAmelCase = huggingface_hub.__version__ UpperCAmelCase = 'not installed' UpperCAmelCase = 'NA' if is_torch_available(): import torch UpperCAmelCase = torch.__version__ UpperCAmelCase = torch.cuda.is_available() UpperCAmelCase = 'not installed' if is_transformers_available(): import transformers UpperCAmelCase = transformers.__version__ UpperCAmelCase = 'not installed' if is_accelerate_available(): import accelerate UpperCAmelCase = accelerate.__version__ UpperCAmelCase = 'not installed' if is_xformers_available(): import xformers UpperCAmelCase = xformers.__version__ UpperCAmelCase = { '`diffusers` version': version, 'Platform': platform.platform(), 'Python version': platform.python_version(), 'PyTorch version (GPU?)': F"{pt_version} ({pt_cuda_available})", 'Huggingface_hub version': hub_version, 'Transformers version': transformers_version, 'Accelerate version': accelerate_version, 'xFormers version': xformers_version, 'Using GPU in script?': '<fill in>', 'Using distributed or parallel set-up in script?': '<fill in>', } print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n' ) print(self.format_dict(UpperCAmelCase__ ) ) return info @staticmethod def a_ ( lowercase_ ) -> Tuple: return "\n".join([F"- {prop}: {val}" for prop, val in d.items()] ) + "\n"
373
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 : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : Union[str, Any] = { """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""", """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''mobilenet_v1''' def __init__( self : Optional[int] , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : Optional[Any]=224 , UpperCAmelCase__ : Optional[int]=1.0 , UpperCAmelCase__ : Optional[int]=8 , UpperCAmelCase__ : Tuple="relu6" , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Dict=0.999 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : Optional[int]=0.001 , **UpperCAmelCase__ : Dict , ) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase__) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''') A__ = num_channels A__ = image_size A__ = depth_multiplier A__ = min_depth A__ = hidden_act A__ = tf_padding A__ = classifier_dropout_prob A__ = initializer_range A__ = layer_norm_eps class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = version.parse('''1.11''' ) @property def SCREAMING_SNAKE_CASE ( self : Any) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict([('''pixel_values''', {0: '''batch'''})]) @property def SCREAMING_SNAKE_CASE ( self : List[str]) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})]) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})]) @property def SCREAMING_SNAKE_CASE ( self : int) ->float: '''simple docstring''' return 1e-4
87
0
import argparse import collections import os 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_table.py lowercase : Tuple = """src/transformers""" lowercase : Any = """docs/source/en""" lowercase : Dict = """.""" def snake_case__ ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): with open(lowercase_ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: A : int = f.readlines() # Find the start prompt. A : int = 0 while not lines[start_index].startswith(lowercase_ ): start_index += 1 start_index += 1 A : str = start_index while not lines[end_index].startswith(lowercase_ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | lowercase : Optional[Any] = """Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. lowercase : Optional[Any] = re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") lowercase : Union[str, Any] = re.compile(r"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. lowercase : str = re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # This is to make sure the transformers module imported is the one in the repo. lowercase : str = direct_transformers_import(TRANSFORMERS_PATH) def snake_case__ ( lowerCamelCase_ ): A : List[str] = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , lowercase_ ) return [m.group(0 ) for m in matches] def snake_case__ ( lowerCamelCase_ , lowerCamelCase_ ): A : int = 2 if text == '''✅''' or text == '''❌''' else len(lowercase_ ) A : List[str] = (width - text_length) // 2 A : Dict = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def snake_case__ ( ): A : Optional[Any] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES A : Union[str, Any] = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } A : Union[str, Any] = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. A : List[str] = collections.defaultdict(lowercase_ ) A : str = collections.defaultdict(lowercase_ ) A : Any = collections.defaultdict(lowercase_ ) A : str = collections.defaultdict(lowercase_ ) A : Dict = collections.defaultdict(lowercase_ ) # Let's lookup through all transformers object (once). for attr_name in dir(lowercase_ ): A : List[str] = None if attr_name.endswith('''Tokenizer''' ): A : Union[str, Any] = slow_tokenizers A : List[Any] = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): A : Dict = fast_tokenizers A : List[Any] = attr_name[:-13] elif _re_tf_models.match(lowercase_ ) is not None: A : str = tf_models A : Tuple = _re_tf_models.match(lowercase_ ).groups()[0] elif _re_flax_models.match(lowercase_ ) is not None: A : Tuple = flax_models A : List[str] = _re_flax_models.match(lowercase_ ).groups()[0] elif _re_pt_models.match(lowercase_ ) is not None: A : List[Any] = pt_models A : str = _re_pt_models.match(lowercase_ ).groups()[0] if lookup_dict is not None: while len(lowercase_ ) > 0: if attr_name in model_name_to_prefix.values(): A : List[str] = True break # Try again after removing the last word in the name A : Union[str, Any] = ''''''.join(camel_case_split(lowercase_ )[:-1] ) # Let's build that table! A : List[Any] = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) A : Union[str, Any] = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). A : List[str] = [len(lowercase_ ) + 2 for c in columns] A : Optional[Any] = max([len(lowercase_ ) for name in model_names] ) + 2 # Build the table per se A : List[Any] = '''|''' + '''|'''.join([_center_text(lowercase_ , lowercase_ ) for c, w in zip(lowercase_ , lowercase_ )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" A : Optional[Any] = {True: '''✅''', False: '''❌'''} for name in model_names: A : Dict = model_name_to_prefix[name] A : List[Any] = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(lowercase_ , lowercase_ ) for l, w in zip(lowercase_ , lowercase_ )] ) + "|\n" return table def snake_case__ ( lowerCamelCase_=False ): A , A , A , A : Union[str, Any] = _find_text_in_file( filename=os.path.join(lowercase_ , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) A : Dict = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(lowercase_ , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": lowercase : Optional[Any] = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") lowercase : Optional[Any] = parser.parse_args() check_model_table(args.fix_and_overwrite)
542
import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase : Dict = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_sentencepiece_available(): import sentencepiece as sp _lowerCamelCase : str = 5 _lowerCamelCase : int = 10 @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = SpeechaTextTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = True def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' super().setUp() A__ = sp.SentencePieceProcessor() spm_model.Load(UpperCAmelCase__) A__ = ['''<s>''', '''<pad>''', '''</s>''', '''<unk>'''] vocab += [spm_model.IdToPiece(id_) for id_ in range(len(UpperCAmelCase__))] A__ = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__)))) A__ = Path(self.tmpdirname) save_json(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''vocab_file''']) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''spm_file''']) A__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' A__ = '''<pad>''' A__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__) , UpperCAmelCase__) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__) , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<s>''') self.assertEqual(vocab_keys[1] , '''<pad>''') self.assertEqual(vocab_keys[-1] , '''j''') self.assertEqual(len(UpperCAmelCase__) , 1_001) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[str]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_001) def SCREAMING_SNAKE_CASE ( self : int) ->List[str]: '''simple docstring''' A__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname) A__ = tokenizer.tokenize('''This is a test''') self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__) , [289, 50, 14, 174, 386] , ) A__ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( UpperCAmelCase__ , [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''', '''é''', '''.'''] , ) A__ = tokenizer.convert_tokens_to_ids(UpperCAmelCase__) self.assertListEqual(UpperCAmelCase__ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8]) A__ = tokenizer.convert_ids_to_tokens(UpperCAmelCase__) self.assertListEqual( UpperCAmelCase__ , [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>''', '''.'''] , ) @slow def SCREAMING_SNAKE_CASE ( self : int) ->List[Any]: '''simple docstring''' A__ = {'''input_ids''': [[3_791, 797, 31, 11, 64, 797, 31, 2_429, 433, 12, 1_176, 12, 20, 786, 915, 142, 2_413, 240, 37, 3_238, 797, 31, 11, 35, 93, 915, 142, 2_413, 240, 37, 5_540, 567, 1_276, 93, 37, 610, 40, 62, 455, 657, 1_042, 123, 780, 177, 37, 309, 241, 1_298, 514, 20, 292, 2_737, 114, 2_469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3_388, 511, 459, 4, 3_555, 40, 321, 302, 705, 4, 3_388, 511, 583, 326, 5, 5, 5, 62, 3_310, 560, 177, 2_680, 217, 1_508, 32, 31, 853, 418, 64, 583, 511, 1_605, 62, 35, 93, 560, 177, 2_680, 217, 1_508, 1_521, 64, 583, 511, 519, 62, 20, 1_515, 764, 20, 149, 261, 5_625, 7_972, 20, 5_540, 567, 1_276, 93, 3_925, 1_675, 11, 15, 802, 7_972, 576, 217, 1_508, 11, 35, 93, 1_253, 2_441, 15, 289, 652, 31, 416, 321, 3_842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2_681, 1_153, 3_434, 20, 5_540, 37, 567, 126, 1_253, 2_441, 3_376, 449, 210, 431, 1_563, 177, 767, 5_540, 11, 1_203, 472, 11, 2_953, 685, 285, 364, 706, 1_153, 20, 6_799, 20, 2_869, 20, 4_464, 126, 40, 2_429, 20, 1_040, 866, 2_664, 418, 20, 318, 20, 1_726, 186, 20, 265, 522, 35, 93, 2_191, 4_634, 20, 1_040, 12, 6_799, 15, 228, 2_356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2_575, 2_666, 684, 1_582, 1_176, 12, 627, 149, 619, 20, 4_902, 563, 11, 20, 149, 261, 3_420, 2_356, 174, 142, 4_714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''facebook/s2t-small-mustc-en-de-st''' , revision='''a14f04cf0776c02f62a8cb800cf7909e15ea23ad''' , ) @require_sentencepiece class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = '''valhalla/s2t_mustc_multilinguial_medium''' UpperCAmelCase__ = '''C\'est trop cool''' UpperCAmelCase__ = '''Esto es genial''' @classmethod def SCREAMING_SNAKE_CASE ( cls : Dict) ->Dict: '''simple docstring''' A__ = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name) return cls def SCREAMING_SNAKE_CASE ( self : str) ->Dict: '''simple docstring''' self.assertEqual(self.tokenizer.lang_code_to_id['''pt'''] , 4) self.assertEqual(self.tokenizer.lang_code_to_id['''ru'''] , 6) self.assertEqual(self.tokenizer.lang_code_to_id['''it'''] , 9) self.assertEqual(self.tokenizer.lang_code_to_id['''de'''] , 11) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Dict: '''simple docstring''' self.assertEqual(self.tokenizer.vocab_size , 10_000) def SCREAMING_SNAKE_CASE ( self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertIn(UpperCAmelCase__ , self.tokenizer.all_special_ids) A__ = [ES_CODE, 4, 1_601, 47, 7_647, 2] A__ = self.tokenizer.decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__) A__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCAmelCase__) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__) self.assertNotIn(self.tokenizer.eos_token , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->str: '''simple docstring''' A__ = '''fr''' A__ = self.tokenizer(self.french_text).input_ids self.assertEqual(encoded[0] , UpperCAmelCase__) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->int: '''simple docstring''' A__ = '''fr''' self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE]) A__ = '''es''' self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE])
87
0
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = 42 SCREAMING_SNAKE_CASE__ : Any = 42 class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 42 SCREAMING_SNAKE_CASE__ : Any = (16, 32, 96, 256) SCREAMING_SNAKE_CASE__ : Optional[int] = jnp.floataa def __UpperCAmelCase ( self : List[str] ): """simple docstring""" _snake_case : List[str] = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) _snake_case : str = [] for i in range(len(self.block_out_channels ) - 1 ): _snake_case : List[Any] = self.block_out_channels[i] _snake_case : int = self.block_out_channels[i + 1] _snake_case : Dict = nn.Conv( UpperCAmelCase__ , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(UpperCAmelCase__ ) _snake_case : str = nn.Conv( UpperCAmelCase__ , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(UpperCAmelCase__ ) _snake_case : int = blocks _snake_case : Tuple = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : int , snake_case : str ): """simple docstring""" _snake_case : Any = self.conv_in(UpperCAmelCase__ ) _snake_case : List[str] = nn.silu(UpperCAmelCase__ ) for block in self.blocks: _snake_case : Optional[int] = block(UpperCAmelCase__ ) _snake_case : List[str] = nn.silu(UpperCAmelCase__ ) _snake_case : str = self.conv_out(UpperCAmelCase__ ) return embedding @flax_register_to_config class SCREAMING_SNAKE_CASE ( nn.Module ,UpperCAmelCase__ ,UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = 32 SCREAMING_SNAKE_CASE__ : Optional[Any] = 4 SCREAMING_SNAKE_CASE__ : Any = ( '''CrossAttnDownBlock2D''', '''CrossAttnDownBlock2D''', '''CrossAttnDownBlock2D''', '''DownBlock2D''', ) SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : List[str] = (320, 640, 1_280, 1_280) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : List[str] = 8 SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 1_280 SCREAMING_SNAKE_CASE__ : int = 0.0 SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Any = jnp.floataa SCREAMING_SNAKE_CASE__ : Tuple = True SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Dict = '''rgb''' SCREAMING_SNAKE_CASE__ : Optional[Any] = (16, 32, 96, 256) def __UpperCAmelCase ( self : Optional[Any] , snake_case : jax.random.KeyArray ): """simple docstring""" _snake_case : Optional[Any] = (1, self.in_channels, self.sample_size, self.sample_size) _snake_case : List[str] = jnp.zeros(UpperCAmelCase__ , dtype=jnp.floataa ) _snake_case : Any = jnp.ones((1,) , dtype=jnp.intaa ) _snake_case : List[str] = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) _snake_case : Dict = (1, 3, self.sample_size * 8, self.sample_size * 8) _snake_case : Optional[int] = jnp.zeros(UpperCAmelCase__ , dtype=jnp.floataa ) _snake_case , _snake_case : Union[str, Any] = jax.random.split(UpperCAmelCase__ ) _snake_case : Optional[Any] = {'params': params_rng, 'dropout': dropout_rng} return self.init(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )["params"] def __UpperCAmelCase ( self : Optional[int] ): """simple docstring""" _snake_case : Any = self.block_out_channels _snake_case : Union[str, Any] = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. _snake_case : int = self.num_attention_heads or self.attention_head_dim # input _snake_case : Tuple = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time _snake_case : Union[str, Any] = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) _snake_case : List[str] = FlaxTimestepEmbedding(UpperCAmelCase__ , dtype=self.dtype ) _snake_case : List[str] = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) _snake_case : List[str] = self.only_cross_attention if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _snake_case : Optional[int] = (only_cross_attention,) * len(self.down_block_types ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _snake_case : List[Any] = (num_attention_heads,) * len(self.down_block_types ) # down _snake_case : Tuple = [] _snake_case : str = [] _snake_case : List[str] = block_out_channels[0] _snake_case : Dict = nn.Conv( UpperCAmelCase__ , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(UpperCAmelCase__ ) for i, down_block_type in enumerate(self.down_block_types ): _snake_case : List[Any] = output_channel _snake_case : Dict = block_out_channels[i] _snake_case : Union[str, Any] = i == len(UpperCAmelCase__ ) - 1 if down_block_type == "CrossAttnDownBlock2D": _snake_case : Any = FlaxCrossAttnDownBlockaD( in_channels=UpperCAmelCase__ , out_channels=UpperCAmelCase__ , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: _snake_case : Dict = FlaxDownBlockaD( in_channels=UpperCAmelCase__ , out_channels=UpperCAmelCase__ , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(UpperCAmelCase__ ) for _ in range(self.layers_per_block ): _snake_case : Tuple = nn.Conv( UpperCAmelCase__ , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(UpperCAmelCase__ ) if not is_final_block: _snake_case : Optional[Any] = nn.Conv( UpperCAmelCase__ , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(UpperCAmelCase__ ) _snake_case : Union[str, Any] = down_blocks _snake_case : int = controlnet_down_blocks # mid _snake_case : Union[str, Any] = block_out_channels[-1] _snake_case : Optional[Any] = FlaxUNetMidBlockaDCrossAttn( in_channels=UpperCAmelCase__ , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) _snake_case : Any = nn.Conv( UpperCAmelCase__ , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : List[str] , snake_case : Tuple , snake_case : Optional[int] , snake_case : Any , snake_case : int , snake_case : float = 1.0 , snake_case : bool = True , snake_case : bool = False , ): """simple docstring""" _snake_case : str = self.controlnet_conditioning_channel_order if channel_order == "bgr": _snake_case : Any = jnp.flip(UpperCAmelCase__ , axis=1 ) # 1. time if not isinstance(UpperCAmelCase__ , jnp.ndarray ): _snake_case : List[Any] = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(UpperCAmelCase__ , jnp.ndarray ) and len(timesteps.shape ) == 0: _snake_case : List[Any] = timesteps.astype(dtype=jnp.floataa ) _snake_case : Optional[int] = jnp.expand_dims(UpperCAmelCase__ , 0 ) _snake_case : Any = self.time_proj(UpperCAmelCase__ ) _snake_case : str = self.time_embedding(UpperCAmelCase__ ) # 2. pre-process _snake_case : Tuple = jnp.transpose(UpperCAmelCase__ , (0, 2, 3, 1) ) _snake_case : int = self.conv_in(UpperCAmelCase__ ) _snake_case : Union[str, Any] = jnp.transpose(UpperCAmelCase__ , (0, 2, 3, 1) ) _snake_case : int = self.controlnet_cond_embedding(UpperCAmelCase__ ) sample += controlnet_cond # 3. down _snake_case : Any = (sample,) for down_block in self.down_blocks: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _snake_case , _snake_case : List[Any] = down_block(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , deterministic=not train ) else: _snake_case , _snake_case : int = down_block(UpperCAmelCase__ , UpperCAmelCase__ , deterministic=not train ) down_block_res_samples += res_samples # 4. mid _snake_case : Union[str, Any] = self.mid_block(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , deterministic=not train ) # 5. contronet blocks _snake_case : Union[str, Any] = () for down_block_res_sample, controlnet_block in zip(UpperCAmelCase__ , self.controlnet_down_blocks ): _snake_case : Dict = controlnet_block(UpperCAmelCase__ ) controlnet_down_block_res_samples += (down_block_res_sample,) _snake_case : Tuple = controlnet_down_block_res_samples _snake_case : List[str] = self.controlnet_mid_block(UpperCAmelCase__ ) # 6. scaling _snake_case : List[Any] = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=UpperCAmelCase__ , mid_block_res_sample=UpperCAmelCase__ )
517
from __future__ import annotations import requests def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" A__ = f"""https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty""" return requests.get(lowercase_ ).json() def SCREAMING_SNAKE_CASE ( lowercase_ = 10 ) -> list[dict]: """simple docstring""" A__ = '''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty''' A__ = requests.get(lowercase_ ).json()[:max_stories] return [get_hackernews_story(lowercase_ ) for story_id in story_ids] def SCREAMING_SNAKE_CASE ( lowercase_ = 10 ) -> str: """simple docstring""" A__ = hackernews_top_stories(lowercase_ ) return "\n".join('''* [{title}]({url})'''.format(**lowercase_ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
87
0
'''simple docstring''' from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING _lowerCAmelCase = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class _SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): def __init__( self : str , *a__ : Tuple , **a__ : int ): super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) requires_backends(self , '''decord''' ) self.check_model_type(UpperCAmelCase__ ) def snake_case__ ( self : Tuple , a__ : List[Any]=None , a__ : Optional[Any]=None , a__ : List[Any]=None ): __magic_name__ = {} if frame_sampling_rate is not None: __magic_name__ = frame_sampling_rate if num_frames is not None: __magic_name__ = num_frames __magic_name__ = {} if top_k is not None: __magic_name__ = top_k return preprocess_params, {}, postprocess_params def __call__( self : str , a__ : Union[str, List[str]] , **a__ : Optional[int] ): return super().__call__(UpperCAmelCase__ , **UpperCAmelCase__ ) def snake_case__ ( self : Tuple , a__ : Optional[int] , a__ : Tuple=None , a__ : List[Any]=1 ): if num_frames is None: __magic_name__ = self.model.config.num_frames if video.startswith('''http://''' ) or video.startswith('''https://''' ): __magic_name__ = BytesIO(requests.get(UpperCAmelCase__ ).content ) __magic_name__ = VideoReader(UpperCAmelCase__ ) videoreader.seek(0 ) __magic_name__ = 0 __magic_name__ = num_frames * frame_sampling_rate - 1 __magic_name__ = np.linspace(UpperCAmelCase__ , UpperCAmelCase__ , num=UpperCAmelCase__ , dtype=np.intaa ) __magic_name__ = videoreader.get_batch(UpperCAmelCase__ ).asnumpy() __magic_name__ = list(UpperCAmelCase__ ) __magic_name__ = self.image_processor(UpperCAmelCase__ , return_tensors=self.framework ) return model_inputs def snake_case__ ( self : Any , a__ : Dict ): __magic_name__ = self.model(**UpperCAmelCase__ ) return model_outputs def snake_case__ ( self : int , a__ : Optional[int] , a__ : str=5 ): if top_k > self.model.config.num_labels: __magic_name__ = self.model.config.num_labels if self.framework == "pt": __magic_name__ = model_outputs.logits.softmax(-1 )[0] __magic_name__ , __magic_name__ = probs.topk(UpperCAmelCase__ ) else: raise ValueError(F'''Unsupported framework: {self.framework}''' ) __magic_name__ = scores.tolist() __magic_name__ = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(UpperCAmelCase__ , UpperCAmelCase__ )]
432
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType _lowerCamelCase : Optional[List[str]] = None _lowerCamelCase : int = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image _lowerCamelCase : Union[str, Any] = [ np.dtype("""|b1"""), np.dtype("""|u1"""), np.dtype("""<u2"""), np.dtype(""">u2"""), np.dtype("""<i2"""), np.dtype(""">i2"""), np.dtype("""<u4"""), np.dtype(""">u4"""), np.dtype("""<i4"""), np.dtype(""">i4"""), np.dtype("""<f4"""), np.dtype(""">f4"""), np.dtype("""<f8"""), np.dtype(""">f8"""), ] @dataclass class UpperCamelCase_ : '''simple docstring''' UpperCAmelCase__ = True UpperCAmelCase__ = None # Automatically constructed UpperCAmelCase__ = "PIL.Image.Image" UpperCAmelCase__ = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) UpperCAmelCase__ = field(default='''Image''' , init=UpperCAmelCase__ , repr=UpperCAmelCase__ ) def __call__( self : List[str]) ->List[str]: '''simple docstring''' return self.pa_type def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"]) ->dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''') if isinstance(UpperCAmelCase__ , UpperCAmelCase__): A__ = np.array(UpperCAmelCase__) if isinstance(UpperCAmelCase__ , UpperCAmelCase__): return {"path": value, "bytes": None} elif isinstance(UpperCAmelCase__ , UpperCAmelCase__): return {"path": None, "bytes": value} elif isinstance(UpperCAmelCase__ , np.ndarray): # convert the image array to PNG/TIFF bytes return encode_np_array(UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , PIL.Image.Image): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(UpperCAmelCase__) 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 return {"bytes": None, "path": value.get('''path''')} elif value.get('''bytes''') is not None or value.get('''path''') is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get('''bytes'''), "path": value.get('''path''')} else: raise ValueError( f"""An image sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""") def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : dict , UpperCAmelCase__ : str=None) ->"PIL.Image.Image": '''simple docstring''' if not self.decode: raise RuntimeError('''Decoding is disabled for this feature. Please use Image(decode=True) instead.''') if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support decoding images, please install \'Pillow\'.''') if token_per_repo_id is None: A__ = {} A__ , A__ = value['''path'''], value['''bytes'''] if bytes_ is None: if path is None: raise ValueError(f"""An image should have one of 'path' or 'bytes' but both are None in {value}.""") else: if is_local_path(UpperCAmelCase__): A__ = PIL.Image.open(UpperCAmelCase__) else: A__ = path.split('''::''')[-1] try: A__ = string_to_dict(UpperCAmelCase__ , config.HUB_DATASETS_URL)['''repo_id'''] A__ = token_per_repo_id.get(UpperCAmelCase__) except ValueError: A__ = None with xopen(UpperCAmelCase__ , '''rb''' , use_auth_token=UpperCAmelCase__) as f: A__ = BytesIO(f.read()) A__ = PIL.Image.open(bytes_) else: A__ = PIL.Image.open(BytesIO(bytes_)) image.load() # to avoid "Too many open files" errors return image def SCREAMING_SNAKE_CASE ( self : Dict) ->Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Value return ( self if self.decode else { "bytes": Value('''binary'''), "path": Value('''string'''), } ) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[pa.StringArray, pa.StructArray, pa.ListArray]) ->pa.StructArray: '''simple docstring''' if pa.types.is_string(storage.type): A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.binary()) A__ = pa.StructArray.from_arrays([bytes_array, storage] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_binary(storage.type): A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays([storage, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_struct(storage.type): if storage.type.get_field_index('''bytes''') >= 0: A__ = storage.field('''bytes''') else: A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.binary()) if storage.type.get_field_index('''path''') >= 0: A__ = storage.field('''path''') else: A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_list(storage.type): A__ = pa.array( [encode_np_array(np.array(UpperCAmelCase__))['''bytes'''] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null()) return array_cast(UpperCAmelCase__ , self.pa_type) def SCREAMING_SNAKE_CASE ( self : List[Any] , UpperCAmelCase__ : pa.StructArray) ->pa.StructArray: '''simple docstring''' @no_op_if_value_is_null def path_to_bytes(UpperCAmelCase__ : Dict): with xopen(UpperCAmelCase__ , '''rb''') as f: A__ = f.read() return bytes_ A__ = 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() , ) A__ = pa.array( [os.path.basename(UpperCAmelCase__) if path is not None else None for path in storage.field('''path''').to_pylist()] , type=pa.string() , ) A__ = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null()) return array_cast(UpperCAmelCase__ , self.pa_type) def SCREAMING_SNAKE_CASE ( ) -> List[str]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() A__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def SCREAMING_SNAKE_CASE ( lowercase_ ) -> bytes: """simple docstring""" A__ = BytesIO() if image.format in list_image_compression_formats(): A__ = image.format else: A__ = '''PNG''' if image.mode in ['''1''', '''L''', '''LA''', '''RGB''', '''RGBA'''] else '''TIFF''' image.save(lowercase_ , format=lowercase_ ) return buffer.getvalue() def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" if hasattr(lowercase_ , '''filename''' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(lowercase_ )} def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) A__ = array.dtype A__ = dtype.byteorder if dtype.byteorder != '''=''' else _NATIVE_BYTEORDER A__ = dtype.kind A__ = dtype.itemsize A__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: A__ = np.dtype('''|u1''' ) if dtype_kind not in ["u", "i"]: raise TypeError( f"""Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.""" ) if dtype is not dest_dtype: warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: A__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: A__ = dtype_byteorder + dtype_kind + str(lowercase_ ) A__ = np.dtype(lowercase_ ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f"""Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}""" ) A__ = PIL.Image.fromarray(array.astype(lowercase_ ) ) return {"path": None, "bytes": image_to_bytes(lowercase_ )} def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[dict]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) if objs: A__ , A__ = first_non_null_value(lowercase_ ) if isinstance(lowercase_ , lowercase_ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(lowercase_ , np.ndarray ): A__ = no_op_if_value_is_null(lowercase_ ) return [obj_to_image_dict_func(lowercase_ ) for obj in objs] elif isinstance(lowercase_ , PIL.Image.Image ): A__ = no_op_if_value_is_null(lowercase_ ) return [obj_to_image_dict_func(lowercase_ ) for obj in objs] else: return objs else: return objs
87
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Optional[int] = { """MIT/ast-finetuned-audioset-10-10-0.4593""": ( """https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json""" ), } class _snake_case ( UpperCAmelCase__ ): lowerCAmelCase_ : Optional[int] = "audio-spectrogram-transformer" def __init__( self , a__=768 , a__=12 , a__=12 , a__=3_072 , a__="gelu" , a__=0.0 , a__=0.0 , a__=0.0_2 , a__=1e-12 , a__=16 , a__=True , a__=10 , a__=10 , a__=1_024 , a__=128 , **a__ , ) -> Optional[Any]: '''simple docstring''' super().__init__(**UpperCAmelCase__ ) snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = patch_size snake_case_ = qkv_bias snake_case_ = frequency_stride snake_case_ = time_stride snake_case_ = max_length snake_case_ = num_mel_bins
400
from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) UpperCAmelCase__ = ( { '''feature-extraction''': TFMobileBertModel, '''fill-mask''': TFMobileBertForMaskedLM, '''question-answering''': TFMobileBertForQuestionAnswering, '''text-classification''': TFMobileBertForSequenceClassification, '''token-classification''': TFMobileBertForTokenClassification, '''zero-shot''': TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase__ = False UpperCAmelCase__ = False def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str=False) ->Optional[Any]: '''simple docstring''' A__ = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__) if return_labels: if model_class in get_values(UpperCAmelCase__): A__ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa) return inputs_dict class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int=13 , UpperCAmelCase__ : str=7 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=99 , UpperCAmelCase__ : List[str]=32 , UpperCAmelCase__ : Optional[int]=32 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Optional[Any]=37 , UpperCAmelCase__ : Optional[int]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : List[Any]=512 , UpperCAmelCase__ : Tuple=16 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : Dict=0.02 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Tuple=None , ) ->Any: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = use_token_type_ids A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = type_vocab_size A__ = type_sequence_label_size A__ = initializer_range A__ = num_labels A__ = num_choices A__ = scope A__ = embedding_size def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Tuple: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) A__ = None if self.use_token_type_ids: A__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) A__ = None A__ = None A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size] , self.type_sequence_label_size) A__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) A__ = ids_tensor([self.batch_size] , self.num_choices) A__ = MobileBertConfig( 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 , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any]) ->Any: '''simple docstring''' A__ = TFMobileBertModel(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) A__ = [input_ids, input_mask] A__ = model(UpperCAmelCase__) A__ = model(UpperCAmelCase__) 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 SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Tuple) ->Optional[Any]: '''simple docstring''' A__ = TFMobileBertForMaskedLM(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any]) ->int: '''simple docstring''' A__ = TFMobileBertForNextSentencePrediction(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int) ->List[Any]: '''simple docstring''' A__ = TFMobileBertForPreTraining(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) 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 SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple) ->Dict: '''simple docstring''' A__ = self.num_labels A__ = TFMobileBertForSequenceClassification(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int) ->Dict: '''simple docstring''' A__ = self.num_choices A__ = TFMobileBertForMultipleChoice(config=UpperCAmelCase__) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1) , (1, self.num_choices, 1)) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1) , (1, self.num_choices, 1)) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 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(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int]) ->int: '''simple docstring''' A__ = self.num_labels A__ = TFMobileBertForTokenClassification(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any]) ->Union[str, Any]: '''simple docstring''' A__ = TFMobileBertForQuestionAnswering(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def SCREAMING_SNAKE_CASE ( self : Any) ->str: '''simple docstring''' A__ = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = config_and_inputs A__ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE ( self : Any) ->Union[str, Any]: '''simple docstring''' A__ = TFMobileBertModelTest.TFMobileBertModelTester(self) A__ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[str]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*UpperCAmelCase__) @slow def SCREAMING_SNAKE_CASE ( self : str) ->List[Any]: '''simple docstring''' for model_name in ["google/mobilebert-uncased"]: A__ = TFMobileBertModel.from_pretrained(UpperCAmelCase__) self.assertIsNotNone(UpperCAmelCase__) @require_tf class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Any: '''simple docstring''' A__ = TFMobileBertForPreTraining.from_pretrained('''google/mobilebert-uncased''') A__ = tf.constant([[0, 1, 2, 3, 4, 5]]) A__ = model(UpperCAmelCase__)[0] A__ = [1, 6, 30_522] self.assertEqual(output.shape , UpperCAmelCase__) A__ = tf.constant( [ [ [-4.5919547, -9.248295, -9.645256], [-6.7306175, -6.440284, -6.6052837], [-7.2743506, -6.7847915, -6.024673], ] ]) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4)
87
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) snake_case_ : int = {"""configuration_vit""": ["""VIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTConfig""", """ViTOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Optional[Any] = ["""ViTFeatureExtractor"""] snake_case_ : Optional[Any] = ["""ViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Tuple = [ """VIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ViTForImageClassification""", """ViTForMaskedImageModeling""", """ViTModel""", """ViTPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : str = [ """TFViTForImageClassification""", """TFViTModel""", """TFViTPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : List[Any] = [ """FlaxViTForImageClassification""", """FlaxViTModel""", """FlaxViTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys snake_case_ : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
138
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int=13 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : str=224 , UpperCAmelCase__ : str=30 , UpperCAmelCase__ : Tuple=400 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Union[str, Any]=[0.5, 0.5, 0.5] , UpperCAmelCase__ : Tuple=[0.5, 0.5, 0.5] , ) ->str: '''simple docstring''' A__ = size if size is not None else {'''height''': 18, '''width''': 18} A__ = parent A__ = batch_size A__ = num_channels A__ = image_size A__ = min_resolution A__ = max_resolution A__ = do_resize A__ = size A__ = do_normalize A__ = image_mean A__ = image_std def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = ViTImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE ( self : List[str]) ->str: '''simple docstring''' A__ = EfficientFormerImageProcessorTester(self) @property def SCREAMING_SNAKE_CASE ( self : Dict) ->int: '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Dict: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_mean''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_std''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_normalize''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''')) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Dict: '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self : str) ->Optional[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random PIL images A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , torch.Tensor) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
87
0
import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset __magic_name__: Any = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class snake_case__ ( nn.Module ): def __init__( self , lowerCAmelCase__ ) -> Any: super().__init__() __magic_name__ : Union[str, Any] = torchvision.models.resnetaaa(pretrained=UpperCAmelCase__ ) __magic_name__ : Dict = list(model.children() )[:-2] __magic_name__ : Optional[Any] = nn.Sequential(*UpperCAmelCase__ ) __magic_name__ : Tuple = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] ) def __magic_name__ ( self , lowerCAmelCase__ ) -> int: __magic_name__ : Any = self.pool(self.model(UpperCAmelCase__ ) ) __magic_name__ : Optional[int] = torch.flatten(UpperCAmelCase__ , start_dim=2 ) __magic_name__ : Union[str, Any] = out.transpose(1 , 2 ).contiguous() return out # BxNx2048 class snake_case__ ( UpperCAmelCase__ ): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Tuple: __magic_name__ : Tuple = [json.loads(UpperCAmelCase__ ) for l in open(UpperCAmelCase__ )] __magic_name__ : Optional[int] = os.path.dirname(UpperCAmelCase__ ) __magic_name__ : Tuple = tokenizer __magic_name__ : int = labels __magic_name__ : List[Any] = len(UpperCAmelCase__ ) __magic_name__ : Tuple = max_seq_length __magic_name__ : Optional[Any] = transforms def __len__( self ) -> Any: return len(self.data ) def __getitem__( self , lowerCAmelCase__ ) -> str: __magic_name__ : Union[str, Any] = torch.LongTensor(self.tokenizer.encode(self.data[index]["""text"""] , add_special_tokens=UpperCAmelCase__ ) ) __magic_name__ ,__magic_name__ ,__magic_name__ : Dict = sentence[0], sentence[1:-1], sentence[-1] __magic_name__ : Optional[Any] = sentence[: self.max_seq_length] __magic_name__ : Dict = torch.zeros(self.n_classes ) __magic_name__ : List[Any] = 1 __magic_name__ : Optional[Any] = Image.open(os.path.join(self.data_dir , self.data[index]["""img"""] ) ).convert("""RGB""" ) __magic_name__ : List[str] = self.transforms(UpperCAmelCase__ ) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def __magic_name__ ( self ) -> List[str]: __magic_name__ : Tuple = Counter() for row in self.data: label_freqs.update(row["""label"""] ) return label_freqs def UpperCamelCase ( _A ): """simple docstring""" __magic_name__ : List[str] = [len(row["""sentence"""] ) for row in batch] __magic_name__ ,__magic_name__ : List[Any] = len(lowercase_ ), max(lowercase_ ) __magic_name__ : int = torch.zeros(lowercase_, lowercase_, dtype=torch.long ) __magic_name__ : Dict = torch.zeros(lowercase_, lowercase_, dtype=torch.long ) for i_batch, (input_row, length) in enumerate(zip(lowercase_, lowercase_ ) ): __magic_name__ : Optional[int] = input_row["""sentence"""] __magic_name__ : List[Any] = 1 __magic_name__ : Union[str, Any] = torch.stack([row["""image"""] for row in batch] ) __magic_name__ : List[str] = torch.stack([row["""label"""] for row in batch] ) __magic_name__ : List[str] = torch.stack([row["""image_start_token"""] for row in batch] ) __magic_name__ : Union[str, Any] = torch.stack([row["""image_end_token"""] for row in batch] ) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def UpperCamelCase ( ): """simple docstring""" return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def UpperCamelCase ( ): """simple docstring""" return transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize( mean=[0.46777044, 0.44531429, 0.40661017], std=[0.12221994, 0.12145835, 0.14380469], ), ] )
324
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance _lowerCamelCase : Dict = 6_378_137.0 _lowerCamelCase : Union[str, Any] = 6_356_752.314_245 _lowerCamelCase : List[Any] = 6378137 def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> float: """simple docstring""" A__ = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude A__ = atan((1 - flattening) * tan(radians(lowercase_ ) ) ) A__ = atan((1 - flattening) * tan(radians(lowercase_ ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius A__ = haversine_distance(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) / EQUATORIAL_RADIUS # Intermediate P and Q values A__ = (b_lata + b_lata) / 2 A__ = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) A__ = (sin(lowercase_ ) ** 2) * (cos(lowercase_ ) ** 2) A__ = cos(sigma / 2 ) ** 2 A__ = (sigma - sin(lowercase_ )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) A__ = (cos(lowercase_ ) ** 2) * (sin(lowercase_ ) ** 2) A__ = sin(sigma / 2 ) ** 2 A__ = (sigma + sin(lowercase_ )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
87
0
from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class lowerCamelCase (UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCamelCase__ = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) lowerCamelCase__ = ( { '''feature-extraction''': TFMobileBertModel, '''fill-mask''': TFMobileBertForMaskedLM, '''question-answering''': TFMobileBertForQuestionAnswering, '''text-classification''': TFMobileBertForSequenceClassification, '''token-classification''': TFMobileBertForTokenClassification, '''zero-shot''': TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False def __A ( self : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Tuple , __magic_name__ : str=False ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): SCREAMING_SNAKE_CASE_ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) return inputs_dict class lowerCamelCase (UpperCAmelCase__ ): """simple docstring""" def __init__( self : List[Any] , __magic_name__ : str , __magic_name__ : int=13 , __magic_name__ : str=7 , __magic_name__ : Optional[Any]=True , __magic_name__ : Optional[int]=True , __magic_name__ : Union[str, Any]=True , __magic_name__ : Optional[int]=True , __magic_name__ : str=99 , __magic_name__ : List[str]=32 , __magic_name__ : Optional[int]=32 , __magic_name__ : Any=2 , __magic_name__ : List[str]=4 , __magic_name__ : Optional[Any]=37 , __magic_name__ : Optional[int]="gelu" , __magic_name__ : Any=0.1 , __magic_name__ : Optional[Any]=0.1 , __magic_name__ : List[Any]=512 , __magic_name__ : Tuple=16 , __magic_name__ : Any=2 , __magic_name__ : Dict=0.02 , __magic_name__ : int=3 , __magic_name__ : List[str]=4 , __magic_name__ : Tuple=None , ) -> Any: SCREAMING_SNAKE_CASE_ = parent SCREAMING_SNAKE_CASE_ = batch_size SCREAMING_SNAKE_CASE_ = seq_length SCREAMING_SNAKE_CASE_ = is_training SCREAMING_SNAKE_CASE_ = use_input_mask SCREAMING_SNAKE_CASE_ = use_token_type_ids SCREAMING_SNAKE_CASE_ = use_labels SCREAMING_SNAKE_CASE_ = vocab_size SCREAMING_SNAKE_CASE_ = hidden_size SCREAMING_SNAKE_CASE_ = num_hidden_layers SCREAMING_SNAKE_CASE_ = num_attention_heads SCREAMING_SNAKE_CASE_ = intermediate_size SCREAMING_SNAKE_CASE_ = hidden_act SCREAMING_SNAKE_CASE_ = hidden_dropout_prob SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ = max_position_embeddings SCREAMING_SNAKE_CASE_ = type_vocab_size SCREAMING_SNAKE_CASE_ = type_sequence_label_size SCREAMING_SNAKE_CASE_ = initializer_range SCREAMING_SNAKE_CASE_ = num_labels SCREAMING_SNAKE_CASE_ = num_choices SCREAMING_SNAKE_CASE_ = scope SCREAMING_SNAKE_CASE_ = embedding_size def __A ( self : Optional[Any] ) -> Tuple: SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE_ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None if self.use_labels: SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE_ = MobileBertConfig( 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 , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : str , __magic_name__ : str , __magic_name__ : List[Any] , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] ) -> Any: SCREAMING_SNAKE_CASE_ = TFMobileBertModel(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = [input_ids, input_mask] SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) 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 __A ( self : List[str] , __magic_name__ : int , __magic_name__ : str , __magic_name__ : Any , __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : Any , __magic_name__ : Tuple ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ = TFMobileBertForMaskedLM(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self : Dict , __magic_name__ : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : List[Any] , __magic_name__ : Optional[Any] ) -> int: SCREAMING_SNAKE_CASE_ = TFMobileBertForNextSentencePrediction(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __A ( self : Dict , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : int ) -> List[Any]: SCREAMING_SNAKE_CASE_ = TFMobileBertForPreTraining(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) 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 __A ( self : Tuple , __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Any , __magic_name__ : Any , __magic_name__ : int , __magic_name__ : List[str] , __magic_name__ : Tuple ) -> Dict: SCREAMING_SNAKE_CASE_ = self.num_labels SCREAMING_SNAKE_CASE_ = TFMobileBertForSequenceClassification(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self : Any , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : str , __magic_name__ : Any , __magic_name__ : Optional[Any] , __magic_name__ : str , __magic_name__ : int ) -> Dict: SCREAMING_SNAKE_CASE_ = self.num_choices SCREAMING_SNAKE_CASE_ = TFMobileBertForMultipleChoice(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE_ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE_ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE_ = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self : Dict , __magic_name__ : Union[str, Any] , __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : List[Any] , __magic_name__ : Any , __magic_name__ : Dict , __magic_name__ : Optional[int] ) -> int: SCREAMING_SNAKE_CASE_ = self.num_labels SCREAMING_SNAKE_CASE_ = TFMobileBertForTokenClassification(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A ( self : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Tuple , __magic_name__ : Union[str, Any] , __magic_name__ : Any , __magic_name__ : Union[str, Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = TFMobileBertForQuestionAnswering(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __A ( self : Any ) -> str: 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, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict def __A ( self : Any ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = TFMobileBertModelTest.TFMobileBertModelTester(self ) SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37 ) def __A ( self : Tuple ) -> Optional[int]: self.config_tester.run_common_tests() def __A ( self : Optional[Any] ) -> Dict: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*UpperCAmelCase__ ) def __A ( self : List[str] ) -> Tuple: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*UpperCAmelCase__ ) def __A ( self : Union[str, Any] ) -> Dict: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*UpperCAmelCase__ ) def __A ( self : Tuple ) -> Dict: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*UpperCAmelCase__ ) def __A ( self : List[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*UpperCAmelCase__ ) def __A ( self : int ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*UpperCAmelCase__ ) def __A ( self : Tuple ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*UpperCAmelCase__ ) def __A ( self : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*UpperCAmelCase__ ) @slow def __A ( self : str ) -> List[Any]: for model_name in ["google/mobilebert-uncased"]: SCREAMING_SNAKE_CASE_ = TFMobileBertModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" @slow def __A ( self : Optional[Any] ) -> Any: SCREAMING_SNAKE_CASE_ = TFMobileBertForPreTraining.from_pretrained("google/mobilebert-uncased" ) SCREAMING_SNAKE_CASE_ = tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ )[0] SCREAMING_SNAKE_CASE_ = [1, 6, 30_522] self.assertEqual(output.shape , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = tf.constant( [ [ [-4.591_9547, -9.24_8295, -9.64_5256], [-6.730_6175, -6.44_0284, -6.605_2837], [-7.274_3506, -6.784_7915, -6.02_4673], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4 )
140
import heapq import sys import numpy as np _lowerCamelCase : Any = tuple[int, int] class UpperCamelCase_ : '''simple docstring''' def __init__( self : Any) ->str: '''simple docstring''' A__ = [] A__ = set() def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' if not self.empty(): return self.elements[0][0] else: return float('''inf''') def SCREAMING_SNAKE_CASE ( self : Tuple) ->str: '''simple docstring''' return len(self.elements) == 0 def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any]) ->List[str]: '''simple docstring''' if item not in self.set: heapq.heappush(self.elements , (priority, item)) self.set.add(UpperCAmelCase__) else: # update # print("update", item) A__ = [] ((A__) , (A__)) = heapq.heappop(self.elements) while x != item: temp.append((pri, x)) ((A__) , (A__)) = heapq.heappop(self.elements) temp.append((priority, item)) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx)) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : List[Any]) ->Union[str, Any]: '''simple docstring''' if item in self.set: self.set.remove(UpperCAmelCase__) A__ = [] ((A__) , (A__)) = heapq.heappop(self.elements) while x != item: temp.append((pro, x)) ((A__) , (A__)) = heapq.heappop(self.elements) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy)) def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[str]: '''simple docstring''' return self.elements[0][1] def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->int: '''simple docstring''' ((A__) , (A__)) = heapq.heappop(self.elements) self.set.remove(UpperCAmelCase__) return (priority, item) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = np.array(lowercase_ ) A__ = np.array(lowercase_ ) return np.linalg.norm(a - b ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" return consistent_heuristic(lowercase_ , lowercase_ ) // t def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Union[str, Any]: """simple docstring""" return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> Optional[int]: """simple docstring""" A__ = g_function[start] + Wa * heuristics[i](lowercase_ , lowercase_ ) return ans def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = np.chararray((n, n) ) for i in range(lowercase_ ): for j in range(lowercase_ ): A__ = '''*''' for i in range(lowercase_ ): for j in range(lowercase_ ): if (j, (n - 1) - i) in blocks: A__ = '''#''' A__ = '''-''' A__ = back_pointer[goal] while x != start: ((A__) , (A__)) = x # print(x) A__ = '''-''' A__ = back_pointer[x] A__ = '''-''' for i in range(lowercase_ ): for j in range(lowercase_ ): if (i, j) == (0, n - 1): print(grid[i][j] , end=''' ''' ) print('''<-- End position''' , end=''' ''' ) else: print(grid[i][j] , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) print('''PATH TAKEN BY THE ALGORITHM IS:-''' ) A__ = back_pointer[goal] while x != start: print(lowercase_ , end=''' ''' ) A__ = back_pointer[x] print(lowercase_ ) sys.exit() def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) -> Union[str, Any]: """simple docstring""" for itera in range(lowercase_ ): open_list[itera].remove_element(lowercase_ ) # print("s", s) # print("j", j) ((A__) , (A__)) = s A__ = (x - 1, y) A__ = (x + 1, y) A__ = (x, y + 1) A__ = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(lowercase_ ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(lowercase_ ) A__ = -1 A__ = float('''inf''' ) if valid(lowercase_ ) and g_function[neighbours] > g_function[s] + 1: A__ = g_function[s] + 1 A__ = s if neighbours not in close_list_anchor: open_list[0].put(lowercase_ , key(lowercase_ , 0 , lowercase_ , lowercase_ ) ) if neighbours not in close_list_inad: for var in range(1 , lowercase_ ): if key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) <= Wa * key( lowercase_ , 0 , lowercase_ , lowercase_ ): open_list[j].put( lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) def SCREAMING_SNAKE_CASE ( ) -> Optional[int]: """simple docstring""" A__ = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list _lowerCamelCase : Dict = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} _lowerCamelCase : Optional[Any] = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] _lowerCamelCase : Optional[int] = make_common_ground() _lowerCamelCase : Optional[Any] = blocks_blk # hyper parameters _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : List[Any] = 20 _lowerCamelCase : Any = 3 # one consistent and two other inconsistent # start and end destination _lowerCamelCase : str = (0, 0) _lowerCamelCase : Tuple = (n - 1, n - 1) _lowerCamelCase : int = 1 def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = {start: 0, goal: float('''inf''' )} A__ = {start: -1, goal: -1} A__ = [] A__ = set() for i in range(lowercase_ ): open_list.append(PriorityQueue() ) open_list[i].put(lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) A__ = [] A__ = [] while open_list[0].minkey() < float('''inf''' ): for i in range(1 , lowercase_ ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float('''inf''' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: A__ , A__ = open_list[i].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_inad.append(lowercase_ ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('''inf''' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: A__ = open_list[0].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , 0 , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_anchor.append(lowercase_ ) print('''No path found to goal''' ) print() for i in range(n - 1 , -1 , -1 ): for j in range(lowercase_ ): if (j, i) in blocks: print('''#''' , end=''' ''' ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print('''*''' , end=''' ''' ) else: print('''-''' , end=''' ''' ) else: print('''*''' , end=''' ''' ) if (j, i) == (n - 1, n - 1): print('''<-- End position''' , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
87
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.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class A( UpperCAmelCase__ ): """simple docstring""" A = "philschmid/bart-large-cnn-samsum" A = ( "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." ) A = "summarizer" A = AutoTokenizer A = AutoModelForSeqaSeqLM A = ["text"] A = ["text"] def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" return self.pre_processor(UpperCAmelCase__ , return_tensors='''pt''' , truncation=UpperCAmelCase__ ) def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" return self.model.generate(**UpperCAmelCase__ )[0] def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ ) -> str: """simple docstring""" return self.pre_processor.decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ )
355
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowerCamelCase : Optional[Any] = """Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine""" def SCREAMING_SNAKE_CASE ( ) -> Dict: """simple docstring""" A__ = _ask_options( '''In which compute environment are you running?''' , ['''This machine''', '''AWS (Amazon SageMaker)'''] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A__ = get_sagemaker_input() else: A__ = get_cluster_input() return config def SCREAMING_SNAKE_CASE ( lowercase_=None ) -> List[Any]: """simple docstring""" if subparsers is not None: A__ = subparsers.add_parser('''config''' , description=lowercase_ ) else: A__ = argparse.ArgumentParser('''Accelerate config command''' , description=lowercase_ ) parser.add_argument( '''--config_file''' , default=lowercase_ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=lowercase_ ) return parser def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Any: """simple docstring""" A__ = get_user_input() if args.config_file is not None: A__ = args.config_file else: if not os.path.isdir(lowercase_ ): os.makedirs(lowercase_ ) A__ = default_yaml_config_file if config_file.endswith('''.json''' ): config.to_json_file(lowercase_ ) else: config.to_yaml_file(lowercase_ ) print(f"""accelerate configuration saved at {config_file}""" ) def SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: """simple docstring""" A__ = config_command_parser() A__ = parser.parse_args() config_command(lowercase_ ) if __name__ == "__main__": main()
87
0
def UpperCamelCase__ ( UpperCAmelCase_ ) -> str: '''simple docstring''' return "".join(chr(ord(lowercase_ ) - 32 ) if '''a''' <= char <= '''z''' else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
322
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _lowerCamelCase : int = logging.get_logger("""transformers.models.speecht5""") def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Tuple: """simple docstring""" hf_model.apply_weight_norm() A__ = checkpoint['''input_conv.weight_g'''] A__ = checkpoint['''input_conv.weight_v'''] A__ = checkpoint['''input_conv.bias'''] for i in range(len(config.upsample_rates ) ): A__ = checkpoint[f"""upsamples.{i}.1.weight_g"""] A__ = checkpoint[f"""upsamples.{i}.1.weight_v"""] A__ = checkpoint[f"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_g"""] A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_v"""] A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.bias"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_g"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_v"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.bias"""] A__ = checkpoint['''output_conv.1.weight_g'''] A__ = checkpoint['''output_conv.1.weight_v'''] A__ = checkpoint['''output_conv.1.bias'''] hf_model.remove_weight_norm() @torch.no_grad() def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , ) -> str: """simple docstring""" if config_path is not None: A__ = SpeechTaHifiGanConfig.from_pretrained(lowercase_ ) else: A__ = SpeechTaHifiGanConfig() A__ = SpeechTaHifiGan(lowercase_ ) A__ = torch.load(lowercase_ ) load_weights(orig_checkpoint['''model''']['''generator'''] , lowercase_ , lowercase_ ) A__ = np.load(lowercase_ ) A__ = stats[0].reshape(-1 ) A__ = stats[1].reshape(-1 ) A__ = torch.from_numpy(lowercase_ ).float() A__ = torch.from_numpy(lowercase_ ).float() model.save_pretrained(lowercase_ ) if repo_id: print('''Pushing to the hub...''' ) model.push_to_hub(lowercase_ ) if __name__ == "__main__": _lowerCamelCase : Any = argparse.ArgumentParser() parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--stats_path""", required=True, default=None, type=str, help="""Path to stats.npy file""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) _lowerCamelCase : List[str] = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
87
0
"""simple docstring""" class snake_case : def __init__( self : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Union[str, Any])-> str: '''simple docstring''' __lowerCAmelCase: Union[str, Any] = name __lowerCAmelCase: Optional[int] = value __lowerCAmelCase: Dict = weight def __repr__( self : Any)-> Optional[Any]: '''simple docstring''' return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})" def lowercase_ ( self : int)-> int: '''simple docstring''' return self.value def lowercase_ ( self : Optional[int])-> str: '''simple docstring''' return self.name def lowercase_ ( self : Union[str, Any])-> Optional[int]: '''simple docstring''' return self.weight def lowercase_ ( self : Any)-> Optional[int]: '''simple docstring''' return self.value / self.weight def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> str: __lowerCAmelCase: Optional[int] = [] for i in range(len(lowercase_ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> str: __lowerCAmelCase: int = sorted(lowercase_ , key=lowercase_ , reverse=lowercase_ ) __lowerCAmelCase: Dict = [] __lowerCAmelCase , __lowerCAmelCase: List[str] = 0.0, 0.0 for i in range(len(lowercase_ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ) -> Any: pass if __name__ == "__main__": import doctest doctest.testmod()
346
import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class UpperCamelCase_ : '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict=13 , UpperCAmelCase__ : Dict=7 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=99 , UpperCAmelCase__ : Union[str, Any]=32 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : List[Any]=37 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=50 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : List[str]=None , ) ->Union[str, Any]: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = initializer_range A__ = use_labels A__ = scope def SCREAMING_SNAKE_CASE ( self : int) ->Any: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) if self.use_labels: A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = self.get_config() return config, input_ids, input_mask, token_labels def SCREAMING_SNAKE_CASE ( self : int) ->int: '''simple docstring''' return BertGenerationConfig( 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 , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Union[str, Any]: '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = self.prepare_config_and_inputs() A__ = True A__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) A__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , **UpperCAmelCase__ : List[Any] , ) ->Dict: '''simple docstring''' A__ = BertGenerationEncoder(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__) A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[Any] , ) ->Dict: '''simple docstring''' A__ = True A__ = BertGenerationEncoder(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Optional[int] , ) ->Any: '''simple docstring''' A__ = True A__ = True A__ = BertGenerationDecoder(config=UpperCAmelCase__).to(UpperCAmelCase__).eval() # first forward pass A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ , ) A__ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size) A__ = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and A__ = torch.cat([input_ids, next_tokens] , dim=-1) A__ = torch.cat([input_mask, next_mask] , dim=-1) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] # select random slice A__ = ids_tensor((1,) , output_from_past.shape[-1]).item() A__ = output_from_no_past[:, -3:, random_slice_idx].detach() A__ = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3)) def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , *UpperCAmelCase__ : List[str] , ) ->List[Any]: '''simple docstring''' A__ = BertGenerationDecoder(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->List[str]: '''simple docstring''' A__ , A__ , A__ , A__ = self.prepare_config_and_inputs() A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () UpperCAmelCase__ = (BertGenerationDecoder,) if is_torch_available() else () UpperCAmelCase__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Dict: '''simple docstring''' A__ = BertGenerationEncoderTester(self) A__ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any]) ->int: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Optional[Any]: '''simple docstring''' A__ , A__ , A__ , A__ = self.model_tester.prepare_config_and_inputs() A__ = '''bert''' self.model_tester.create_and_check_model(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any: '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() A__ = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*UpperCAmelCase__) @slow def SCREAMING_SNAKE_CASE ( self : Dict) ->List[Any]: '''simple docstring''' A__ = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') self.assertIsNotNone(UpperCAmelCase__) @require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Any) ->Union[str, Any]: '''simple docstring''' A__ = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') A__ = torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]) with torch.no_grad(): A__ = model(UpperCAmelCase__)[0] A__ = torch.Size([1, 8, 1_024]) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4)) @require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' A__ = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') A__ = torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]) with torch.no_grad(): A__ = model(UpperCAmelCase__)[0] A__ = torch.Size([1, 8, 50_358]) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4))
87
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE_ = { """configuration_blip""": [ """BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlipConfig""", """BlipTextConfig""", """BlipVisionConfig""", ], """processing_blip""": ["""BlipProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""BlipImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlipModel""", """BlipPreTrainedModel""", """BlipForConditionalGeneration""", """BlipForQuestionAnswering""", """BlipVisionModel""", """BlipTextModel""", """BlipForImageTextRetrieval""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBlipModel""", """TFBlipPreTrainedModel""", """TFBlipForConditionalGeneration""", """TFBlipForQuestionAnswering""", """TFBlipVisionModel""", """TFBlipTextModel""", """TFBlipForImageTextRetrieval""", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
373
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 _lowerCamelCase : int = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Dict: """simple docstring""" A__ = set() A__ = [] def parse_line(lowercase_ ): for line in fp: if isinstance(lowercase_ , lowercase_ ): A__ = 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(lowercase_ ) > 0: A__ = '''\n'''.join(lowercase_ ) # Only keep the warnings specified in `targets` if any(f""": {x}: """ in warning for x in targets ): selected_warnings.add(lowercase_ ) buffer.clear() continue else: A__ = line.strip() buffer.append(lowercase_ ) if from_gh: for filename in os.listdir(lowercase_ ): A__ = os.path.join(lowercase_ , lowercase_ ) if not os.path.isdir(lowercase_ ): # read the file if filename != "warnings.txt": continue with open(lowercase_ ) as fp: parse_line(lowercase_ ) else: try: with zipfile.ZipFile(lowercase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowercase_ ): # read the file if filename != "warnings.txt": continue with z.open(lowercase_ ) as fp: parse_line(lowercase_ ) 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 SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = set() A__ = [os.path.join(lowercase_ , lowercase_ ) for p in os.listdir(lowercase_ ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(lowercase_ , lowercase_ ) ) return selected_warnings if __name__ == "__main__": def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" return values.split(''',''' ) _lowerCamelCase : int = 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.""", ) _lowerCamelCase : List[Any] = parser.parse_args() _lowerCamelCase : List[str] = 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 _lowerCamelCase : 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("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts _lowerCamelCase : Any = extract_warnings(args.output_dir, args.targets) _lowerCamelCase : Optional[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)
87
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase : Optional[Any] = {"""configuration_yolos""": ["""YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """YolosConfig""", """YolosOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : str = ["""YolosFeatureExtractor"""] lowercase : Any = ["""YolosImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Union[str, Any] = [ """YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST""", """YolosForObjectDetection""", """YolosModel""", """YolosPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys lowercase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
542
class UpperCamelCase_ : # Public class to implement a graph '''simple docstring''' def __init__( self : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->None: '''simple docstring''' A__ = row A__ = col A__ = graph def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->bool: '''simple docstring''' return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->None: '''simple docstring''' A__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order A__ = [-1, 0, 1, -1, 1, -1, 0, 1] A__ = True # Make those cells visited for k in range(8): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__): self.diffs(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->int: # And finally, count all islands. '''simple docstring''' A__ = [[False for j in range(self.COL)] for i in range(self.ROW)] A__ = 0 for i in range(self.ROW): for j in range(self.COL): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) count += 1 return count
87
0
'''simple docstring''' import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class SCREAMING_SNAKE_CASE ( pl.LightningModule ): '''simple docstring''' def __init__( self : Optional[Any] , snake_case : Union[str, Any] ): """simple docstring""" super().__init__() _snake_case : int = model _snake_case : List[str] = 2 _snake_case : int = nn.Linear(self.model.config.hidden_size , self.num_labels ) def __UpperCAmelCase ( self : Optional[int] ): """simple docstring""" pass def lowerCamelCase__ ( a__ , a__ , a__) -> List[Any]: """simple docstring""" _snake_case : Optional[int] = LongformerModel.from_pretrained(lowercase_) _snake_case : Optional[int] = LightningModel(lowercase_) _snake_case : Any = torch.load(lowercase_ , map_location=torch.device('cpu')) lightning_model.load_state_dict(ckpt['state_dict']) # init longformer question answering model _snake_case : List[str] = LongformerForQuestionAnswering.from_pretrained(lowercase_) # 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(lowercase_) 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 )
517
from __future__ import annotations import requests _lowerCamelCase : str = set( """approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod_post category clicked content_categories created_utc downs edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta is_original_content is_reddit_media_domain is_video link_flair_css_class link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title name permalink pwls quarantine saved score secure_media secure_media_embed selftext subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type total_awards_received ups upvote_ratio url user_reports""".split() ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = 1 , lowercase_ = "new" , lowercase_ = None ) -> dict: """simple docstring""" A__ = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(lowercase_ ) - valid_terms ) ): A__ = f"""Invalid search term: {invalid_search_terms}""" raise ValueError(lowercase_ ) A__ = requests.get( f"""https://reddit.com/r/{subreddit}/{age}.json?limit={limit}""" , headers={'''User-agent''': '''A random string'''} , ) if response.status_code == 429: raise requests.HTTPError A__ = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(lowercase_ )} A__ = {} for id_ in range(lowercase_ ): A__ = { item: data['''data''']['''children'''][id_]['''data'''][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("""learnpython""", wanted_data=["""title""", """url""", """selftext"""]))
87
0
'''simple docstring''' 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 _SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE :Any = 1 __SCREAMING_SNAKE_CASE :Optional[int] = 2 __SCREAMING_SNAKE_CASE :List[Any] = 3 __SCREAMING_SNAKE_CASE :Dict = 4 __SCREAMING_SNAKE_CASE :Optional[Any] = 5 @dataclass class _SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE :str = 42 class _SCREAMING_SNAKE_CASE : __SCREAMING_SNAKE_CASE :Union[str, Any] = SCHEDULER_CONFIG_NAME __SCREAMING_SNAKE_CASE :Dict = ["""dtype"""] __SCREAMING_SNAKE_CASE :Dict = [] __SCREAMING_SNAKE_CASE :List[str] = True @classmethod def snake_case__ ( cls : List[Any] , a__ : Dict[str, Any] = None , a__ : Optional[str] = None , a__ : int=False , **a__ : Union[str, Any] , ): __magic_name__ , __magic_name__ = cls.load_config( pretrained_model_name_or_path=UpperCAmelCase__ , subfolder=UpperCAmelCase__ , return_unused_kwargs=UpperCAmelCase__ , **UpperCAmelCase__ , ) __magic_name__ , __magic_name__ = cls.from_config(UpperCAmelCase__ , return_unused_kwargs=UpperCAmelCase__ , **UpperCAmelCase__ ) if hasattr(UpperCAmelCase__ , '''create_state''' ) and getattr(UpperCAmelCase__ , '''has_state''' , UpperCAmelCase__ ): __magic_name__ = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def snake_case__ ( self : List[Any] , a__ : Union[str, os.PathLike] , a__ : bool = False , **a__ : Optional[Any] ): self.save_config(save_directory=UpperCAmelCase__ , push_to_hub=UpperCAmelCase__ , **UpperCAmelCase__ ) @property def snake_case__ ( self : Optional[int] ): return self._get_compatibles() @classmethod def snake_case__ ( cls : int ): __magic_name__ = list(set([cls.__name__] + cls._compatibles ) ) __magic_name__ = importlib.import_module(__name__.split('''.''' )[0] ) __magic_name__ = [ getattr(UpperCAmelCase__ , UpperCAmelCase__ ) for c in compatible_classes_str if hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) ] return compatible_classes def UpperCamelCase ( a , a ) -> jnp.ndarray: '''simple docstring''' assert len(lowercase_ ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(lowercase_ ) - x.ndim) ) , lowercase_ ) def UpperCamelCase ( a , a=0.9_99 , a=jnp.floataa ) -> jnp.ndarray: '''simple docstring''' def alpha_bar(a ): return math.cos((time_step + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 __magic_name__ = [] for i in range(lowercase_ ): __magic_name__ = i / num_diffusion_timesteps __magic_name__ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(lowercase_ ) / alpha_bar(lowercase_ ) , lowercase_ ) ) return jnp.array(lowercase_ , dtype=lowercase_ ) @flax.struct.dataclass class _SCREAMING_SNAKE_CASE : __SCREAMING_SNAKE_CASE :List[Any] = 42 __SCREAMING_SNAKE_CASE :int = 42 __SCREAMING_SNAKE_CASE :Any = 42 @classmethod def snake_case__ ( cls : Union[str, Any] , a__ : List[str] ): __magic_name__ = scheduler.config if config.trained_betas is not None: __magic_name__ = jnp.asarray(config.trained_betas , dtype=scheduler.dtype ) elif config.beta_schedule == "linear": __magic_name__ = 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. __magic_name__ = ( 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 __magic_name__ = 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__}''' ) __magic_name__ = 1.0 - betas __magic_name__ = jnp.cumprod(UpperCAmelCase__ , axis=0 ) return cls( alphas=UpperCAmelCase__ , betas=UpperCAmelCase__ , alphas_cumprod=UpperCAmelCase__ , ) def UpperCamelCase ( a , a , a , a ) -> List[str]: '''simple docstring''' __magic_name__ = state.alphas_cumprod __magic_name__ = alphas_cumprod[timesteps] ** 0.5 __magic_name__ = sqrt_alpha_prod.flatten() __magic_name__ = broadcast_to_shape_from_left(lowercase_ , original_samples.shape ) __magic_name__ = (1 - alphas_cumprod[timesteps]) ** 0.5 __magic_name__ = sqrt_one_minus_alpha_prod.flatten() __magic_name__ = broadcast_to_shape_from_left(lowercase_ , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def UpperCamelCase ( a , a , a , a ) -> List[str]: '''simple docstring''' __magic_name__ , __magic_name__ = get_sqrt_alpha_prod(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) __magic_name__ = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def UpperCamelCase ( a , a , a , a ) -> List[str]: '''simple docstring''' __magic_name__ , __magic_name__ = get_sqrt_alpha_prod(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) __magic_name__ = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
432
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = JukeboxTokenizer UpperCAmelCase__ = { '''artist''': '''Zac Brown Band''', '''genres''': '''Country''', '''lyrics''': '''I met a traveller from an antique land, Who said "Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away ''', } @require_torch def SCREAMING_SNAKE_CASE ( self : Dict) ->int: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''') A__ = tokenizer(**self.metas)['''input_ids'''] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 7_169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]]), torch.tensor([[0, 0, 0, 1_069, 11]]), torch.tensor([[0, 0, 0, 1_069, 11]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2])) @require_torch def SCREAMING_SNAKE_CASE ( self : List[str]) ->Optional[int]: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''') A__ = tokenizer(**self.metas)['''input_ids'''] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 1_069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]]), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]]), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2]))
87
0
'''simple docstring''' import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _SCREAMING_SNAKE_CASE : int = logging.get_logger("transformers.models.speecht5") def UpperCamelCase_( snake_case : Tuple , snake_case : Optional[int] , snake_case : str ): '''simple docstring''' hf_model.apply_weight_norm() snake_case_ = checkpoint["input_conv.weight_g"] snake_case_ = checkpoint["input_conv.weight_v"] snake_case_ = checkpoint["input_conv.bias"] for i in range(len(config.upsample_rates ) ): snake_case_ = checkpoint[f'upsamples.{i}.1.weight_g'] snake_case_ = checkpoint[f'upsamples.{i}.1.weight_v'] snake_case_ = checkpoint[f'upsamples.{i}.1.bias'] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): snake_case_ = checkpoint[f'blocks.{i}.convs1.{j}.1.weight_g'] snake_case_ = checkpoint[f'blocks.{i}.convs1.{j}.1.weight_v'] snake_case_ = checkpoint[f'blocks.{i}.convs1.{j}.1.bias'] snake_case_ = checkpoint[f'blocks.{i}.convs2.{j}.1.weight_g'] snake_case_ = checkpoint[f'blocks.{i}.convs2.{j}.1.weight_v'] snake_case_ = checkpoint[f'blocks.{i}.convs2.{j}.1.bias'] snake_case_ = checkpoint["output_conv.1.weight_g"] snake_case_ = checkpoint["output_conv.1.weight_v"] snake_case_ = checkpoint["output_conv.1.bias"] hf_model.remove_weight_norm() @torch.no_grad() def UpperCamelCase_( snake_case : List[Any] , snake_case : List[str] , snake_case : str , snake_case : Optional[int]=None , snake_case : int=None , ): '''simple docstring''' if config_path is not None: snake_case_ = SpeechTaHifiGanConfig.from_pretrained(lowercase_ ) else: snake_case_ = SpeechTaHifiGanConfig() snake_case_ = SpeechTaHifiGan(lowercase_ ) snake_case_ = torch.load(lowercase_ ) load_weights(orig_checkpoint["model"]["generator"] , lowercase_ , lowercase_ ) snake_case_ = np.load(lowercase_ ) snake_case_ = stats[0].reshape(-1 ) snake_case_ = stats[1].reshape(-1 ) snake_case_ = torch.from_numpy(lowercase_ ).float() snake_case_ = torch.from_numpy(lowercase_ ).float() model.save_pretrained(lowercase_ ) if repo_id: print("Pushing to the hub..." ) model.push_to_hub(lowercase_ ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser() parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--stats_path", required=True, default=None, type=str, help="Path to stats.npy file") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model." ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) _SCREAMING_SNAKE_CASE : List[str] = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
400
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : str = logging.get_logger(__name__) _lowerCamelCase : List[str] = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''openai-gpt''' UpperCAmelCase__ = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict=40_478 , UpperCAmelCase__ : str=512 , UpperCAmelCase__ : Union[str, Any]=768 , UpperCAmelCase__ : Optional[Any]=12 , UpperCAmelCase__ : Any=12 , UpperCAmelCase__ : Optional[Any]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : List[str]=1e-5 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Any="cls_index" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Optional[Any]=0.1 , **UpperCAmelCase__ : Dict , ) ->Any: '''simple docstring''' A__ = vocab_size A__ = n_positions A__ = n_embd A__ = n_layer A__ = n_head A__ = afn A__ = resid_pdrop A__ = embd_pdrop A__ = attn_pdrop A__ = layer_norm_epsilon A__ = initializer_range A__ = summary_type A__ = summary_use_proj A__ = summary_activation A__ = summary_first_dropout A__ = summary_proj_to_labels super().__init__(**UpperCAmelCase__)
87
0
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
138
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
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType __magic_name__: Optional[List[str]] = None __magic_name__: int = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image __magic_name__: Union[str, Any] = [ np.dtype("|b1"), np.dtype("|u1"), np.dtype("<u2"), np.dtype(">u2"), np.dtype("<i2"), np.dtype(">i2"), np.dtype("<u4"), np.dtype(">u4"), np.dtype("<i4"), np.dtype(">i4"), np.dtype("<f4"), np.dtype(">f4"), np.dtype("<f8"), np.dtype(">f8"), ] @dataclass class snake_case__ : lowercase__ : List[Any] = True lowercase__ : Optional[int] = None # Automatically constructed lowercase__ : Dict = '''PIL.Image.Image''' lowercase__ : Dict = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) lowercase__ : List[str] = field(default='''Image''' , init=UpperCAmelCase__ , repr=UpperCAmelCase__ ) def __call__( self ) -> List[str]: return self.pa_type def __magic_name__ ( self , lowerCAmelCase__ ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install \'Pillow\'.""" ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __magic_name__ : Dict = np.array(UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return {"path": value, "bytes": None} elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return {"path": None, "bytes": value} elif isinstance(UpperCAmelCase__ , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(UpperCAmelCase__ ) 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 return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( F'An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.' ) def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__=None ) -> "PIL.Image.Image": if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Image(decode=True) instead.""" ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support decoding images, please install \'Pillow\'.""" ) if token_per_repo_id is None: __magic_name__ : List[str] = {} __magic_name__ ,__magic_name__ : Optional[int] = value["""path"""], value["""bytes"""] if bytes_ is None: if path is None: raise ValueError(F'An image should have one of \'path\' or \'bytes\' but both are None in {value}.' ) else: if is_local_path(UpperCAmelCase__ ): __magic_name__ : List[str] = PIL.Image.open(UpperCAmelCase__ ) else: __magic_name__ : Optional[Any] = path.split("""::""" )[-1] try: __magic_name__ : str = string_to_dict(UpperCAmelCase__ , config.HUB_DATASETS_URL )["""repo_id"""] __magic_name__ : Optional[Any] = token_per_repo_id.get(UpperCAmelCase__ ) except ValueError: __magic_name__ : Optional[Any] = None with xopen(UpperCAmelCase__ , """rb""" , use_auth_token=UpperCAmelCase__ ) as f: __magic_name__ : Optional[int] = BytesIO(f.read() ) __magic_name__ : List[str] = PIL.Image.open(bytes_ ) else: __magic_name__ : List[Any] = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __magic_name__ ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value return ( self if self.decode else { "bytes": Value("""binary""" ), "path": Value("""string""" ), } ) def __magic_name__ ( self , lowerCAmelCase__ ) -> pa.StructArray: if pa.types.is_string(storage.type ): __magic_name__ : Dict = pa.array([None] * len(UpperCAmelCase__ ) , type=pa.binary() ) __magic_name__ : Union[str, Any] = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): __magic_name__ : Dict = pa.array([None] * len(UpperCAmelCase__ ) , type=pa.string() ) __magic_name__ : str = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: __magic_name__ : str = storage.field("""bytes""" ) else: __magic_name__ : int = pa.array([None] * len(UpperCAmelCase__ ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: __magic_name__ : List[str] = storage.field("""path""" ) else: __magic_name__ : Optional[Any] = pa.array([None] * len(UpperCAmelCase__ ) , type=pa.string() ) __magic_name__ : str = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): __magic_name__ : Tuple = pa.array( [encode_np_array(np.array(UpperCAmelCase__ ) )["""bytes"""] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) __magic_name__ : Any = pa.array([None] * len(UpperCAmelCase__ ) , type=pa.string() ) __magic_name__ : List[Any] = pa.StructArray.from_arrays( [bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(UpperCAmelCase__ , self.pa_type ) def __magic_name__ ( self , lowerCAmelCase__ ) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(lowerCAmelCase__ ): with xopen(UpperCAmelCase__ , """rb""" ) as f: __magic_name__ : List[str] = f.read() return bytes_ __magic_name__ : List[Any] = 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() , ) __magic_name__ : Optional[Any] = pa.array( [os.path.basename(UpperCAmelCase__ ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) __magic_name__ : Union[str, Any] = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(UpperCAmelCase__ , self.pa_type ) def UpperCamelCase ( ): """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install \'Pillow\'.""" ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() __magic_name__ : Dict = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def UpperCamelCase ( _A ): """simple docstring""" __magic_name__ : str = BytesIO() if image.format in list_image_compression_formats(): __magic_name__ : List[str] = image.format else: __magic_name__ : List[str] = """PNG""" if image.mode in ["""1""", """L""", """LA""", """RGB""", """RGBA"""] else """TIFF""" image.save(lowercase_, format=lowercase_ ) return buffer.getvalue() def UpperCamelCase ( _A ): """simple docstring""" if hasattr(lowercase_, """filename""" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(lowercase_ )} def UpperCamelCase ( _A ): """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install \'Pillow\'.""" ) __magic_name__ : Union[str, Any] = array.dtype __magic_name__ : List[str] = dtype.byteorder if dtype.byteorder != """=""" else _NATIVE_BYTEORDER __magic_name__ : List[Any] = dtype.kind __magic_name__ : Dict = dtype.itemsize __magic_name__ : Dict = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: __magic_name__ : Tuple = np.dtype("""|u1""" ) if dtype_kind not in ["u", "i"]: raise TypeError( f'Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.' ) if dtype is not dest_dtype: warnings.warn(f'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: __magic_name__ : List[str] = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: __magic_name__ : Optional[Any] = dtype_byteorder + dtype_kind + str(lowercase_ ) __magic_name__ : List[Any] = np.dtype(lowercase_ ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f'Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}' ) __magic_name__ : Union[str, Any] = PIL.Image.fromarray(array.astype(lowercase_ ) ) return {"path": None, "bytes": image_to_bytes(lowercase_ )} def UpperCamelCase ( _A ): """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install \'Pillow\'.""" ) if objs: __magic_name__ ,__magic_name__ : Union[str, Any] = first_non_null_value(lowercase_ ) if isinstance(lowercase_, lowercase_ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(lowercase_, np.ndarray ): __magic_name__ : List[Any] = no_op_if_value_is_null(lowercase_ ) return [obj_to_image_dict_func(lowercase_ ) for obj in objs] elif isinstance(lowercase_, PIL.Image.Image ): __magic_name__ : int = no_op_if_value_is_null(lowercase_ ) return [obj_to_image_dict_func(lowercase_ ) for obj in objs] else: return objs else: return objs
324
import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None ) -> Dict: """simple docstring""" if "." in tensor_name: A__ = tensor_name.split('''.''' ) for split in splits[:-1]: A__ = getattr(lowercase_ , lowercase_ ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) A__ = new_module A__ = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(f"""{module} does not have a parameter or a buffer named {tensor_name}.""" ) A__ = tensor_name in module._buffers A__ = getattr(lowercase_ , lowercase_ ) if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None: raise ValueError(f"""{tensor_name} is on the meta device, we need a `value` to put in on {device}.""" ) A__ = False A__ = False if is_buffer or not is_bitsandbytes_available(): A__ = False A__ = False else: A__ = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) A__ = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: A__ = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to('''cpu''' ) if value.dtype == torch.inta: A__ = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse( '''0.37.2''' ) if not is_abit_serializable: raise ValueError( '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ''' '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' ) else: A__ = torch.tensor(lowercase_ , device='''cpu''' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , lowercase_ ) and fpaa_statistics is None: A__ = new_value.T A__ = old_value.__dict__ if is_abit: A__ = bnb.nn.IntaParams(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) elif is_abit: A__ = bnb.nn.Paramsabit(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) A__ = new_value if fpaa_statistics is not None: setattr(module.weight , '''SCB''' , fpaa_statistics.to(lowercase_ ) ) else: if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to(lowercase_ ) else: A__ = torch.tensor(lowercase_ , device=lowercase_ ) if is_buffer: A__ = new_value else: A__ = nn.Parameter(lowercase_ , requires_grad=old_value.requires_grad ) A__ = new_value def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=False ) -> Dict: """simple docstring""" for name, module in model.named_children(): if current_key_name is None: A__ = [] current_key_name.append(lowercase_ ) if (isinstance(lowercase_ , nn.Linear ) or isinstance(lowercase_ , lowercase_ )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '''.'''.join(lowercase_ ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(lowercase_ , lowercase_ ): A__ , A__ = module.weight.shape else: A__ = module.in_features A__ = module.out_features if quantization_config.quantization_method() == "llm_int8": A__ = bnb.nn.LinearabitLt( lowercase_ , lowercase_ , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) A__ = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: A__ = bnb.nn.Linearabit( lowercase_ , lowercase_ , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) A__ = True # Store the module class in case we need to transpose the weight later A__ = type(lowercase_ ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(lowercase_ ) if len(list(module.children() ) ) > 0: A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ , has_been_replaced=lowercase_ , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None ) -> Tuple: """simple docstring""" A__ = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Dict: """simple docstring""" warnings.warn( '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , lowercase_ , ) return replace_with_bnb_linear(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Optional[Any]: """simple docstring""" warnings.warn( '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , lowercase_ , ) return set_module_quantized_tensor_to_device(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]: """simple docstring""" A__ = deepcopy(lowercase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() A__ = find_tied_parameters(lowercase_ ) # For compatibility with Accelerate < 0.18 if isinstance(lowercase_ , lowercase_ ): A__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: A__ = sum(lowercase_ , [] ) A__ = len(lowercase_ ) > 0 # Check if it is a base model A__ = not hasattr(lowercase_ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head A__ = list(model.named_children() ) A__ = [list_modules[-1][0]] # add last module together with tied weights A__ = set(lowercase_ ) - set(lowercase_ ) A__ = list(set(lowercase_ ) ) + list(lowercase_ ) # remove ".weight" from the keys A__ = ['''.weight''', '''.bias'''] A__ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: A__ = name.replace(lowercase_ , '''''' ) filtered_module_names.append(lowercase_ ) return filtered_module_names
87
0
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class lowerCamelCase : """simple docstring""" def __init__( self : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : List[str]=13 , __magic_name__ : List[Any]=7 , __magic_name__ : List[Any]=True , __magic_name__ : Optional[int]=True , __magic_name__ : Optional[int]=True , __magic_name__ : List[str]=True , __magic_name__ : str=99 , __magic_name__ : Tuple=32 , __magic_name__ : Optional[Any]=2 , __magic_name__ : List[Any]=4 , __magic_name__ : Union[str, Any]=37 , __magic_name__ : Any="gelu" , __magic_name__ : Tuple=0.1 , __magic_name__ : Optional[Any]=0.1 , __magic_name__ : int=512 , __magic_name__ : Tuple=16 , __magic_name__ : Any=2 , __magic_name__ : int=0.02 , __magic_name__ : Optional[int]=3 , __magic_name__ : int=4 , __magic_name__ : int=None , ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = parent SCREAMING_SNAKE_CASE_ = 13 SCREAMING_SNAKE_CASE_ = 7 SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = 99 SCREAMING_SNAKE_CASE_ = 384 SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 37 SCREAMING_SNAKE_CASE_ = "gelu" SCREAMING_SNAKE_CASE_ = 0.1 SCREAMING_SNAKE_CASE_ = 0.1 SCREAMING_SNAKE_CASE_ = 512 SCREAMING_SNAKE_CASE_ = 16 SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 0.02 SCREAMING_SNAKE_CASE_ = 3 SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 128 SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 9 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = None def __A ( self : List[Any] ) -> int: SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE_ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None if self.use_labels: SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE_ = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=UpperCAmelCase__ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Optional[Any] ) -> List[Any]: SCREAMING_SNAKE_CASE_ = TFConvBertModel(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} SCREAMING_SNAKE_CASE_ = [input_ids, input_mask] SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : str , __magic_name__ : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : Tuple ) -> Tuple: SCREAMING_SNAKE_CASE_ = TFConvBertForMaskedLM(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self : str , __magic_name__ : int , __magic_name__ : List[Any] , __magic_name__ : str , __magic_name__ : int , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : str ) -> Tuple: SCREAMING_SNAKE_CASE_ = self.num_labels SCREAMING_SNAKE_CASE_ = TFConvBertForSequenceClassification(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : Union[str, Any] , __magic_name__ : int , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = self.num_choices SCREAMING_SNAKE_CASE_ = TFConvBertForMultipleChoice(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE_ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE_ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE_ = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Optional[Any] , __magic_name__ : str , __magic_name__ : List[str] , __magic_name__ : str ) -> Tuple: SCREAMING_SNAKE_CASE_ = self.num_labels SCREAMING_SNAKE_CASE_ = TFConvBertForTokenClassification(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A ( self : Union[str, Any] , __magic_name__ : List[Any] , __magic_name__ : str , __magic_name__ : Any , __magic_name__ : Optional[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : List[Any] , __magic_name__ : List[str] ) -> Any: SCREAMING_SNAKE_CASE_ = TFConvBertForQuestionAnswering(config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __A ( self : Any ) -> Optional[int]: 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, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class lowerCamelCase (UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCamelCase__ = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) lowerCamelCase__ = ( { '''feature-extraction''': TFConvBertModel, '''fill-mask''': TFConvBertForMaskedLM, '''question-answering''': TFConvBertForQuestionAnswering, '''text-classification''': TFConvBertForSequenceClassification, '''token-classification''': TFConvBertForTokenClassification, '''zero-shot''': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def __A ( self : Union[str, Any] ) -> Dict: SCREAMING_SNAKE_CASE_ = TFConvBertModelTester(self ) SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37 ) def __A ( self : int ) -> Union[str, Any]: self.config_tester.run_common_tests() def __A ( self : Dict ) -> Tuple: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def __A ( self : List[Any] ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def __A ( self : int ) -> int: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def __A ( self : Any ) -> Dict: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def __A ( self : List[str] ) -> int: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def __A ( self : int ) -> List[str]: SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def __A ( self : Dict ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True if hasattr(UpperCAmelCase__ , "use_cache" ): SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) SCREAMING_SNAKE_CASE_ = getattr(self.model_tester , "key_length" , UpperCAmelCase__ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = model_class(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = len(model(UpperCAmelCase__ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCAmelCase__ , saved_model=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = os.path.join(UpperCAmelCase__ , "saved_model" , "1" ) SCREAMING_SNAKE_CASE_ = tf.keras.models.load_model(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ ) if self.is_encoder_decoder: SCREAMING_SNAKE_CASE_ = outputs["encoder_hidden_states"] SCREAMING_SNAKE_CASE_ = outputs["encoder_attentions"] else: SCREAMING_SNAKE_CASE_ = outputs["hidden_states"] SCREAMING_SNAKE_CASE_ = outputs["attentions"] self.assertEqual(len(UpperCAmelCase__ ) , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(UpperCAmelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def __A ( self : Dict ) -> Tuple: SCREAMING_SNAKE_CASE_ = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) self.assertIsNotNone(UpperCAmelCase__ ) def __A ( self : Optional[int] ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = getattr(self.model_tester , "decoder_seq_length" , self.model_tester.seq_length ) SCREAMING_SNAKE_CASE_ = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) SCREAMING_SNAKE_CASE_ = getattr(self.model_tester , "key_length" , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = getattr(self.model_tester , "key_length" , UpperCAmelCase__ ) def check_decoder_attentions_output(__magic_name__ : List[Any] ): SCREAMING_SNAKE_CASE_ = len(UpperCAmelCase__ ) self.assertEqual(out_len % 2 , 0 ) SCREAMING_SNAKE_CASE_ = outputs.decoder_attentions self.assertEqual(len(UpperCAmelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(__magic_name__ : str ): SCREAMING_SNAKE_CASE_ = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(UpperCAmelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = model_class(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = model(self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) SCREAMING_SNAKE_CASE_ = len(UpperCAmelCase__ ) self.assertEqual(config.output_hidden_states , UpperCAmelCase__ ) check_encoder_attentions_output(UpperCAmelCase__ ) if self.is_encoder_decoder: SCREAMING_SNAKE_CASE_ = model_class(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = model(self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCAmelCase__ ) check_decoder_attentions_output(UpperCAmelCase__ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = model_class(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = model(self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCAmelCase__ ) check_encoder_attentions_output(UpperCAmelCase__ ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = model_class(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = model(self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(UpperCAmelCase__ ) ) self.assertEqual(model.config.output_hidden_states , UpperCAmelCase__ ) check_encoder_attentions_output(UpperCAmelCase__ ) @require_tf class lowerCamelCase (unittest.TestCase ): """simple docstring""" @slow def __A ( self : List[Any] ) -> Any: SCREAMING_SNAKE_CASE_ = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) SCREAMING_SNAKE_CASE_ = tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE_ = model(UpperCAmelCase__ )[0] SCREAMING_SNAKE_CASE_ = [1, 6, 768] self.assertEqual(output.shape , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = tf.constant( [ [ [-0.0347_5493, -0.468_6034, -0.3063_8832], [0.2263_7248, -0.2698_8646, -0.742_3424], [0.1032_4868, -0.4501_3508, -0.5828_0784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4 )
140
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) _lowerCamelCase : str = 299792458 # Symbols _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = symbols("""ct x y z""") def SCREAMING_SNAKE_CASE ( lowercase_ ) -> float: """simple docstring""" 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 ( lowercase_ ) -> float: """simple docstring""" return 1 / sqrt(1 - beta(lowercase_ ) ** 2 ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> np.ndarray: """simple docstring""" return np.array( [ [gamma(lowercase_ ), -gamma(lowercase_ ) * beta(lowercase_ ), 0, 0], [-gamma(lowercase_ ) * beta(lowercase_ ), gamma(lowercase_ ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = None ) -> np.ndarray: """simple docstring""" if event is None: A__ = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(lowercase_ ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: _lowerCamelCase : Tuple = transform(29979245) 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 _lowerCamelCase : int = {ct: c, x: 1, y: 1, z: 1} _lowerCamelCase : Any = [four_vector[i].subs(sub_dict) for i in range(4)] print(F'''\n{numerical_vector}''')
87
0
"""simple docstring""" from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": UpperCamelCase__ :Optional[int] = input("""Enter image url: """).strip() print(F"""Downloading image from {url} ...""") UpperCamelCase__ :Union[str, Any] = BeautifulSoup(requests.get(url).content, """html.parser""") # The image URL is in the content field of the first meta tag with property og:image UpperCamelCase__ :List[Any] = soup.find("""meta""", {"""property""": """og:image"""})["""content"""] UpperCamelCase__ :int = requests.get(image_url).content UpperCamelCase__ :Optional[Any] = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, """wb""") as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
355
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> list: """simple docstring""" if len(lowercase_ ) <= 1: return [tuple(lowercase_ )] A__ = [] def generate(lowercase_ , lowercase_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , lowercase_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even A__ , A__ = arr[k - 1], arr[i] else: # k is odd A__ , A__ = arr[k - 1], arr[0] generate(k - 1 , lowercase_ ) generate(len(lowercase_ ) , lowercase_ ) return res if __name__ == "__main__": _lowerCamelCase : int = input("""Enter numbers separated by a comma:\n""").strip() _lowerCamelCase : str = [int(item) for item in user_input.split(""",""")] print(heaps(arr))
87
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCamelCase__ = { """configuration_pix2struct""": [ """PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Pix2StructConfig""", """Pix2StructTextConfig""", """Pix2StructVisionConfig""", ], """processing_pix2struct""": ["""Pix2StructProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ["""Pix2StructImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Pix2StructPreTrainedModel""", """Pix2StructForConditionalGeneration""", """Pix2StructVisionModel""", """Pix2StructTextModel""", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
322
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Union[str, Any]: """simple docstring""" A__ = np.max(_outputs , axis=-1 , keepdims=lowercase_ ) A__ = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowercase_ ) class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''sigmoid''' UpperCAmelCase__ = '''softmax''' UpperCAmelCase__ = '''none''' @add_end_docstrings( UpperCAmelCase__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = False UpperCAmelCase__ = ClassificationFunction.NONE def __init__( self : Any , **UpperCAmelCase__ : Optional[Any]) ->str: '''simple docstring''' super().__init__(**UpperCAmelCase__) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int="" , **UpperCAmelCase__ : Any) ->int: '''simple docstring''' A__ = tokenizer_kwargs A__ = {} if hasattr(self.model.config , '''return_all_scores''') and return_all_scores is None: A__ = self.model.config.return_all_scores if isinstance(UpperCAmelCase__ , UpperCAmelCase__) or top_k is None: A__ = top_k A__ = False elif return_all_scores is not None: warnings.warn( '''`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of''' ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.''' , UpperCAmelCase__ , ) if return_all_scores: A__ = None else: A__ = 1 if isinstance(UpperCAmelCase__ , UpperCAmelCase__): A__ = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: A__ = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self : str , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : Optional[int]) ->Union[str, Any]: '''simple docstring''' A__ = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__) # TODO try and retrieve it in a nicer way from _sanitize_parameters. A__ = '''top_k''' not in kwargs if isinstance(args[0] , UpperCAmelCase__) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : Any , **UpperCAmelCase__ : str) ->Dict[str, GenericTensor]: '''simple docstring''' A__ = self.framework if isinstance(UpperCAmelCase__ , UpperCAmelCase__): return self.tokenizer(**UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__) and len(UpperCAmelCase__) == 1 and isinstance(inputs[0] , UpperCAmelCase__) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a''' ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.''') return self.tokenizer(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : Tuple) ->Tuple: '''simple docstring''' return self.model(**UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : str=True) ->Dict: '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: A__ = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: A__ = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''') and function_to_apply is None: A__ = self.model.config.function_to_apply else: A__ = ClassificationFunction.NONE A__ = model_outputs['''logits'''][0] A__ = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: A__ = sigmoid(UpperCAmelCase__) elif function_to_apply == ClassificationFunction.SOFTMAX: A__ = softmax(UpperCAmelCase__) elif function_to_apply == ClassificationFunction.NONE: A__ = outputs else: raise ValueError(f"""Unrecognized `function_to_apply` argument: {function_to_apply}""") if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} A__ = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(UpperCAmelCase__) ] if not _legacy: dict_scores.sort(key=lambda UpperCAmelCase__: x["score"] , reverse=UpperCAmelCase__) if top_k is not None: A__ = dict_scores[:top_k] return dict_scores
87
0
"""simple docstring""" import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class snake_case ( unittest.TestCase ): @property def lowercase_ ( self : List[str])-> List[Any]: '''simple docstring''' torch.manual_seed(0) __lowerCAmelCase: Tuple = UNetaDModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , ) return model def lowercase_ ( self : Tuple)-> int: '''simple docstring''' __lowerCAmelCase: Tuple = self.dummy_uncond_unet __lowerCAmelCase: Optional[int] = KarrasVeScheduler() __lowerCAmelCase: str = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__) pipe.to(UpperCAmelCase__) pipe.set_progress_bar_config(disable=UpperCAmelCase__) __lowerCAmelCase: Union[str, Any] = torch.manual_seed(0) __lowerCAmelCase: str = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="numpy").images __lowerCAmelCase: Dict = torch.manual_seed(0) __lowerCAmelCase: int = pipe(num_inference_steps=2 , generator=UpperCAmelCase__ , output_type="numpy" , return_dict=UpperCAmelCase__)[0] __lowerCAmelCase: List[str] = image[0, -3:, -3:, -1] __lowerCAmelCase: Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __lowerCAmelCase: Union[str, 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 snake_case ( unittest.TestCase ): def lowercase_ ( self : Tuple)-> List[str]: '''simple docstring''' __lowerCAmelCase: List[Any] = "google/ncsnpp-celebahq-256" __lowerCAmelCase: int = UNetaDModel.from_pretrained(UpperCAmelCase__) __lowerCAmelCase: List[Any] = KarrasVeScheduler() __lowerCAmelCase: str = KarrasVePipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__) pipe.to(UpperCAmelCase__) pipe.set_progress_bar_config(disable=UpperCAmelCase__) __lowerCAmelCase: Optional[Any] = torch.manual_seed(0) __lowerCAmelCase: int = pipe(num_inference_steps=2_0 , generator=UpperCAmelCase__ , output_type="numpy").images __lowerCAmelCase: int = image[0, -3:, -3:, -1] assert image.shape == (1, 2_5_6, 2_5_6, 3) __lowerCAmelCase: Tuple = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
346
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase : Any = {"""configuration_xlnet""": ["""XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : int = ["""XLNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : int = ["""XLNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Union[str, Any] = [ """XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLNetForMultipleChoice""", """XLNetForQuestionAnswering""", """XLNetForQuestionAnsweringSimple""", """XLNetForSequenceClassification""", """XLNetForTokenClassification""", """XLNetLMHeadModel""", """XLNetModel""", """XLNetPreTrainedModel""", """load_tf_weights_in_xlnet""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Dict = [ """TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLNetForMultipleChoice""", """TFXLNetForQuestionAnsweringSimple""", """TFXLNetForSequenceClassification""", """TFXLNetForTokenClassification""", """TFXLNetLMHeadModel""", """TFXLNetMainLayer""", """TFXLNetModel""", """TFXLNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys _lowerCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
87
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { """microsoft/cvt-13""": """https://huggingface.co/microsoft/cvt-13/resolve/main/config.json""", # See all Cvt models at https://huggingface.co/models?filter=cvt } class _UpperCAmelCase ( UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE : int = "cvt" def __init__( self , lowercase_=3 , lowercase_=[7, 3, 3] , lowercase_=[4, 2, 2] , lowercase_=[2, 1, 1] , lowercase_=[6_4, 1_9_2, 3_8_4] , lowercase_=[1, 3, 6] , lowercase_=[1, 2, 1_0] , lowercase_=[4.0, 4.0, 4.0] , lowercase_=[0.0, 0.0, 0.0] , lowercase_=[0.0, 0.0, 0.0] , lowercase_=[0.0, 0.0, 0.1] , lowercase_=[True, True, True] , lowercase_=[False, False, True] , lowercase_=["dw_bn", "dw_bn", "dw_bn"] , lowercase_=[3, 3, 3] , lowercase_=[1, 1, 1] , lowercase_=[2, 2, 2] , lowercase_=[1, 1, 1] , lowercase_=[1, 1, 1] , lowercase_=0.0_2 , lowercase_=1E-12 , **lowercase_ , ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) UpperCAmelCase = num_channels UpperCAmelCase = patch_sizes UpperCAmelCase = patch_stride UpperCAmelCase = patch_padding UpperCAmelCase = embed_dim UpperCAmelCase = num_heads UpperCAmelCase = depth UpperCAmelCase = mlp_ratio UpperCAmelCase = attention_drop_rate UpperCAmelCase = drop_rate UpperCAmelCase = drop_path_rate UpperCAmelCase = qkv_bias UpperCAmelCase = cls_token UpperCAmelCase = qkv_projection_method UpperCAmelCase = kernel_qkv UpperCAmelCase = padding_kv UpperCAmelCase = stride_kv UpperCAmelCase = padding_q UpperCAmelCase = stride_q UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps
373
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 : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : Union[str, Any] = { """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""", """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''mobilenet_v1''' def __init__( self : Optional[int] , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : Optional[Any]=224 , UpperCAmelCase__ : Optional[int]=1.0 , UpperCAmelCase__ : Optional[int]=8 , UpperCAmelCase__ : Tuple="relu6" , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Dict=0.999 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : Optional[int]=0.001 , **UpperCAmelCase__ : Dict , ) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase__) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''') A__ = num_channels A__ = image_size A__ = depth_multiplier A__ = min_depth A__ = hidden_act A__ = tf_padding A__ = classifier_dropout_prob A__ = initializer_range A__ = layer_norm_eps class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = version.parse('''1.11''' ) @property def SCREAMING_SNAKE_CASE ( self : Any) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict([('''pixel_values''', {0: '''batch'''})]) @property def SCREAMING_SNAKE_CASE ( self : List[str]) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})]) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})]) @property def SCREAMING_SNAKE_CASE ( self : int) ->float: '''simple docstring''' return 1e-4
87
0
def snake_case__ ( lowerCamelCase_ ): if len(lowercase_ ) <= 1: return [tuple(lowercase_ )] A : Optional[Any] = [] def generate(lowerCamelCase_ , lowerCamelCase_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , lowercase_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even A , A : Optional[Any] = arr[k - 1], arr[i] else: # k is odd A , A : int = arr[k - 1], arr[0] generate(k - 1 , lowercase_ ) generate(len(lowercase_ ) , lowercase_ ) return res if __name__ == "__main__": lowercase : int = input("Enter numbers separated by a comma:\n").strip() lowercase : str = [int(item) for item in user_input.split(",")] print(heaps(arr))
542
import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase : Dict = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_sentencepiece_available(): import sentencepiece as sp _lowerCamelCase : str = 5 _lowerCamelCase : int = 10 @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = SpeechaTextTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = True def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' super().setUp() A__ = sp.SentencePieceProcessor() spm_model.Load(UpperCAmelCase__) A__ = ['''<s>''', '''<pad>''', '''</s>''', '''<unk>'''] vocab += [spm_model.IdToPiece(id_) for id_ in range(len(UpperCAmelCase__))] A__ = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__)))) A__ = Path(self.tmpdirname) save_json(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''vocab_file''']) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''spm_file''']) A__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' A__ = '''<pad>''' A__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__) , UpperCAmelCase__) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__) , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<s>''') self.assertEqual(vocab_keys[1] , '''<pad>''') self.assertEqual(vocab_keys[-1] , '''j''') self.assertEqual(len(UpperCAmelCase__) , 1_001) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[str]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_001) def SCREAMING_SNAKE_CASE ( self : int) ->List[str]: '''simple docstring''' A__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname) A__ = tokenizer.tokenize('''This is a test''') self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__) , [289, 50, 14, 174, 386] , ) A__ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( UpperCAmelCase__ , [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''', '''é''', '''.'''] , ) A__ = tokenizer.convert_tokens_to_ids(UpperCAmelCase__) self.assertListEqual(UpperCAmelCase__ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8]) A__ = tokenizer.convert_ids_to_tokens(UpperCAmelCase__) self.assertListEqual( UpperCAmelCase__ , [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>''', '''.'''] , ) @slow def SCREAMING_SNAKE_CASE ( self : int) ->List[Any]: '''simple docstring''' A__ = {'''input_ids''': [[3_791, 797, 31, 11, 64, 797, 31, 2_429, 433, 12, 1_176, 12, 20, 786, 915, 142, 2_413, 240, 37, 3_238, 797, 31, 11, 35, 93, 915, 142, 2_413, 240, 37, 5_540, 567, 1_276, 93, 37, 610, 40, 62, 455, 657, 1_042, 123, 780, 177, 37, 309, 241, 1_298, 514, 20, 292, 2_737, 114, 2_469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3_388, 511, 459, 4, 3_555, 40, 321, 302, 705, 4, 3_388, 511, 583, 326, 5, 5, 5, 62, 3_310, 560, 177, 2_680, 217, 1_508, 32, 31, 853, 418, 64, 583, 511, 1_605, 62, 35, 93, 560, 177, 2_680, 217, 1_508, 1_521, 64, 583, 511, 519, 62, 20, 1_515, 764, 20, 149, 261, 5_625, 7_972, 20, 5_540, 567, 1_276, 93, 3_925, 1_675, 11, 15, 802, 7_972, 576, 217, 1_508, 11, 35, 93, 1_253, 2_441, 15, 289, 652, 31, 416, 321, 3_842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2_681, 1_153, 3_434, 20, 5_540, 37, 567, 126, 1_253, 2_441, 3_376, 449, 210, 431, 1_563, 177, 767, 5_540, 11, 1_203, 472, 11, 2_953, 685, 285, 364, 706, 1_153, 20, 6_799, 20, 2_869, 20, 4_464, 126, 40, 2_429, 20, 1_040, 866, 2_664, 418, 20, 318, 20, 1_726, 186, 20, 265, 522, 35, 93, 2_191, 4_634, 20, 1_040, 12, 6_799, 15, 228, 2_356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2_575, 2_666, 684, 1_582, 1_176, 12, 627, 149, 619, 20, 4_902, 563, 11, 20, 149, 261, 3_420, 2_356, 174, 142, 4_714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''facebook/s2t-small-mustc-en-de-st''' , revision='''a14f04cf0776c02f62a8cb800cf7909e15ea23ad''' , ) @require_sentencepiece class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = '''valhalla/s2t_mustc_multilinguial_medium''' UpperCAmelCase__ = '''C\'est trop cool''' UpperCAmelCase__ = '''Esto es genial''' @classmethod def SCREAMING_SNAKE_CASE ( cls : Dict) ->Dict: '''simple docstring''' A__ = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name) return cls def SCREAMING_SNAKE_CASE ( self : str) ->Dict: '''simple docstring''' self.assertEqual(self.tokenizer.lang_code_to_id['''pt'''] , 4) self.assertEqual(self.tokenizer.lang_code_to_id['''ru'''] , 6) self.assertEqual(self.tokenizer.lang_code_to_id['''it'''] , 9) self.assertEqual(self.tokenizer.lang_code_to_id['''de'''] , 11) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Dict: '''simple docstring''' self.assertEqual(self.tokenizer.vocab_size , 10_000) def SCREAMING_SNAKE_CASE ( self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertIn(UpperCAmelCase__ , self.tokenizer.all_special_ids) A__ = [ES_CODE, 4, 1_601, 47, 7_647, 2] A__ = self.tokenizer.decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__) A__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCAmelCase__) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__) self.assertNotIn(self.tokenizer.eos_token , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->str: '''simple docstring''' A__ = '''fr''' A__ = self.tokenizer(self.french_text).input_ids self.assertEqual(encoded[0] , UpperCAmelCase__) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->int: '''simple docstring''' A__ = '''fr''' self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE]) A__ = '''es''' self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE])
87
0
'''simple docstring''' import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def lowerCamelCase__ ( a__) -> Dict: """simple docstring""" _snake_case : List[Any] = OrderedDict() for key, value in state_dict.items(): if key.startswith('module.encoder'): _snake_case : Tuple = key.replace('module.encoder' , 'glpn.encoder') if key.startswith('module.decoder'): _snake_case : Tuple = key.replace('module.decoder' , 'decoder.stages') if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 _snake_case : Any = key[key.find('patch_embed') + len('patch_embed')] _snake_case : List[str] = key.replace(F"""patch_embed{idx}""" , F"""patch_embeddings.{int(lowercase_)-1}""") if "norm" in key: _snake_case : Tuple = key.replace('norm' , 'layer_norm') if "glpn.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 _snake_case : int = key[key.find('glpn.encoder.layer_norm') + len('glpn.encoder.layer_norm')] _snake_case : Union[str, Any] = key.replace(F"""layer_norm{idx}""" , F"""layer_norm.{int(lowercase_)-1}""") if "layer_norm1" in key: _snake_case : str = key.replace('layer_norm1' , 'layer_norm_1') if "layer_norm2" in key: _snake_case : Tuple = key.replace('layer_norm2' , 'layer_norm_2') if "block" in key: # replace for example block1 by block.0 _snake_case : str = key[key.find('block') + len('block')] _snake_case : Union[str, Any] = key.replace(F"""block{idx}""" , F"""block.{int(lowercase_)-1}""") if "attn.q" in key: _snake_case : Tuple = key.replace('attn.q' , 'attention.self.query') if "attn.proj" in key: _snake_case : Any = key.replace('attn.proj' , 'attention.output.dense') if "attn" in key: _snake_case : Optional[int] = key.replace('attn' , 'attention.self') if "fc1" in key: _snake_case : List[Any] = key.replace('fc1' , 'dense1') if "fc2" in key: _snake_case : Tuple = key.replace('fc2' , 'dense2') if "linear_pred" in key: _snake_case : Any = key.replace('linear_pred' , 'classifier') if "linear_fuse" in key: _snake_case : int = key.replace('linear_fuse.conv' , 'linear_fuse') _snake_case : List[Any] = key.replace('linear_fuse.bn' , 'batch_norm') if "linear_c" in key: # replace for example linear_c4 by linear_c.3 _snake_case : Tuple = key[key.find('linear_c') + len('linear_c')] _snake_case : Union[str, Any] = key.replace(F"""linear_c{idx}""" , F"""linear_c.{int(lowercase_)-1}""") if "bot_conv" in key: _snake_case : Tuple = key.replace('bot_conv' , '0.convolution') if "skip_conv1" in key: _snake_case : int = key.replace('skip_conv1' , '1.convolution') if "skip_conv2" in key: _snake_case : Dict = key.replace('skip_conv2' , '2.convolution') if "fusion1" in key: _snake_case : Tuple = key.replace('fusion1' , '1.fusion') if "fusion2" in key: _snake_case : Dict = key.replace('fusion2' , '2.fusion') if "fusion3" in key: _snake_case : Optional[Any] = key.replace('fusion3' , '3.fusion') if "fusion" in key and "conv" in key: _snake_case : List[str] = key.replace('conv' , 'convolutional_layer') if key.startswith('module.last_layer_depth'): _snake_case : Tuple = key.replace('module.last_layer_depth' , 'head.head') _snake_case : Optional[Any] = value return new_state_dict def lowerCamelCase__ ( a__ , a__) -> Union[str, Any]: """simple docstring""" for i in range(config.num_encoder_blocks): for j in range(config.depths[i]): # read in weights + bias of keys and values (which is a single matrix in the original implementation) _snake_case : Tuple = state_dict.pop(F"""glpn.encoder.block.{i}.{j}.attention.self.kv.weight""") _snake_case : Any = state_dict.pop(F"""glpn.encoder.block.{i}.{j}.attention.self.kv.bias""") # next, add keys and values (in that order) to the state dict _snake_case : List[str] = kv_weight[ : config.hidden_sizes[i], : ] _snake_case : Dict = kv_bias[: config.hidden_sizes[i]] _snake_case : Optional[int] = kv_weight[ config.hidden_sizes[i] :, : ] _snake_case : Union[str, Any] = kv_bias[config.hidden_sizes[i] :] def lowerCamelCase__ ( ) -> Tuple: """simple docstring""" _snake_case : Dict = 'http://images.cocodataset.org/val2017/000000039769.jpg' _snake_case : int = Image.open(requests.get(lowercase_ , stream=lowercase_).raw) return image @torch.no_grad() def lowerCamelCase__ ( a__ , a__ , a__=False , a__=None) -> List[str]: """simple docstring""" _snake_case : Optional[int] = GLPNConfig(hidden_sizes=[6_4, 1_2_8, 3_2_0, 5_1_2] , decoder_hidden_size=6_4 , depths=[3, 8, 2_7, 3]) # load image processor (only resize + rescale) _snake_case : int = GLPNImageProcessor() # prepare image _snake_case : Union[str, Any] = prepare_img() _snake_case : Optional[Any] = image_processor(images=lowercase_ , return_tensors='pt').pixel_values logger.info('Converting model...') # load original state dict _snake_case : Dict = torch.load(lowercase_ , map_location=torch.device('cpu')) # rename keys _snake_case : List[str] = rename_keys(lowercase_) # key and value matrices need special treatment read_in_k_v(lowercase_ , lowercase_) # create HuggingFace model and load state dict _snake_case : List[str] = GLPNForDepthEstimation(lowercase_) model.load_state_dict(lowercase_) model.eval() # forward pass _snake_case : str = model(lowercase_) _snake_case : Tuple = outputs.predicted_depth # verify output if model_name is not None: if "nyu" in model_name: _snake_case : Dict = torch.tensor( [[4.4_1_4_7, 4.0_8_7_3, 4.0_6_7_3], [3.7_8_9_0, 3.2_8_8_1, 3.1_5_2_5], [3.7_6_7_4, 3.5_4_2_3, 3.4_9_1_3]]) elif "kitti" in model_name: _snake_case : Union[str, Any] = torch.tensor( [[3.4_2_9_1, 2.7_8_6_5, 2.5_1_5_1], [3.2_8_4_1, 2.7_0_2_1, 2.3_5_0_2], [3.1_1_4_7, 2.4_6_2_5, 2.2_4_8_1]]) else: raise ValueError(F"""Unknown model name: {model_name}""") _snake_case : int = torch.Size([1, 4_8_0, 6_4_0]) assert predicted_depth.shape == expected_shape assert torch.allclose(predicted_depth[0, :3, :3] , lowercase_ , atol=1E-4) print('Looks ok!') # finally, push to hub if required if push_to_hub: logger.info('Pushing model and image processor to the hub...') model.push_to_hub( repo_path_or_name=Path(lowercase_ , lowercase_) , organization='nielsr' , commit_message='Add model' , use_temp_dir=lowercase_ , ) image_processor.push_to_hub( repo_path_or_name=Path(lowercase_ , lowercase_) , organization='nielsr' , commit_message='Add image processor' , use_temp_dir=lowercase_ , ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original PyTorch checkpoint (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) parser.add_argument( "--model_name", default="glpn-kitti", type=str, help="Name of the model in case you're pushing to the hub.", ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_glpn_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
517
from __future__ import annotations import requests def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" A__ = f"""https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty""" return requests.get(lowercase_ ).json() def SCREAMING_SNAKE_CASE ( lowercase_ = 10 ) -> list[dict]: """simple docstring""" A__ = '''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty''' A__ = requests.get(lowercase_ ).json()[:max_stories] return [get_hackernews_story(lowercase_ ) for story_id in story_ids] def SCREAMING_SNAKE_CASE ( lowercase_ = 10 ) -> str: """simple docstring""" A__ = hackernews_top_stories(lowercase_ ) return "\n".join('''* [{title}]({url})'''.format(**lowercase_ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
87
0
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def UpperCamelCase ( a ) -> str: '''simple docstring''' __magic_name__ = filter(lambda a : p.requires_grad , model.parameters() ) __magic_name__ = sum([np.prod(p.size() ) for p in model_parameters] ) return params _lowerCAmelCase = logging.getLogger(__name__) def UpperCamelCase ( a , a ) -> Any: '''simple docstring''' if metric == "rouge2": __magic_name__ = '''{val_avg_rouge2:.4f}-{step_count}''' elif metric == "bleu": __magic_name__ = '''{val_avg_bleu:.4f}-{step_count}''' elif metric == "em": __magic_name__ = '''{val_avg_em:.4f}-{step_count}''' else: raise NotImplementedError( F'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' ''' function.''' ) __magic_name__ = ModelCheckpoint( dirpath=lowercase_ , filename=lowercase_ , monitor=F'''val_{metric}''' , mode='''max''' , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def UpperCamelCase ( a , a ) -> List[Any]: '''simple docstring''' return EarlyStopping( monitor=F'''val_{metric}''' , mode='''min''' if '''loss''' in metric else '''max''' , patience=lowercase_ , verbose=lowercase_ , ) class _SCREAMING_SNAKE_CASE ( pl.Callback ): def snake_case__ ( self : List[str] , a__ : str , a__ : Dict ): __magic_name__ = {F'''lr_group_{i}''': param['''lr'''] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(UpperCAmelCase__ ) @rank_zero_only def snake_case__ ( self : str , a__ : pl.Trainer , a__ : pl.LightningModule , a__ : str , a__ : int=True ): logger.info(F'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) __magic_name__ = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['''log''', '''progress_bar''', '''preds''']} ) # Log results __magic_name__ = Path(pl_module.hparams.output_dir ) if type_path == "test": __magic_name__ = od / '''test_results.txt''' __magic_name__ = od / '''test_generations.txt''' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. __magic_name__ = od / F'''{type_path}_results/{trainer.global_step:05d}.txt''' __magic_name__ = od / F'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=UpperCAmelCase__ ) generations_file.parent.mkdir(exist_ok=UpperCAmelCase__ ) with open(UpperCAmelCase__ , '''a+''' ) as writer: for key in sorted(UpperCAmelCase__ ): if key in ["log", "progress_bar", "preds"]: continue __magic_name__ = metrics[key] if isinstance(UpperCAmelCase__ , torch.Tensor ): __magic_name__ = val.item() __magic_name__ = F'''{key}: {val:.6f}\n''' writer.write(UpperCAmelCase__ ) if not save_generations: return if "preds" in metrics: __magic_name__ = '''\n'''.join(metrics['''preds'''] ) generations_file.open('''w+''' ).write(UpperCAmelCase__ ) @rank_zero_only def snake_case__ ( self : Tuple , a__ : int , a__ : Any ): try: __magic_name__ = pl_module.model.model.num_parameters() except AttributeError: __magic_name__ = pl_module.model.num_parameters() __magic_name__ = count_trainable_parameters(UpperCAmelCase__ ) # mp stands for million parameters trainer.logger.log_metrics({'''n_params''': npars, '''mp''': npars / 1E6, '''grad_mp''': n_trainable_pars / 1E6} ) @rank_zero_only def snake_case__ ( self : Optional[int] , a__ : pl.Trainer , a__ : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(UpperCAmelCase__ , UpperCAmelCase__ , '''test''' ) @rank_zero_only def snake_case__ ( self : Optional[int] , a__ : pl.Trainer , a__ : List[str] ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
432
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType _lowerCamelCase : Optional[List[str]] = None _lowerCamelCase : int = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image _lowerCamelCase : Union[str, Any] = [ np.dtype("""|b1"""), np.dtype("""|u1"""), np.dtype("""<u2"""), np.dtype(""">u2"""), np.dtype("""<i2"""), np.dtype(""">i2"""), np.dtype("""<u4"""), np.dtype(""">u4"""), np.dtype("""<i4"""), np.dtype(""">i4"""), np.dtype("""<f4"""), np.dtype(""">f4"""), np.dtype("""<f8"""), np.dtype(""">f8"""), ] @dataclass class UpperCamelCase_ : '''simple docstring''' UpperCAmelCase__ = True UpperCAmelCase__ = None # Automatically constructed UpperCAmelCase__ = "PIL.Image.Image" UpperCAmelCase__ = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) UpperCAmelCase__ = field(default='''Image''' , init=UpperCAmelCase__ , repr=UpperCAmelCase__ ) def __call__( self : List[str]) ->List[str]: '''simple docstring''' return self.pa_type def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"]) ->dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''') if isinstance(UpperCAmelCase__ , UpperCAmelCase__): A__ = np.array(UpperCAmelCase__) if isinstance(UpperCAmelCase__ , UpperCAmelCase__): return {"path": value, "bytes": None} elif isinstance(UpperCAmelCase__ , UpperCAmelCase__): return {"path": None, "bytes": value} elif isinstance(UpperCAmelCase__ , np.ndarray): # convert the image array to PNG/TIFF bytes return encode_np_array(UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , PIL.Image.Image): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(UpperCAmelCase__) 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 return {"bytes": None, "path": value.get('''path''')} elif value.get('''bytes''') is not None or value.get('''path''') is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get('''bytes'''), "path": value.get('''path''')} else: raise ValueError( f"""An image sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""") def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : dict , UpperCAmelCase__ : str=None) ->"PIL.Image.Image": '''simple docstring''' if not self.decode: raise RuntimeError('''Decoding is disabled for this feature. Please use Image(decode=True) instead.''') if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support decoding images, please install \'Pillow\'.''') if token_per_repo_id is None: A__ = {} A__ , A__ = value['''path'''], value['''bytes'''] if bytes_ is None: if path is None: raise ValueError(f"""An image should have one of 'path' or 'bytes' but both are None in {value}.""") else: if is_local_path(UpperCAmelCase__): A__ = PIL.Image.open(UpperCAmelCase__) else: A__ = path.split('''::''')[-1] try: A__ = string_to_dict(UpperCAmelCase__ , config.HUB_DATASETS_URL)['''repo_id'''] A__ = token_per_repo_id.get(UpperCAmelCase__) except ValueError: A__ = None with xopen(UpperCAmelCase__ , '''rb''' , use_auth_token=UpperCAmelCase__) as f: A__ = BytesIO(f.read()) A__ = PIL.Image.open(bytes_) else: A__ = PIL.Image.open(BytesIO(bytes_)) image.load() # to avoid "Too many open files" errors return image def SCREAMING_SNAKE_CASE ( self : Dict) ->Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Value return ( self if self.decode else { "bytes": Value('''binary'''), "path": Value('''string'''), } ) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[pa.StringArray, pa.StructArray, pa.ListArray]) ->pa.StructArray: '''simple docstring''' if pa.types.is_string(storage.type): A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.binary()) A__ = pa.StructArray.from_arrays([bytes_array, storage] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_binary(storage.type): A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays([storage, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_struct(storage.type): if storage.type.get_field_index('''bytes''') >= 0: A__ = storage.field('''bytes''') else: A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.binary()) if storage.type.get_field_index('''path''') >= 0: A__ = storage.field('''path''') else: A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_list(storage.type): A__ = pa.array( [encode_np_array(np.array(UpperCAmelCase__))['''bytes'''] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null()) return array_cast(UpperCAmelCase__ , self.pa_type) def SCREAMING_SNAKE_CASE ( self : List[Any] , UpperCAmelCase__ : pa.StructArray) ->pa.StructArray: '''simple docstring''' @no_op_if_value_is_null def path_to_bytes(UpperCAmelCase__ : Dict): with xopen(UpperCAmelCase__ , '''rb''') as f: A__ = f.read() return bytes_ A__ = 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() , ) A__ = pa.array( [os.path.basename(UpperCAmelCase__) if path is not None else None for path in storage.field('''path''').to_pylist()] , type=pa.string() , ) A__ = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null()) return array_cast(UpperCAmelCase__ , self.pa_type) def SCREAMING_SNAKE_CASE ( ) -> List[str]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() A__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def SCREAMING_SNAKE_CASE ( lowercase_ ) -> bytes: """simple docstring""" A__ = BytesIO() if image.format in list_image_compression_formats(): A__ = image.format else: A__ = '''PNG''' if image.mode in ['''1''', '''L''', '''LA''', '''RGB''', '''RGBA'''] else '''TIFF''' image.save(lowercase_ , format=lowercase_ ) return buffer.getvalue() def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" if hasattr(lowercase_ , '''filename''' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(lowercase_ )} def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) A__ = array.dtype A__ = dtype.byteorder if dtype.byteorder != '''=''' else _NATIVE_BYTEORDER A__ = dtype.kind A__ = dtype.itemsize A__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: A__ = np.dtype('''|u1''' ) if dtype_kind not in ["u", "i"]: raise TypeError( f"""Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.""" ) if dtype is not dest_dtype: warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: A__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: A__ = dtype_byteorder + dtype_kind + str(lowercase_ ) A__ = np.dtype(lowercase_ ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f"""Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}""" ) A__ = PIL.Image.fromarray(array.astype(lowercase_ ) ) return {"path": None, "bytes": image_to_bytes(lowercase_ )} def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[dict]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) if objs: A__ , A__ = first_non_null_value(lowercase_ ) if isinstance(lowercase_ , lowercase_ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(lowercase_ , np.ndarray ): A__ = no_op_if_value_is_null(lowercase_ ) return [obj_to_image_dict_func(lowercase_ ) for obj in objs] elif isinstance(lowercase_ , PIL.Image.Image ): A__ = no_op_if_value_is_null(lowercase_ ) return [obj_to_image_dict_func(lowercase_ ) for obj in objs] else: return objs else: return objs
87
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _snake_case ( UpperCAmelCase__ , unittest.TestCase ): lowerCAmelCase_ : List[str] = KandinskyVaaPipeline lowerCAmelCase_ : Tuple = [ "image_embeds", "negative_image_embeds", ] lowerCAmelCase_ : List[Any] = ["image_embeds", "negative_image_embeds"] lowerCAmelCase_ : Optional[int] = [ "generator", "height", "width", "latents", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] lowerCAmelCase_ : Dict = False @property def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' return 32 @property def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' return 32 @property def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' return self.time_input_dim @property def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' return self.time_input_dim * 4 @property def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' return 100 @property def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = { "in_channels": 4, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } snake_case_ = UNetaDConditionModel(**UpperCAmelCase__ ) return model @property def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="linear" , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , clip_sample=UpperCAmelCase__ , set_alpha_to_one=UpperCAmelCase__ , steps_offset=1 , prediction_type="epsilon" , thresholding=UpperCAmelCase__ , ) snake_case_ = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def lowerCAmelCase__ ( self , a__ , a__=0 ) -> Optional[Any]: '''simple docstring''' snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase__ ) if str(UpperCAmelCase__ ).startswith("mps" ): snake_case_ = torch.manual_seed(UpperCAmelCase__ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) snake_case_ = { "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = "cpu" snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**UpperCAmelCase__ ) snake_case_ = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) snake_case_ = pipe(**self.get_dummy_inputs(UpperCAmelCase__ ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(UpperCAmelCase__ ) , return_dict=UpperCAmelCase__ , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array( [0.6_2_3_7_9_7_6, 1.0, 0.3_6_4_4_1_3_3_2, 1.0, 0.7_0_6_3_9_6_3_4, 0.2_9_8_7_7_1_8_6, 0.8_5_6_5_2_1_2_5, 0.5_2_1_6_8_4_3, 0.5_4_4_5_4_0_4_6] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy" ) snake_case_ = KandinskyVaaPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase__ ) snake_case_ = KandinskyVaaPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-decoder" , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(UpperCAmelCase__ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase__ ) snake_case_ = "red cat, 4k photo" snake_case_ = torch.Generator(device="cuda" ).manual_seed(0 ) snake_case_ , snake_case_ = pipe_prior( UpperCAmelCase__ , generator=UpperCAmelCase__ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() snake_case_ = torch.Generator(device="cuda" ).manual_seed(0 ) snake_case_ = pipeline( image_embeds=UpperCAmelCase__ , negative_image_embeds=UpperCAmelCase__ , generator=UpperCAmelCase__ , num_inference_steps=100 , output_type="np" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase__ , UpperCAmelCase__ )
400
from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) UpperCAmelCase__ = ( { '''feature-extraction''': TFMobileBertModel, '''fill-mask''': TFMobileBertForMaskedLM, '''question-answering''': TFMobileBertForQuestionAnswering, '''text-classification''': TFMobileBertForSequenceClassification, '''token-classification''': TFMobileBertForTokenClassification, '''zero-shot''': TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase__ = False UpperCAmelCase__ = False def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str=False) ->Optional[Any]: '''simple docstring''' A__ = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__) if return_labels: if model_class in get_values(UpperCAmelCase__): A__ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa) return inputs_dict class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int=13 , UpperCAmelCase__ : str=7 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=99 , UpperCAmelCase__ : List[str]=32 , UpperCAmelCase__ : Optional[int]=32 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Optional[Any]=37 , UpperCAmelCase__ : Optional[int]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : List[Any]=512 , UpperCAmelCase__ : Tuple=16 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : Dict=0.02 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Tuple=None , ) ->Any: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = use_token_type_ids A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = type_vocab_size A__ = type_sequence_label_size A__ = initializer_range A__ = num_labels A__ = num_choices A__ = scope A__ = embedding_size def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Tuple: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) A__ = None if self.use_token_type_ids: A__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) A__ = None A__ = None A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size] , self.type_sequence_label_size) A__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) A__ = ids_tensor([self.batch_size] , self.num_choices) A__ = MobileBertConfig( 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 , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any]) ->Any: '''simple docstring''' A__ = TFMobileBertModel(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) A__ = [input_ids, input_mask] A__ = model(UpperCAmelCase__) A__ = model(UpperCAmelCase__) 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 SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Tuple) ->Optional[Any]: '''simple docstring''' A__ = TFMobileBertForMaskedLM(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any]) ->int: '''simple docstring''' A__ = TFMobileBertForNextSentencePrediction(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int) ->List[Any]: '''simple docstring''' A__ = TFMobileBertForPreTraining(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) 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 SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple) ->Dict: '''simple docstring''' A__ = self.num_labels A__ = TFMobileBertForSequenceClassification(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int) ->Dict: '''simple docstring''' A__ = self.num_choices A__ = TFMobileBertForMultipleChoice(config=UpperCAmelCase__) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1) , (1, self.num_choices, 1)) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1) , (1, self.num_choices, 1)) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 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(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int]) ->int: '''simple docstring''' A__ = self.num_labels A__ = TFMobileBertForTokenClassification(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any]) ->Union[str, Any]: '''simple docstring''' A__ = TFMobileBertForQuestionAnswering(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def SCREAMING_SNAKE_CASE ( self : Any) ->str: '''simple docstring''' A__ = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = config_and_inputs A__ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE ( self : Any) ->Union[str, Any]: '''simple docstring''' A__ = TFMobileBertModelTest.TFMobileBertModelTester(self) A__ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[str]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*UpperCAmelCase__) @slow def SCREAMING_SNAKE_CASE ( self : str) ->List[Any]: '''simple docstring''' for model_name in ["google/mobilebert-uncased"]: A__ = TFMobileBertModel.from_pretrained(UpperCAmelCase__) self.assertIsNotNone(UpperCAmelCase__) @require_tf class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Any: '''simple docstring''' A__ = TFMobileBertForPreTraining.from_pretrained('''google/mobilebert-uncased''') A__ = tf.constant([[0, 1, 2, 3, 4, 5]]) A__ = model(UpperCAmelCase__)[0] A__ = [1, 6, 30_522] self.assertEqual(output.shape , UpperCAmelCase__) A__ = tf.constant( [ [ [-4.5919547, -9.248295, -9.645256], [-6.7306175, -6.440284, -6.6052837], [-7.2743506, -6.7847915, -6.024673], ] ]) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4)
87
0
'''simple docstring''' import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin snake_case_ : Dict = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_sentencepiece_available(): import sentencepiece as sp snake_case_ : str = 5 snake_case_ : int = 10 @require_sentencepiece @require_tokenizers class A_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' _lowerCAmelCase = SpeechaTextTokenizer _lowerCAmelCase = False _lowerCAmelCase = True def a ( self ): super().setUp() _UpperCamelCase = sp.SentencePieceProcessor() spm_model.Load(UpperCAmelCase__ ) _UpperCamelCase = ["<s>", "<pad>", "</s>", "<unk>"] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(UpperCAmelCase__ ) )] _UpperCamelCase = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) _UpperCamelCase = Path(self.tmpdirname ) save_json(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES["vocab_file"] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES["spm_file"] ) _UpperCamelCase = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def a ( self ): _UpperCamelCase = "<pad>" _UpperCamelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def a ( self ): _UpperCamelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(UpperCAmelCase__ ) , 10_01 ) def a ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 10_01 ) def a ( self ): _UpperCamelCase = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) _UpperCamelCase = tokenizer.tokenize("This is a test" ) self.assertListEqual(UpperCAmelCase__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [2_89, 50, 14, 1_74, 3_86] , ) _UpperCamelCase = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( UpperCAmelCase__ , [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(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [12, 25, 88, 59, 28, 23, 11, 4, 6_06, 3_51, 3_51, 3_51, 7, 16, 70, 50, 76, 84, 10, 4, 8] ) _UpperCamelCase = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [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>", "."] , ) @slow def a ( self ): _UpperCamelCase = {"input_ids": [[37_91, 7_97, 31, 11, 64, 7_97, 31, 24_29, 4_33, 12, 11_76, 12, 20, 7_86, 9_15, 1_42, 24_13, 2_40, 37, 32_38, 7_97, 31, 11, 35, 93, 9_15, 1_42, 24_13, 2_40, 37, 55_40, 5_67, 12_76, 93, 37, 6_10, 40, 62, 4_55, 6_57, 10_42, 1_23, 7_80, 1_77, 37, 3_09, 2_41, 12_98, 5_14, 20, 2_92, 27_37, 1_14, 24_69, 2_41, 85, 64, 3_02, 5_48, 5_28, 4_23, 4, 5_09, 4_06, 4_23, 37, 6_01, 4, 7_77, 3_02, 5_48, 5_28, 4_23, 2_84, 4, 33_88, 5_11, 4_59, 4, 35_55, 40, 3_21, 3_02, 7_05, 4, 33_88, 5_11, 5_83, 3_26, 5, 5, 5, 62, 33_10, 5_60, 1_77, 26_80, 2_17, 15_08, 32, 31, 8_53, 4_18, 64, 5_83, 5_11, 16_05, 62, 35, 93, 5_60, 1_77, 26_80, 2_17, 15_08, 15_21, 64, 5_83, 5_11, 5_19, 62, 20, 15_15, 7_64, 20, 1_49, 2_61, 56_25, 79_72, 20, 55_40, 5_67, 12_76, 93, 39_25, 16_75, 11, 15, 8_02, 79_72, 5_76, 2_17, 15_08, 11, 35, 93, 12_53, 24_41, 15, 2_89, 6_52, 31, 4_16, 3_21, 38_42, 1_15, 40, 9_11, 8, 4_76, 6_19, 4, 3_80, 1_42, 4_23, 3_35, 2_40, 35, 93, 2_64, 8, 11, 3_35, 5_69, 4_20, 1_63, 5, 2], [2_60, 5_48, 5_28, 4_23, 20, 4_51, 20, 26_81, 11_53, 34_34, 20, 55_40, 37, 5_67, 1_26, 12_53, 24_41, 33_76, 4_49, 2_10, 4_31, 15_63, 1_77, 7_67, 55_40, 11, 12_03, 4_72, 11, 29_53, 6_85, 2_85, 3_64, 7_06, 11_53, 20, 67_99, 20, 28_69, 20, 44_64, 1_26, 40, 24_29, 20, 10_40, 8_66, 26_64, 4_18, 20, 3_18, 20, 17_26, 1_86, 20, 2_65, 5_22, 35, 93, 21_91, 46_34, 20, 10_40, 12, 67_99, 15, 2_28, 23_56, 1_42, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [25_75, 26_66, 6_84, 15_82, 11_76, 12, 6_27, 1_49, 6_19, 20, 49_02, 5_63, 11, 20, 1_49, 2_61, 34_20, 23_56, 1_74, 1_42, 47_14, 1_31, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name="facebook/s2t-small-mustc-en-de-st" , revision="a14f04cf0776c02f62a8cb800cf7909e15ea23ad" , ) @require_sentencepiece class A_ ( unittest.TestCase ): '''simple docstring''' _lowerCAmelCase = """valhalla/s2t_mustc_multilinguial_medium""" _lowerCAmelCase = """C\'est trop cool""" _lowerCAmelCase = """Esto es genial""" @classmethod def a ( cls ): _UpperCamelCase = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def a ( self ): self.assertEqual(self.tokenizer.lang_code_to_id["pt"] , 4 ) self.assertEqual(self.tokenizer.lang_code_to_id["ru"] , 6 ) self.assertEqual(self.tokenizer.lang_code_to_id["it"] , 9 ) self.assertEqual(self.tokenizer.lang_code_to_id["de"] , 11 ) def a ( self ): self.assertEqual(self.tokenizer.vocab_size , 1_00_00 ) def a ( self ): self.assertIn(UpperCAmelCase__ , self.tokenizer.all_special_ids ) _UpperCamelCase = [ES_CODE, 4, 16_01, 47, 76_47, 2] _UpperCamelCase = self.tokenizer.decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) _UpperCamelCase = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertNotIn(self.tokenizer.eos_token , UpperCAmelCase__ ) def a ( self ): _UpperCamelCase = "fr" _UpperCamelCase = self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0] , UpperCAmelCase__ ) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id ) def a ( self ): _UpperCamelCase = "fr" self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] ) _UpperCamelCase = "es" self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
138
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int=13 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : str=224 , UpperCAmelCase__ : str=30 , UpperCAmelCase__ : Tuple=400 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Union[str, Any]=[0.5, 0.5, 0.5] , UpperCAmelCase__ : Tuple=[0.5, 0.5, 0.5] , ) ->str: '''simple docstring''' A__ = size if size is not None else {'''height''': 18, '''width''': 18} A__ = parent A__ = batch_size A__ = num_channels A__ = image_size A__ = min_resolution A__ = max_resolution A__ = do_resize A__ = size A__ = do_normalize A__ = image_mean A__ = image_std def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = ViTImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE ( self : List[str]) ->str: '''simple docstring''' A__ = EfficientFormerImageProcessorTester(self) @property def SCREAMING_SNAKE_CASE ( self : Dict) ->int: '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Dict: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_mean''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_std''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_normalize''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''')) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Dict: '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self : str) ->Optional[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random PIL images A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , torch.Tensor) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
87
0
import math from collections.abc import Callable def UpperCamelCase ( _A, _A, _A ): """simple docstring""" __magic_name__ : List[str] = xa __magic_name__ : List[Any] = xa while True: if x_n == x_na or function(lowercase_ ) == function(lowercase_ ): raise ZeroDivisionError("""float division by zero, could not find root""" ) __magic_name__ : int = x_na - ( function(lowercase_ ) / ((function(lowercase_ ) - function(lowercase_ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na __magic_name__ : Tuple = x_na __magic_name__ : Optional[Any] = x_na def UpperCamelCase ( _A ): """simple docstring""" return math.pow(lowercase_, 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
324
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance _lowerCamelCase : Dict = 6_378_137.0 _lowerCamelCase : Union[str, Any] = 6_356_752.314_245 _lowerCamelCase : List[Any] = 6378137 def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> float: """simple docstring""" A__ = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude A__ = atan((1 - flattening) * tan(radians(lowercase_ ) ) ) A__ = atan((1 - flattening) * tan(radians(lowercase_ ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius A__ = haversine_distance(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) / EQUATORIAL_RADIUS # Intermediate P and Q values A__ = (b_lata + b_lata) / 2 A__ = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) A__ = (sin(lowercase_ ) ** 2) * (cos(lowercase_ ) ** 2) A__ = cos(sigma / 2 ) ** 2 A__ = (sigma - sin(lowercase_ )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) A__ = (cos(lowercase_ ) ** 2) * (sin(lowercase_ ) ** 2) A__ = sin(sigma / 2 ) ** 2 A__ = (sigma + sin(lowercase_ )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
87
0
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase (UpperCAmelCase__ ): """simple docstring""" lowerCamelCase__ = '''EncodecFeatureExtractor''' lowerCamelCase__ = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : int ) -> Dict: super().__init__(UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = self.feature_extractor SCREAMING_SNAKE_CASE_ = False def __A ( self : Tuple , __magic_name__ : List[Any]=None , __magic_name__ : List[str]=None , __magic_name__ : Tuple=True ) -> str: return self.tokenizer.get_decoder_prompt_ids(task=UpperCAmelCase__ , language=UpperCAmelCase__ , no_timestamps=UpperCAmelCase__ ) def __call__( self : Any , *__magic_name__ : Tuple , **__magic_name__ : Union[str, Any] ) -> int: if self._in_target_context_manager: return self.current_processor(*UpperCAmelCase__ , **UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = kwargs.pop("audio" , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = kwargs.pop("sampling_rate" , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = kwargs.pop("text" , UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 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 text is not None: SCREAMING_SNAKE_CASE_ = self.tokenizer(UpperCAmelCase__ , **UpperCAmelCase__ ) if audio is not None: SCREAMING_SNAKE_CASE_ = self.feature_extractor(UpperCAmelCase__ , *UpperCAmelCase__ , sampling_rate=UpperCAmelCase__ , **UpperCAmelCase__ ) if audio is None: return inputs elif text is None: return audio_inputs else: SCREAMING_SNAKE_CASE_ = audio_inputs["input_values"] if "padding_mask" in audio_inputs: SCREAMING_SNAKE_CASE_ = audio_inputs["padding_mask"] return inputs def __A ( self : Optional[Any] , *__magic_name__ : List[str] , **__magic_name__ : Any ) -> List[str]: SCREAMING_SNAKE_CASE_ = kwargs.pop("audio" , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = kwargs.pop("padding_mask" , UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 0: SCREAMING_SNAKE_CASE_ = args[0] SCREAMING_SNAKE_CASE_ = args[1:] if audio_values is not None: return self._decode_audio(UpperCAmelCase__ , padding_mask=UpperCAmelCase__ ) else: return self.tokenizer.batch_decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def __A ( self : Dict , *__magic_name__ : Tuple , **__magic_name__ : int ) -> str: return self.tokenizer.decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def __A ( self : List[str] , __magic_name__ : Tuple , __magic_name__ : Optional = None ) -> List[np.ndarray]: SCREAMING_SNAKE_CASE_ = to_numpy(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = audio_values.shape if padding_mask is None: return list(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = to_numpy(UpperCAmelCase__ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) SCREAMING_SNAKE_CASE_ = seq_len - padding_mask.shape[-1] SCREAMING_SNAKE_CASE_ = 1 - self.feature_extractor.padding_value SCREAMING_SNAKE_CASE_ = np.pad(UpperCAmelCase__ , ((0, 0), (0, difference)) , "constant" , constant_values=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = audio_values.tolist() for i in range(UpperCAmelCase__ ): SCREAMING_SNAKE_CASE_ = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] SCREAMING_SNAKE_CASE_ = sliced_audio.reshape(UpperCAmelCase__ , -1 ) return audio_values
140
import heapq import sys import numpy as np _lowerCamelCase : Any = tuple[int, int] class UpperCamelCase_ : '''simple docstring''' def __init__( self : Any) ->str: '''simple docstring''' A__ = [] A__ = set() def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' if not self.empty(): return self.elements[0][0] else: return float('''inf''') def SCREAMING_SNAKE_CASE ( self : Tuple) ->str: '''simple docstring''' return len(self.elements) == 0 def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any]) ->List[str]: '''simple docstring''' if item not in self.set: heapq.heappush(self.elements , (priority, item)) self.set.add(UpperCAmelCase__) else: # update # print("update", item) A__ = [] ((A__) , (A__)) = heapq.heappop(self.elements) while x != item: temp.append((pri, x)) ((A__) , (A__)) = heapq.heappop(self.elements) temp.append((priority, item)) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx)) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : List[Any]) ->Union[str, Any]: '''simple docstring''' if item in self.set: self.set.remove(UpperCAmelCase__) A__ = [] ((A__) , (A__)) = heapq.heappop(self.elements) while x != item: temp.append((pro, x)) ((A__) , (A__)) = heapq.heappop(self.elements) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy)) def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[str]: '''simple docstring''' return self.elements[0][1] def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->int: '''simple docstring''' ((A__) , (A__)) = heapq.heappop(self.elements) self.set.remove(UpperCAmelCase__) return (priority, item) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = np.array(lowercase_ ) A__ = np.array(lowercase_ ) return np.linalg.norm(a - b ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" return consistent_heuristic(lowercase_ , lowercase_ ) // t def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Union[str, Any]: """simple docstring""" return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> Optional[int]: """simple docstring""" A__ = g_function[start] + Wa * heuristics[i](lowercase_ , lowercase_ ) return ans def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = np.chararray((n, n) ) for i in range(lowercase_ ): for j in range(lowercase_ ): A__ = '''*''' for i in range(lowercase_ ): for j in range(lowercase_ ): if (j, (n - 1) - i) in blocks: A__ = '''#''' A__ = '''-''' A__ = back_pointer[goal] while x != start: ((A__) , (A__)) = x # print(x) A__ = '''-''' A__ = back_pointer[x] A__ = '''-''' for i in range(lowercase_ ): for j in range(lowercase_ ): if (i, j) == (0, n - 1): print(grid[i][j] , end=''' ''' ) print('''<-- End position''' , end=''' ''' ) else: print(grid[i][j] , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) print('''PATH TAKEN BY THE ALGORITHM IS:-''' ) A__ = back_pointer[goal] while x != start: print(lowercase_ , end=''' ''' ) A__ = back_pointer[x] print(lowercase_ ) sys.exit() def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) -> Union[str, Any]: """simple docstring""" for itera in range(lowercase_ ): open_list[itera].remove_element(lowercase_ ) # print("s", s) # print("j", j) ((A__) , (A__)) = s A__ = (x - 1, y) A__ = (x + 1, y) A__ = (x, y + 1) A__ = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(lowercase_ ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(lowercase_ ) A__ = -1 A__ = float('''inf''' ) if valid(lowercase_ ) and g_function[neighbours] > g_function[s] + 1: A__ = g_function[s] + 1 A__ = s if neighbours not in close_list_anchor: open_list[0].put(lowercase_ , key(lowercase_ , 0 , lowercase_ , lowercase_ ) ) if neighbours not in close_list_inad: for var in range(1 , lowercase_ ): if key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) <= Wa * key( lowercase_ , 0 , lowercase_ , lowercase_ ): open_list[j].put( lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) def SCREAMING_SNAKE_CASE ( ) -> Optional[int]: """simple docstring""" A__ = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list _lowerCamelCase : Dict = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} _lowerCamelCase : Optional[Any] = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] _lowerCamelCase : Optional[int] = make_common_ground() _lowerCamelCase : Optional[Any] = blocks_blk # hyper parameters _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : List[Any] = 20 _lowerCamelCase : Any = 3 # one consistent and two other inconsistent # start and end destination _lowerCamelCase : str = (0, 0) _lowerCamelCase : Tuple = (n - 1, n - 1) _lowerCamelCase : int = 1 def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = {start: 0, goal: float('''inf''' )} A__ = {start: -1, goal: -1} A__ = [] A__ = set() for i in range(lowercase_ ): open_list.append(PriorityQueue() ) open_list[i].put(lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) A__ = [] A__ = [] while open_list[0].minkey() < float('''inf''' ): for i in range(1 , lowercase_ ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float('''inf''' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: A__ , A__ = open_list[i].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_inad.append(lowercase_ ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('''inf''' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: A__ = open_list[0].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , 0 , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_anchor.append(lowercase_ ) print('''No path found to goal''' ) print() for i in range(n - 1 , -1 , -1 ): for j in range(lowercase_ ): if (j, i) in blocks: print('''#''' , end=''' ''' ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print('''*''' , end=''' ''' ) else: print('''-''' , end=''' ''' ) else: print('''*''' , end=''' ''' ) if (j, i) == (n - 1, n - 1): print('''<-- End position''' , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
87
0
"""simple docstring""" from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCamelCase__ :Tuple = logging.get_logger(__name__) UpperCamelCase__ :Dict = { """EleutherAI/gpt-j-6B""": """https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json""", # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class A( UpperCAmelCase__ ): """simple docstring""" A = "gptj" A = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , SCREAMING_SNAKE_CASE__=5_04_00 , SCREAMING_SNAKE_CASE__=20_48 , SCREAMING_SNAKE_CASE__=40_96 , SCREAMING_SNAKE_CASE__=28 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=64 , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__="gelu_new" , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=0.0_2 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=5_02_56 , SCREAMING_SNAKE_CASE__=5_02_56 , SCREAMING_SNAKE_CASE__=False , **SCREAMING_SNAKE_CASE__ , ) -> Dict: """simple docstring""" _UpperCamelCase :List[Any] = vocab_size _UpperCamelCase :Union[str, Any] = n_positions _UpperCamelCase :Dict = n_embd _UpperCamelCase :List[Any] = n_layer _UpperCamelCase :Optional[Any] = n_head _UpperCamelCase :str = n_inner _UpperCamelCase :str = rotary_dim _UpperCamelCase :Optional[Any] = activation_function _UpperCamelCase :Union[str, Any] = resid_pdrop _UpperCamelCase :List[str] = embd_pdrop _UpperCamelCase :Optional[int] = attn_pdrop _UpperCamelCase :Dict = layer_norm_epsilon _UpperCamelCase :int = initializer_range _UpperCamelCase :List[str] = use_cache _UpperCamelCase :Optional[int] = bos_token_id _UpperCamelCase :Any = eos_token_id super().__init__( bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , tie_word_embeddings=UpperCAmelCase__ , **UpperCAmelCase__ ) class A( UpperCAmelCase__ ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "default" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , ) -> Optional[int]: """simple docstring""" super().__init__(UpperCAmelCase__ , task=UpperCAmelCase__ , patching_specs=UpperCAmelCase__ , use_past=UpperCAmelCase__ ) if not getattr(self._config , '''pad_token_id''' , UpperCAmelCase__ ): # TODO: how to do that better? _UpperCamelCase :Dict = 0 @property def _UpperCamelCase( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" _UpperCamelCase :Any = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: self.fill_with_past_key_values_(UpperCAmelCase__ , direction='''inputs''' ) _UpperCamelCase :Union[str, Any] = {0: '''batch''', 1: '''past_sequence + sequence'''} else: _UpperCamelCase :Any = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def _UpperCamelCase( self ) -> int: """simple docstring""" return self._config.n_layer @property def _UpperCamelCase( self ) -> int: """simple docstring""" return self._config.n_head def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , ) -> Mapping[str, Any]: """simple docstring""" _UpperCamelCase :List[Any] = super(UpperCAmelCase__ , self ).generate_dummy_inputs( UpperCAmelCase__ , batch_size=UpperCAmelCase__ , seq_length=UpperCAmelCase__ , is_pair=UpperCAmelCase__ , framework=UpperCAmelCase__ ) # We need to order the input in the way they appears in the forward() _UpperCamelCase :List[str] = OrderedDict({'''input_ids''': common_inputs['''input_ids''']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch _UpperCamelCase , _UpperCamelCase :List[str] = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values _UpperCamelCase :str = seqlen + 2 _UpperCamelCase :Optional[int] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) _UpperCamelCase :Any = [ (torch.zeros(UpperCAmelCase__ ), torch.zeros(UpperCAmelCase__ )) for _ in range(self.num_layers ) ] _UpperCamelCase :Optional[Any] = common_inputs['''attention_mask'''] if self.use_past: _UpperCamelCase :int = ordered_inputs['''attention_mask'''].dtype _UpperCamelCase :List[str] = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(UpperCAmelCase__ , UpperCAmelCase__ , dtype=UpperCAmelCase__ )] , dim=1 ) return ordered_inputs @property def _UpperCamelCase( self ) -> int: """simple docstring""" return 13
355
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowerCamelCase : Optional[Any] = """Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine""" def SCREAMING_SNAKE_CASE ( ) -> Dict: """simple docstring""" A__ = _ask_options( '''In which compute environment are you running?''' , ['''This machine''', '''AWS (Amazon SageMaker)'''] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A__ = get_sagemaker_input() else: A__ = get_cluster_input() return config def SCREAMING_SNAKE_CASE ( lowercase_=None ) -> List[Any]: """simple docstring""" if subparsers is not None: A__ = subparsers.add_parser('''config''' , description=lowercase_ ) else: A__ = argparse.ArgumentParser('''Accelerate config command''' , description=lowercase_ ) parser.add_argument( '''--config_file''' , default=lowercase_ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=lowercase_ ) return parser def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Any: """simple docstring""" A__ = get_user_input() if args.config_file is not None: A__ = args.config_file else: if not os.path.isdir(lowercase_ ): os.makedirs(lowercase_ ) A__ = default_yaml_config_file if config_file.endswith('''.json''' ): config.to_json_file(lowercase_ ) else: config.to_yaml_file(lowercase_ ) print(f"""accelerate configuration saved at {config_file}""" ) def SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: """simple docstring""" A__ = config_command_parser() A__ = parser.parse_args() config_command(lowercase_ ) if __name__ == "__main__": main()
87
0
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class UpperCAmelCase__ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase_ = JukeboxTokenizer UpperCAmelCase_ = { '''artist''': '''Zac Brown Band''', '''genres''': '''Country''', '''lyrics''': '''I met a traveller from an antique land, Who said "Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away ''', } @require_torch def lowerCAmelCase_ ( self : Dict ): """simple docstring""" import torch _lowercase : List[str] = JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) _lowercase : Union[str, Any] = tokenizer(**self.metas )['''input_ids'''] # fmt: off _lowercase : Optional[Any] = [ torch.tensor([[ 0, 0, 0, 71_69, 5_07, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def lowerCAmelCase_ ( self : List[str] ): """simple docstring""" import torch _lowercase : List[str] = JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) _lowercase : List[Any] = tokenizer(**self.metas )['''input_ids'''] # fmt: off _lowercase : Any = [ torch.tensor([[ 0, 0, 0, 10_69, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
322
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _lowerCamelCase : int = logging.get_logger("""transformers.models.speecht5""") def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Tuple: """simple docstring""" hf_model.apply_weight_norm() A__ = checkpoint['''input_conv.weight_g'''] A__ = checkpoint['''input_conv.weight_v'''] A__ = checkpoint['''input_conv.bias'''] for i in range(len(config.upsample_rates ) ): A__ = checkpoint[f"""upsamples.{i}.1.weight_g"""] A__ = checkpoint[f"""upsamples.{i}.1.weight_v"""] A__ = checkpoint[f"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_g"""] A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_v"""] A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.bias"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_g"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_v"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.bias"""] A__ = checkpoint['''output_conv.1.weight_g'''] A__ = checkpoint['''output_conv.1.weight_v'''] A__ = checkpoint['''output_conv.1.bias'''] hf_model.remove_weight_norm() @torch.no_grad() def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , ) -> str: """simple docstring""" if config_path is not None: A__ = SpeechTaHifiGanConfig.from_pretrained(lowercase_ ) else: A__ = SpeechTaHifiGanConfig() A__ = SpeechTaHifiGan(lowercase_ ) A__ = torch.load(lowercase_ ) load_weights(orig_checkpoint['''model''']['''generator'''] , lowercase_ , lowercase_ ) A__ = np.load(lowercase_ ) A__ = stats[0].reshape(-1 ) A__ = stats[1].reshape(-1 ) A__ = torch.from_numpy(lowercase_ ).float() A__ = torch.from_numpy(lowercase_ ).float() model.save_pretrained(lowercase_ ) if repo_id: print('''Pushing to the hub...''' ) model.push_to_hub(lowercase_ ) if __name__ == "__main__": _lowerCamelCase : Any = argparse.ArgumentParser() parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--stats_path""", required=True, default=None, type=str, help="""Path to stats.npy file""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) _lowerCamelCase : List[str] = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
87
0
"""simple docstring""" from itertools import count def a__ ( __SCREAMING_SNAKE_CASE = 5_0 ) -> int: __lowerCAmelCase: Any = [1] * min_block_length for n in count(lowercase_ ): fill_count_functions.append(1 ) for block_length in range(lowercase_ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_0_0_0_0_0_0: break return n if __name__ == "__main__": print(F'''{solution() = }''')
346
import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class UpperCamelCase_ : '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict=13 , UpperCAmelCase__ : Dict=7 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=99 , UpperCAmelCase__ : Union[str, Any]=32 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : List[Any]=37 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=50 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : List[str]=None , ) ->Union[str, Any]: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = initializer_range A__ = use_labels A__ = scope def SCREAMING_SNAKE_CASE ( self : int) ->Any: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) if self.use_labels: A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = self.get_config() return config, input_ids, input_mask, token_labels def SCREAMING_SNAKE_CASE ( self : int) ->int: '''simple docstring''' return BertGenerationConfig( 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 , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Union[str, Any]: '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = self.prepare_config_and_inputs() A__ = True A__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) A__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , **UpperCAmelCase__ : List[Any] , ) ->Dict: '''simple docstring''' A__ = BertGenerationEncoder(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__) A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[Any] , ) ->Dict: '''simple docstring''' A__ = True A__ = BertGenerationEncoder(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Optional[int] , ) ->Any: '''simple docstring''' A__ = True A__ = True A__ = BertGenerationDecoder(config=UpperCAmelCase__).to(UpperCAmelCase__).eval() # first forward pass A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ , ) A__ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size) A__ = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and A__ = torch.cat([input_ids, next_tokens] , dim=-1) A__ = torch.cat([input_mask, next_mask] , dim=-1) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] # select random slice A__ = ids_tensor((1,) , output_from_past.shape[-1]).item() A__ = output_from_no_past[:, -3:, random_slice_idx].detach() A__ = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3)) def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , *UpperCAmelCase__ : List[str] , ) ->List[Any]: '''simple docstring''' A__ = BertGenerationDecoder(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->List[str]: '''simple docstring''' A__ , A__ , A__ , A__ = self.prepare_config_and_inputs() A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () UpperCAmelCase__ = (BertGenerationDecoder,) if is_torch_available() else () UpperCAmelCase__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Dict: '''simple docstring''' A__ = BertGenerationEncoderTester(self) A__ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any]) ->int: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Optional[Any]: '''simple docstring''' A__ , A__ , A__ , A__ = self.model_tester.prepare_config_and_inputs() A__ = '''bert''' self.model_tester.create_and_check_model(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any: '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() A__ = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*UpperCAmelCase__) @slow def SCREAMING_SNAKE_CASE ( self : Dict) ->List[Any]: '''simple docstring''' A__ = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') self.assertIsNotNone(UpperCAmelCase__) @require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Any) ->Union[str, Any]: '''simple docstring''' A__ = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') A__ = torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]) with torch.no_grad(): A__ = model(UpperCAmelCase__)[0] A__ = torch.Size([1, 8, 1_024]) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4)) @require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' A__ = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') A__ = torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]) with torch.no_grad(): A__ = model(UpperCAmelCase__)[0] A__ = torch.Size([1, 8, 50_358]) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4))
87
0
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase__ ( lowerCAmelCase : Optional[int] ) -> Dict: """simple docstring""" return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) SCREAMING_SNAKE_CASE_ = """ transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions. """ class _UpperCAmelCase ( UpperCAmelCase__ ): @staticmethod def a_ ( lowercase_ ) -> Tuple: UpperCAmelCase = parser.add_parser( 'convert' , help='CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.' , ) train_parser.add_argument('--model_type' , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help='Model\'s type.' ) train_parser.add_argument( '--tf_checkpoint' , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help='TensorFlow checkpoint path or folder.' ) train_parser.add_argument( '--pytorch_dump_output' , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help='Path to the PyTorch saved model output.' ) train_parser.add_argument('--config' , type=UpperCAmelCase__ , default='' , help='Configuration file path or folder.' ) train_parser.add_argument( '--finetuning_task_name' , type=UpperCAmelCase__ , default=UpperCAmelCase__ , help='Optional fine-tuning task name if the TF model was a finetuned model.' , ) train_parser.set_defaults(func=UpperCAmelCase__ ) def __init__( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , *lowercase_ , ) -> Optional[int]: UpperCAmelCase = logging.get_logger('transformers-cli/converting' ) self._logger.info(F"Loading model {model_type}" ) UpperCAmelCase = model_type UpperCAmelCase = tf_checkpoint UpperCAmelCase = pytorch_dump_output UpperCAmelCase = config UpperCAmelCase = finetuning_task_name def a_ ( self ) -> Any: if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(UpperCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) if "ckpt" in self._tf_checkpoint.lower(): UpperCAmelCase = self._tf_checkpoint UpperCAmelCase = '' else: UpperCAmelCase = self._tf_checkpoint UpperCAmelCase = '' convert_transfo_xl_checkpoint_to_pytorch( UpperCAmelCase__ , self._config , self._pytorch_dump_output , UpperCAmelCase__ ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]' )
373
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 _lowerCamelCase : int = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Dict: """simple docstring""" A__ = set() A__ = [] def parse_line(lowercase_ ): for line in fp: if isinstance(lowercase_ , lowercase_ ): A__ = 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(lowercase_ ) > 0: A__ = '''\n'''.join(lowercase_ ) # Only keep the warnings specified in `targets` if any(f""": {x}: """ in warning for x in targets ): selected_warnings.add(lowercase_ ) buffer.clear() continue else: A__ = line.strip() buffer.append(lowercase_ ) if from_gh: for filename in os.listdir(lowercase_ ): A__ = os.path.join(lowercase_ , lowercase_ ) if not os.path.isdir(lowercase_ ): # read the file if filename != "warnings.txt": continue with open(lowercase_ ) as fp: parse_line(lowercase_ ) else: try: with zipfile.ZipFile(lowercase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowercase_ ): # read the file if filename != "warnings.txt": continue with z.open(lowercase_ ) as fp: parse_line(lowercase_ ) 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 SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = set() A__ = [os.path.join(lowercase_ , lowercase_ ) for p in os.listdir(lowercase_ ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(lowercase_ , lowercase_ ) ) return selected_warnings if __name__ == "__main__": def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" return values.split(''',''' ) _lowerCamelCase : int = 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.""", ) _lowerCamelCase : List[Any] = parser.parse_args() _lowerCamelCase : List[str] = 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 _lowerCamelCase : 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("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts _lowerCamelCase : Any = extract_warnings(args.output_dir, args.targets) _lowerCamelCase : Optional[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)
87
0
import argparse import os 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_task_guides.py lowercase : Dict = """src/transformers""" lowercase : Tuple = """docs/source/en/tasks""" def snake_case__ ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): with open(lowercase_ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: A : Optional[int] = f.readlines() # Find the start prompt. A : Optional[Any] = 0 while not lines[start_index].startswith(lowercase_ ): start_index += 1 start_index += 1 A : Any = start_index while not lines[end_index].startswith(lowercase_ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. lowercase : Union[str, Any] = direct_transformers_import(TRANSFORMERS_PATH) lowercase : List[Any] = { """asr.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, """audio_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, """language_modeling.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, """image_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, """masked_language_modeling.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, """multiple_choice.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, """object_detection.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, """question_answering.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, """semantic_segmentation.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, """sequence_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, """summarization.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, """token_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, """translation.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, """video_classification.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, """document_question_answering.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, """monocular_depth_estimation.md""": transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). lowercase : List[str] = { """summarization.md""": ("""nllb""",), """translation.md""": ("""nllb""",), } def snake_case__ ( lowerCamelCase_ ): A : Tuple = TASK_GUIDE_TO_MODELS[task_guide] A : Union[str, Any] = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(lowercase_ , set() ) A : Tuple = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([F'[{name}](../model_doc/{code})' for code, name in model_names.items()] ) + "\n" def snake_case__ ( lowerCamelCase_ , lowerCamelCase_=False ): A , A , A , A : List[Any] = _find_text_in_file( filename=os.path.join(lowercase_ , lowercase_ ) , start_prompt='''<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->''' , end_prompt='''<!--End of the generated tip-->''' , ) A : str = get_model_list_for_task(lowercase_ ) if current_list != new_list: if overwrite: with open(os.path.join(lowercase_ , lowercase_ ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( F'The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`' ''' to fix this.''' ) if __name__ == "__main__": lowercase : List[Any] = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") lowercase : Optional[Any] = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
542
class UpperCamelCase_ : # Public class to implement a graph '''simple docstring''' def __init__( self : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->None: '''simple docstring''' A__ = row A__ = col A__ = graph def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->bool: '''simple docstring''' return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->None: '''simple docstring''' A__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order A__ = [-1, 0, 1, -1, 1, -1, 0, 1] A__ = True # Make those cells visited for k in range(8): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__): self.diffs(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->int: # And finally, count all islands. '''simple docstring''' A__ = [[False for j in range(self.COL)] for i in range(self.ROW)] A__ = 0 for i in range(self.ROW): for j in range(self.COL): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) count += 1 return count
87
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = ['''flax'''] def __init__( self : int , *snake_case : Any , **snake_case : Optional[Any] ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Optional[Any] , *snake_case : List[str] , **snake_case : List[str] ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Any , *snake_case : Tuple , **snake_case : List[str] ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = ['''flax'''] def __init__( self : Dict , *snake_case : Optional[int] , **snake_case : Dict ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Dict , *snake_case : List[Any] , **snake_case : int ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Any , *snake_case : Tuple , **snake_case : Optional[int] ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ['''flax'''] def __init__( self : int , *snake_case : Union[str, Any] , **snake_case : int ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Dict , *snake_case : Optional[int] , **snake_case : List[str] ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Dict , *snake_case : Dict , **snake_case : Optional[Any] ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = ['''flax'''] def __init__( self : str , *snake_case : List[Any] , **snake_case : str ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : int , *snake_case : int , **snake_case : str ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Optional[int] , *snake_case : List[str] , **snake_case : Optional[Any] ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = ['''flax'''] def __init__( self : Optional[int] , *snake_case : Union[str, Any] , **snake_case : List[Any] ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Tuple , *snake_case : Union[str, Any] , **snake_case : Dict ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : List[str] , *snake_case : Optional[Any] , **snake_case : Optional[Any] ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = ['''flax'''] def __init__( self : List[str] , *snake_case : str , **snake_case : List[Any] ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : List[Any] , *snake_case : List[str] , **snake_case : List[str] ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : str , *snake_case : Optional[int] , **snake_case : List[str] ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = ['''flax'''] def __init__( self : Union[str, Any] , *snake_case : Any , **snake_case : Any ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Union[str, Any] , *snake_case : Tuple , **snake_case : Tuple ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Any , *snake_case : List[Any] , **snake_case : int ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = ['''flax'''] def __init__( self : List[str] , *snake_case : Optional[Any] , **snake_case : Optional[Any] ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Optional[Any] , *snake_case : Optional[int] , **snake_case : List[str] ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : int , *snake_case : Dict , **snake_case : str ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ['''flax'''] def __init__( self : int , *snake_case : Union[str, Any] , **snake_case : List[Any] ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Optional[Any] , *snake_case : Optional[Any] , **snake_case : Union[str, Any] ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : int , *snake_case : List[Any] , **snake_case : str ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['''flax'''] def __init__( self : List[str] , *snake_case : Any , **snake_case : int ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : List[Any] , *snake_case : Optional[Any] , **snake_case : Union[str, Any] ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Union[str, Any] , *snake_case : Union[str, Any] , **snake_case : Optional[Any] ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = ['''flax'''] def __init__( self : Tuple , *snake_case : Optional[int] , **snake_case : Optional[int] ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : List[str] , *snake_case : Any , **snake_case : Optional[int] ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Any , *snake_case : Dict , **snake_case : Dict ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = ['''flax'''] def __init__( self : str , *snake_case : Optional[Any] , **snake_case : int ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Union[str, Any] , *snake_case : List[Any] , **snake_case : Dict ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Tuple , *snake_case : List[Any] , **snake_case : Optional[Any] ): """simple docstring""" requires_backends(cls , ['flax'] ) class SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = ['''flax'''] def __init__( self : List[str] , *snake_case : List[Any] , **snake_case : Tuple ): """simple docstring""" requires_backends(self , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Optional[int] , *snake_case : Any , **snake_case : int ): """simple docstring""" requires_backends(cls , ['flax'] ) @classmethod def __UpperCAmelCase ( cls : Optional[int] , *snake_case : int , **snake_case : Any ): """simple docstring""" requires_backends(cls , ['flax'] )
517
from __future__ import annotations import requests _lowerCamelCase : str = set( """approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod_post category clicked content_categories created_utc downs edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta is_original_content is_reddit_media_domain is_video link_flair_css_class link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title name permalink pwls quarantine saved score secure_media secure_media_embed selftext subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type total_awards_received ups upvote_ratio url user_reports""".split() ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = 1 , lowercase_ = "new" , lowercase_ = None ) -> dict: """simple docstring""" A__ = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(lowercase_ ) - valid_terms ) ): A__ = f"""Invalid search term: {invalid_search_terms}""" raise ValueError(lowercase_ ) A__ = requests.get( f"""https://reddit.com/r/{subreddit}/{age}.json?limit={limit}""" , headers={'''User-agent''': '''A random string'''} , ) if response.status_code == 429: raise requests.HTTPError A__ = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(lowercase_ )} A__ = {} for id_ in range(lowercase_ ): A__ = { item: data['''data''']['''children'''][id_]['''data'''][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("""learnpython""", wanted_data=["""title""", """url""", """selftext"""]))
87
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { """facebook/convnextv2-tiny-1k-224""": """https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json""", } class _SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ,UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE :Any = """convnextv2""" def __init__( self : Optional[int] , a__ : Optional[int]=3 , a__ : List[Any]=4 , a__ : int=4 , a__ : List[str]=None , a__ : str=None , a__ : Optional[Any]="gelu" , a__ : Optional[int]=0.02 , a__ : int=1E-12 , a__ : List[str]=0.0 , a__ : int=224 , a__ : int=None , a__ : Any=None , **a__ : Optional[int] , ): super().__init__(**UpperCAmelCase__ ) __magic_name__ = num_channels __magic_name__ = patch_size __magic_name__ = num_stages __magic_name__ = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __magic_name__ = [3, 3, 9, 3] if depths is None else depths __magic_name__ = hidden_act __magic_name__ = initializer_range __magic_name__ = layer_norm_eps __magic_name__ = drop_path_rate __magic_name__ = image_size __magic_name__ = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] __magic_name__ , __magic_name__ = get_aligned_output_features_output_indices( out_features=UpperCAmelCase__ , out_indices=UpperCAmelCase__ , stage_names=self.stage_names )
432
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = JukeboxTokenizer UpperCAmelCase__ = { '''artist''': '''Zac Brown Band''', '''genres''': '''Country''', '''lyrics''': '''I met a traveller from an antique land, Who said "Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away ''', } @require_torch def SCREAMING_SNAKE_CASE ( self : Dict) ->int: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''') A__ = tokenizer(**self.metas)['''input_ids'''] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 7_169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]]), torch.tensor([[0, 0, 0, 1_069, 11]]), torch.tensor([[0, 0, 0, 1_069, 11]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2])) @require_torch def SCREAMING_SNAKE_CASE ( self : List[str]) ->Optional[int]: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''') A__ = tokenizer(**self.metas)['''input_ids'''] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 1_069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]]), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]]), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2]))
87
0
'''simple docstring''' from scipy.stats import spearmanr import datasets _SCREAMING_SNAKE_CASE : List[Any] = """ 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. """ _SCREAMING_SNAKE_CASE : Any = """ 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 """ _SCREAMING_SNAKE_CASE : List[Any] = 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 _snake_case ( datasets.Metric ): def lowerCAmelCase__ ( self ) -> Optional[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 lowerCAmelCase__ ( self , a__ , a__ , a__=False ) -> int: '''simple docstring''' snake_case_ = spearmanr(UpperCAmelCase__ , UpperCAmelCase__ ) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
400
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : str = logging.get_logger(__name__) _lowerCamelCase : List[str] = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''openai-gpt''' UpperCAmelCase__ = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict=40_478 , UpperCAmelCase__ : str=512 , UpperCAmelCase__ : Union[str, Any]=768 , UpperCAmelCase__ : Optional[Any]=12 , UpperCAmelCase__ : Any=12 , UpperCAmelCase__ : Optional[Any]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : List[str]=1e-5 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Any="cls_index" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Optional[Any]=0.1 , **UpperCAmelCase__ : Dict , ) ->Any: '''simple docstring''' A__ = vocab_size A__ = n_positions A__ = n_embd A__ = n_layer A__ = n_head A__ = afn A__ = resid_pdrop A__ = embd_pdrop A__ = attn_pdrop A__ = layer_norm_epsilon A__ = initializer_range A__ = summary_type A__ = summary_use_proj A__ = summary_activation A__ = summary_first_dropout A__ = summary_proj_to_labels super().__init__(**UpperCAmelCase__)
87
0
'''simple docstring''' import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() snake_case_ : Any = logging.get_logger(__name__) snake_case_ : Optional[Any] = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn.grep_linear""": """encoder.layers.*.attention.gru_rel_pos_linear""", """self_attn.relative_attention_bias""": """encoder.layers.*.attention.rel_attn_embed""", """self_attn.grep_a""": """encoder.layers.*.attention.gru_rel_pos_const""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } snake_case_ : int = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def lowercase__( _UpperCamelCase : int , _UpperCamelCase : List[str] , _UpperCamelCase : Dict , _UpperCamelCase : Dict , _UpperCamelCase : List[str] )-> Optional[Any]: """simple docstring""" for attribute in key.split("." ): _UpperCamelCase = getattr(lowercase_ , lowercase_ ) if weight_type is not None: _UpperCamelCase = getattr(lowercase_ , lowercase_ ).shape else: _UpperCamelCase = hf_pointer.shape assert hf_shape == value.shape, ( f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" f" {value.shape} for {full_name}" ) if weight_type == "weight": _UpperCamelCase = value elif weight_type == "weight_g": _UpperCamelCase = value elif weight_type == "weight_v": _UpperCamelCase = value elif weight_type == "bias": _UpperCamelCase = value else: _UpperCamelCase = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def lowercase__( _UpperCamelCase : Dict , _UpperCamelCase : Optional[int] )-> Dict: """simple docstring""" _UpperCamelCase = [] _UpperCamelCase = fairseq_model.state_dict() _UpperCamelCase = hf_model.feature_extractor for name, value in fairseq_dict.items(): _UpperCamelCase = False if "conv_layers" in name: load_conv_layer( lowercase_ , lowercase_ , lowercase_ , lowercase_ , hf_model.config.feat_extract_norm == "group" , ) _UpperCamelCase = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: _UpperCamelCase = True if "*" in mapped_key: _UpperCamelCase = name.split(lowercase_ )[0].split("." )[-2] _UpperCamelCase = mapped_key.replace("*" , lowercase_ ) if "weight_g" in name: _UpperCamelCase = "weight_g" elif "weight_v" in name: _UpperCamelCase = "weight_v" elif "bias" in name and "relative_attention_bias" not in name: _UpperCamelCase = "bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj _UpperCamelCase = "weight" else: _UpperCamelCase = None set_recursively(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) continue if not is_used: unused_weights.append(lowercase_ ) logger.warning(f"Unused weights: {unused_weights}" ) def lowercase__( _UpperCamelCase : Optional[int] , _UpperCamelCase : Any , _UpperCamelCase : List[Any] , _UpperCamelCase : Dict , _UpperCamelCase : Union[str, Any] )-> Optional[Any]: """simple docstring""" _UpperCamelCase = full_name.split("conv_layers." )[-1] _UpperCamelCase = name.split("." ) _UpperCamelCase = int(items[0] ) _UpperCamelCase = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) _UpperCamelCase = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) _UpperCamelCase = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) _UpperCamelCase = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) _UpperCamelCase = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(lowercase_ ) @torch.no_grad() def lowercase__( _UpperCamelCase : List[Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : List[str]=None )-> List[Any]: """simple docstring""" _UpperCamelCase = torch.load(lowercase_ ) _UpperCamelCase = WavLMConfigOrig(checkpoint["cfg"] ) _UpperCamelCase = WavLMOrig(lowercase_ ) model.load_state_dict(checkpoint["model"] ) model.eval() if config_path is not None: _UpperCamelCase = WavLMConfig.from_pretrained(lowercase_ ) else: _UpperCamelCase = WavLMConfig() _UpperCamelCase = WavLMModel(lowercase_ ) recursively_load_weights(lowercase_ , lowercase_ ) hf_wavlm.save_pretrained(lowercase_ ) if __name__ == "__main__": snake_case_ : str = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') snake_case_ : Optional[Any] = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
138
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 __magic_name__: int = 10 def UpperCamelCase ( _A ): """simple docstring""" __magic_name__ : str = 1 __magic_name__ : int = max(lowercase_ ) while placement <= max_digit: # declare and initialize empty buckets __magic_name__ : Optional[int] = [[] for _ in range(lowercase_ )] # split list_of_ints between the buckets for i in list_of_ints: __magic_name__ : Any = int((i / placement) % RADIX ) buckets[tmp].append(lowercase_ ) # put each buckets' contents into list_of_ints __magic_name__ : str = 0 for b in range(lowercase_ ): for i in buckets[b]: __magic_name__ : List[str] = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
324
import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None ) -> Dict: """simple docstring""" if "." in tensor_name: A__ = tensor_name.split('''.''' ) for split in splits[:-1]: A__ = getattr(lowercase_ , lowercase_ ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) A__ = new_module A__ = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(f"""{module} does not have a parameter or a buffer named {tensor_name}.""" ) A__ = tensor_name in module._buffers A__ = getattr(lowercase_ , lowercase_ ) if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None: raise ValueError(f"""{tensor_name} is on the meta device, we need a `value` to put in on {device}.""" ) A__ = False A__ = False if is_buffer or not is_bitsandbytes_available(): A__ = False A__ = False else: A__ = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) A__ = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: A__ = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to('''cpu''' ) if value.dtype == torch.inta: A__ = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse( '''0.37.2''' ) if not is_abit_serializable: raise ValueError( '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ''' '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' ) else: A__ = torch.tensor(lowercase_ , device='''cpu''' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , lowercase_ ) and fpaa_statistics is None: A__ = new_value.T A__ = old_value.__dict__ if is_abit: A__ = bnb.nn.IntaParams(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) elif is_abit: A__ = bnb.nn.Paramsabit(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) A__ = new_value if fpaa_statistics is not None: setattr(module.weight , '''SCB''' , fpaa_statistics.to(lowercase_ ) ) else: if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to(lowercase_ ) else: A__ = torch.tensor(lowercase_ , device=lowercase_ ) if is_buffer: A__ = new_value else: A__ = nn.Parameter(lowercase_ , requires_grad=old_value.requires_grad ) A__ = new_value def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=False ) -> Dict: """simple docstring""" for name, module in model.named_children(): if current_key_name is None: A__ = [] current_key_name.append(lowercase_ ) if (isinstance(lowercase_ , nn.Linear ) or isinstance(lowercase_ , lowercase_ )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '''.'''.join(lowercase_ ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(lowercase_ , lowercase_ ): A__ , A__ = module.weight.shape else: A__ = module.in_features A__ = module.out_features if quantization_config.quantization_method() == "llm_int8": A__ = bnb.nn.LinearabitLt( lowercase_ , lowercase_ , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) A__ = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: A__ = bnb.nn.Linearabit( lowercase_ , lowercase_ , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) A__ = True # Store the module class in case we need to transpose the weight later A__ = type(lowercase_ ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(lowercase_ ) if len(list(module.children() ) ) > 0: A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ , has_been_replaced=lowercase_ , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None ) -> Tuple: """simple docstring""" A__ = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Dict: """simple docstring""" warnings.warn( '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , lowercase_ , ) return replace_with_bnb_linear(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Optional[Any]: """simple docstring""" warnings.warn( '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , lowercase_ , ) return set_module_quantized_tensor_to_device(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]: """simple docstring""" A__ = deepcopy(lowercase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() A__ = find_tied_parameters(lowercase_ ) # For compatibility with Accelerate < 0.18 if isinstance(lowercase_ , lowercase_ ): A__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: A__ = sum(lowercase_ , [] ) A__ = len(lowercase_ ) > 0 # Check if it is a base model A__ = not hasattr(lowercase_ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head A__ = list(model.named_children() ) A__ = [list_modules[-1][0]] # add last module together with tied weights A__ = set(lowercase_ ) - set(lowercase_ ) A__ = list(set(lowercase_ ) ) + list(lowercase_ ) # remove ".weight" from the keys A__ = ['''.weight''', '''.bias'''] A__ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: A__ = name.replace(lowercase_ , '''''' ) filtered_module_names.append(lowercase_ ) return filtered_module_names
87
0
import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def a__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): if openai_config_file == "": SCREAMING_SNAKE_CASE_ = OpenAIGPTConfig() else: SCREAMING_SNAKE_CASE_ = OpenAIGPTConfig.from_json_file(lowercase_ ) SCREAMING_SNAKE_CASE_ = OpenAIGPTModel(lowercase_ ) # Load weights from numpy load_tf_weights_in_openai_gpt(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model SCREAMING_SNAKE_CASE_ = pytorch_dump_folder_path + "/" + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ = pytorch_dump_folder_path + "/" + CONFIG_NAME print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) print(F'''Save configuration file to {pytorch_config_dump_path}''' ) with open(lowercase_ , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": A : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--openai_checkpoint_folder_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( "--openai_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained OpenAI model. \n" "This specifies the model architecture." ), ) A : Optional[Any] = parser.parse_args() convert_openai_checkpoint_to_pytorch( args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path )
140
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) _lowerCamelCase : str = 299792458 # Symbols _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = symbols("""ct x y z""") def SCREAMING_SNAKE_CASE ( lowercase_ ) -> float: """simple docstring""" 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 ( lowercase_ ) -> float: """simple docstring""" return 1 / sqrt(1 - beta(lowercase_ ) ** 2 ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> np.ndarray: """simple docstring""" return np.array( [ [gamma(lowercase_ ), -gamma(lowercase_ ) * beta(lowercase_ ), 0, 0], [-gamma(lowercase_ ) * beta(lowercase_ ), gamma(lowercase_ ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = None ) -> np.ndarray: """simple docstring""" if event is None: A__ = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(lowercase_ ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: _lowerCamelCase : Tuple = transform(29979245) 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 _lowerCamelCase : int = {ct: c, x: 1, y: 1, z: 1} _lowerCamelCase : Any = [four_vector[i].subs(sub_dict) for i in range(4)] print(F'''\n{numerical_vector}''')
87
0
"""simple docstring""" import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 UpperCamelCase__ :Optional[Any] = { """return_dict""": False, """output_hidden_states""": True, """output_attentions""": True, """torchscript""": True, """torch_dtype""": """float16""", """use_bfloat16""": True, """tf_legacy_loss""": True, """pruned_heads""": {"""a""": 1}, """tie_word_embeddings""": False, """is_decoder""": True, """cross_attention_hidden_size""": 128, """add_cross_attention""": True, """tie_encoder_decoder""": True, """max_length""": 50, """min_length""": 3, """do_sample""": True, """early_stopping""": True, """num_beams""": 3, """num_beam_groups""": 3, """diversity_penalty""": 0.5, """temperature""": 2.0, """top_k""": 10, """top_p""": 0.7, """typical_p""": 0.2, """repetition_penalty""": 0.8, """length_penalty""": 0.8, """no_repeat_ngram_size""": 5, """encoder_no_repeat_ngram_size""": 5, """bad_words_ids""": [1, 2, 3], """num_return_sequences""": 3, """chunk_size_feed_forward""": 5, """output_scores""": True, """return_dict_in_generate""": True, """forced_bos_token_id""": 2, """forced_eos_token_id""": 3, """remove_invalid_values""": True, """architectures""": ["""BertModel"""], """finetuning_task""": """translation""", """id2label""": {0: """label"""}, """label2id""": {"""label""": """0"""}, """tokenizer_class""": """BertTokenizerFast""", """prefix""": """prefix""", """bos_token_id""": 6, """pad_token_id""": 7, """eos_token_id""": 8, """sep_token_id""": 9, """decoder_start_token_id""": 10, """exponential_decay_length_penalty""": (5, 1.01), """suppress_tokens""": [0, 1], """begin_suppress_tokens""": 2, """task_specific_params""": {"""translation""": """some_params"""}, """problem_type""": """regression""", } @is_staging_test class A( unittest.TestCase ): """simple docstring""" @classmethod def _UpperCamelCase( cls ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase :List[str] = TOKEN HfFolder.save_token(UpperCAmelCase__ ) @classmethod def _UpperCamelCase( cls ) -> int: """simple docstring""" try: delete_repo(token=cls._token , repo_id='''test-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-config-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-config''' ) except HTTPError: pass def _UpperCamelCase( self ) -> Any: """simple docstring""" _UpperCamelCase :str = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub('''test-config''' , use_auth_token=self._token ) _UpperCamelCase :Any = BertConfig.from_pretrained(f"{USER}/test-config" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase__ , getattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(UpperCAmelCase__ , repo_id='''test-config''' , push_to_hub=UpperCAmelCase__ , use_auth_token=self._token ) _UpperCamelCase :Tuple = BertConfig.from_pretrained(f"{USER}/test-config" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase__ , getattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) def _UpperCamelCase( self ) -> str: """simple docstring""" _UpperCamelCase :Union[str, Any] = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub('''valid_org/test-config-org''' , use_auth_token=self._token ) _UpperCamelCase :Tuple = BertConfig.from_pretrained('''valid_org/test-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase__ , getattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( UpperCAmelCase__ , repo_id='''valid_org/test-config-org''' , push_to_hub=UpperCAmelCase__ , use_auth_token=self._token ) _UpperCamelCase :str = BertConfig.from_pretrained('''valid_org/test-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase__ , getattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) def _UpperCamelCase( self ) -> Any: """simple docstring""" CustomConfig.register_for_auto_class() _UpperCamelCase :Optional[Any] = CustomConfig(attribute=42 ) config.push_to_hub('''test-dynamic-config''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {'''AutoConfig''': '''custom_configuration.CustomConfig'''} ) _UpperCamelCase :int = AutoConfig.from_pretrained(f"{USER}/test-dynamic-config" , trust_remote_code=UpperCAmelCase__ ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , '''CustomConfig''' ) self.assertEqual(new_config.attribute , 42 ) class A( unittest.TestCase ): """simple docstring""" def _UpperCamelCase( self ) -> Tuple: """simple docstring""" _UpperCamelCase :List[str] = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated _UpperCamelCase :Tuple = c.n_embd + 1 # int _UpperCamelCase :Optional[int] = c.resid_pdrop + 1.0 # float _UpperCamelCase :List[Any] = not c.scale_attn_weights # bool _UpperCamelCase :Any = c.summary_type + '''foo''' # str c.update_from_string( f"n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}" ) self.assertEqual(UpperCAmelCase__ , c.n_embd , '''mismatch for key: n_embd''' ) self.assertEqual(UpperCAmelCase__ , c.resid_pdrop , '''mismatch for key: resid_pdrop''' ) self.assertEqual(UpperCAmelCase__ , c.scale_attn_weights , '''mismatch for key: scale_attn_weights''' ) self.assertEqual(UpperCAmelCase__ , c.summary_type , '''mismatch for key: summary_type''' ) def _UpperCamelCase( self ) -> Any: """simple docstring""" _UpperCamelCase :str = PretrainedConfig() _UpperCamelCase :List[Any] = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( UpperCAmelCase__ , ['''is_encoder_decoder''', '''_name_or_path''', '''_commit_hash''', '''transformers_version'''] ) _UpperCamelCase :List[Any] = [key for key, value in config_common_kwargs.items() if value == getattr(UpperCAmelCase__ , UpperCAmelCase__ )] if len(UpperCAmelCase__ ) > 0: raise ValueError( '''The following keys are set with the default values in''' ''' `test_configuration_common.config_common_kwargs` pick another value for them:''' f" {', '.join(UpperCAmelCase__ )}." ) def _UpperCamelCase( self ) -> List[str]: """simple docstring""" with self.assertRaises(UpperCAmelCase__ ): # config is in subfolder, the following should not work without specifying the subfolder _UpperCamelCase :Union[str, Any] = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' ) _UpperCamelCase :List[str] = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' , subfolder='''bert''' ) self.assertIsNotNone(UpperCAmelCase__ ) def _UpperCamelCase( self ) -> Dict: """simple docstring""" _UpperCamelCase :Union[str, Any] = mock.Mock() _UpperCamelCase :Tuple = 5_00 _UpperCamelCase :Any = {} _UpperCamelCase :List[str] = HTTPError _UpperCamelCase :Tuple = {} # Download this model to make sure it's in the cache. _UpperCamelCase :Tuple = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=UpperCAmelCase__ ) as mock_head: _UpperCamelCase :List[Any] = BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # This check we did call the fake head request mock_head.assert_called() def _UpperCamelCase( self ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase :Tuple = BertConfig.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json''' ) def _UpperCamelCase( self ) -> Optional[int]: """simple docstring""" _UpperCamelCase :Optional[Any] = AutoConfig.from_pretrained('''bert-base-cased''' ) _UpperCamelCase :Union[str, Any] = ['''config.4.0.0.json'''] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(UpperCAmelCase__ ) _UpperCamelCase :Any = 2 json.dump(configuration.to_dict() , open(os.path.join(UpperCAmelCase__ , '''config.4.0.0.json''' ) , '''w''' ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 _UpperCamelCase :str = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 _UpperCamelCase :Tuple = ['''config.42.0.0.json'''] _UpperCamelCase :Tuple = 7_68 configuration.save_pretrained(UpperCAmelCase__ ) shutil.move(os.path.join(UpperCAmelCase__ , '''config.4.0.0.json''' ) , os.path.join(UpperCAmelCase__ , '''config.42.0.0.json''' ) ) _UpperCamelCase :Union[str, Any] = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertEqual(new_configuration.hidden_size , 7_68 ) def _UpperCamelCase( self ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase :List[Any] = '''hf-internal-testing/test-two-configs''' import transformers as new_transformers _UpperCamelCase :Union[str, Any] = '''v4.0.0''' _UpperCamelCase , _UpperCamelCase :Optional[Any] = new_transformers.models.auto.AutoConfig.from_pretrained( UpperCAmelCase__ , return_unused_kwargs=UpperCAmelCase__ ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(UpperCAmelCase__ , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers _UpperCamelCase :Optional[Any] = '''v3.0.0''' _UpperCamelCase :Optional[int] = old_transformers.models.auto.AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertEqual(old_configuration.hidden_size , 7_68 )
355
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> list: """simple docstring""" if len(lowercase_ ) <= 1: return [tuple(lowercase_ )] A__ = [] def generate(lowercase_ , lowercase_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , lowercase_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even A__ , A__ = arr[k - 1], arr[i] else: # k is odd A__ , A__ = arr[k - 1], arr[0] generate(k - 1 , lowercase_ ) generate(len(lowercase_ ) , lowercase_ ) return res if __name__ == "__main__": _lowerCamelCase : int = input("""Enter numbers separated by a comma:\n""").strip() _lowerCamelCase : str = [int(item) for item in user_input.split(""",""")] print(heaps(arr))
87
0
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class UpperCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def lowerCAmelCase_ ( self : Dict ): """simple docstring""" _lowercase : Dict = 0 def lowerCAmelCase_ ( self : Any ): """simple docstring""" _lowercase : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase_ ( self : Optional[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowercase : Tuple = Path(UpperCAmelCase__ ) / '''preprocessor_config.json''' _lowercase : List[Any] = Path(UpperCAmelCase__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(UpperCAmelCase__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(UpperCAmelCase__ , '''w''' ) ) _lowercase : Optional[Any] = AutoImageProcessor.from_pretrained(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase_ ( self : List[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowercase : Optional[Any] = Path(UpperCAmelCase__ ) / '''preprocessor_config.json''' _lowercase : List[Any] = Path(UpperCAmelCase__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(UpperCAmelCase__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(UpperCAmelCase__ , '''w''' ) ) _lowercase : Union[str, Any] = AutoImageProcessor.from_pretrained(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase_ ( self : Optional[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowercase : Any = CLIPConfig() # Create a dummy config file with image_proceesor_type _lowercase : int = Path(UpperCAmelCase__ ) / '''preprocessor_config.json''' _lowercase : Any = Path(UpperCAmelCase__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(UpperCAmelCase__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(UpperCAmelCase__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally _lowercase : List[Any] = AutoImageProcessor.from_pretrained(UpperCAmelCase__ ).to_dict() config_dict.pop('''image_processor_type''' ) _lowercase : str = CLIPImageProcessor(**UpperCAmelCase__ ) # save in new folder model_config.save_pretrained(UpperCAmelCase__ ) config.save_pretrained(UpperCAmelCase__ ) _lowercase : Optional[Any] = AutoImageProcessor.from_pretrained(UpperCAmelCase__ ) # make sure private variable is not incorrectly saved _lowercase : int = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase_ ( self : List[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowercase : Tuple = Path(UpperCAmelCase__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(UpperCAmelCase__ , '''w''' ) , ) _lowercase : List[Any] = AutoImageProcessor.from_pretrained(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase_ ( self : int ): """simple docstring""" with self.assertRaisesRegex( UpperCAmelCase__ , '''clip-base is not a local folder and is not a valid model identifier''' ): _lowercase : Optional[int] = AutoImageProcessor.from_pretrained('''clip-base''' ) def lowerCAmelCase_ ( self : List[str] ): """simple docstring""" with self.assertRaisesRegex( UpperCAmelCase__ , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): _lowercase : Tuple = AutoImageProcessor.from_pretrained(UpperCAmelCase__ , revision='''aaaaaa''' ) def lowerCAmelCase_ ( self : Optional[int] ): """simple docstring""" with self.assertRaisesRegex( UpperCAmelCase__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): _lowercase : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def lowerCAmelCase_ ( self : List[str] ): """simple docstring""" with self.assertRaises(UpperCAmelCase__ ): _lowercase : Tuple = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(UpperCAmelCase__ ): _lowercase : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=UpperCAmelCase__ ) _lowercase : Union[str, Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=UpperCAmelCase__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(UpperCAmelCase__ ) _lowercase : Union[str, Any] = AutoImageProcessor.from_pretrained(UpperCAmelCase__ , trust_remote_code=UpperCAmelCase__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def lowerCAmelCase_ ( self : Optional[Any] ): """simple docstring""" try: AutoConfig.register('''custom''' , UpperCAmelCase__ ) AutoImageProcessor.register(UpperCAmelCase__ , UpperCAmelCase__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(UpperCAmelCase__ ): AutoImageProcessor.register(UpperCAmelCase__ , UpperCAmelCase__ ) with tempfile.TemporaryDirectory() as tmpdirname: _lowercase : List[Any] = Path(UpperCAmelCase__ ) / '''preprocessor_config.json''' _lowercase : Tuple = Path(UpperCAmelCase__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(UpperCAmelCase__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(UpperCAmelCase__ , '''w''' ) ) _lowercase : Tuple = CustomImageProcessor.from_pretrained(UpperCAmelCase__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(UpperCAmelCase__ ) _lowercase : int = AutoImageProcessor.from_pretrained(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def lowerCAmelCase_ ( self : Tuple ): """simple docstring""" class UpperCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase_ = True try: AutoConfig.register('''custom''' , UpperCAmelCase__ ) AutoImageProcessor.register(UpperCAmelCase__ , UpperCAmelCase__ ) # If remote code is not set, the default is to use local _lowercase : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. _lowercase : Union[str, Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=UpperCAmelCase__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub _lowercase : List[str] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=UpperCAmelCase__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(UpperCAmelCase__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
322
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Union[str, Any]: """simple docstring""" A__ = np.max(_outputs , axis=-1 , keepdims=lowercase_ ) A__ = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowercase_ ) class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''sigmoid''' UpperCAmelCase__ = '''softmax''' UpperCAmelCase__ = '''none''' @add_end_docstrings( UpperCAmelCase__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = False UpperCAmelCase__ = ClassificationFunction.NONE def __init__( self : Any , **UpperCAmelCase__ : Optional[Any]) ->str: '''simple docstring''' super().__init__(**UpperCAmelCase__) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int="" , **UpperCAmelCase__ : Any) ->int: '''simple docstring''' A__ = tokenizer_kwargs A__ = {} if hasattr(self.model.config , '''return_all_scores''') and return_all_scores is None: A__ = self.model.config.return_all_scores if isinstance(UpperCAmelCase__ , UpperCAmelCase__) or top_k is None: A__ = top_k A__ = False elif return_all_scores is not None: warnings.warn( '''`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of''' ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.''' , UpperCAmelCase__ , ) if return_all_scores: A__ = None else: A__ = 1 if isinstance(UpperCAmelCase__ , UpperCAmelCase__): A__ = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: A__ = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self : str , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : Optional[int]) ->Union[str, Any]: '''simple docstring''' A__ = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__) # TODO try and retrieve it in a nicer way from _sanitize_parameters. A__ = '''top_k''' not in kwargs if isinstance(args[0] , UpperCAmelCase__) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : Any , **UpperCAmelCase__ : str) ->Dict[str, GenericTensor]: '''simple docstring''' A__ = self.framework if isinstance(UpperCAmelCase__ , UpperCAmelCase__): return self.tokenizer(**UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__) and len(UpperCAmelCase__) == 1 and isinstance(inputs[0] , UpperCAmelCase__) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a''' ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.''') return self.tokenizer(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : Tuple) ->Tuple: '''simple docstring''' return self.model(**UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : str=True) ->Dict: '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: A__ = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: A__ = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''') and function_to_apply is None: A__ = self.model.config.function_to_apply else: A__ = ClassificationFunction.NONE A__ = model_outputs['''logits'''][0] A__ = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: A__ = sigmoid(UpperCAmelCase__) elif function_to_apply == ClassificationFunction.SOFTMAX: A__ = softmax(UpperCAmelCase__) elif function_to_apply == ClassificationFunction.NONE: A__ = outputs else: raise ValueError(f"""Unrecognized `function_to_apply` argument: {function_to_apply}""") if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} A__ = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(UpperCAmelCase__) ] if not _legacy: dict_scores.sort(key=lambda UpperCAmelCase__: x["score"] , reverse=UpperCAmelCase__) if top_k is not None: A__ = dict_scores[:top_k] return dict_scores
87
0
"""simple docstring""" import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch __A = """sshleifer/bart-tiny-random""" __A = """patrickvonplaten/t5-tiny-random""" @require_torch class snake_case ( unittest.TestCase ): @cached_property def lowercase_ ( self : List[Any])-> str: '''simple docstring''' return AutoConfig.from_pretrained(UpperCAmelCase__) def lowercase_ ( self : Optional[int])-> Dict: '''simple docstring''' __lowerCAmelCase , *__lowerCAmelCase: int = create_student_by_copying_alternating_layers(UpperCAmelCase__ , tempfile.mkdtemp() , e=1 , d=1) self.assertEqual(student.config.num_hidden_layers , 1) def lowercase_ ( self : int)-> Any: '''simple docstring''' __lowerCAmelCase , *__lowerCAmelCase: Union[str, Any] = create_student_by_copying_alternating_layers(UpperCAmelCase__ , tempfile.mkdtemp() , e=1 , d=UpperCAmelCase__) def lowercase_ ( self : List[Any])-> Union[str, Any]: '''simple docstring''' __lowerCAmelCase , *__lowerCAmelCase: List[str] = create_student_by_copying_alternating_layers(UpperCAmelCase__ , tempfile.mkdtemp() , e=1 , d=UpperCAmelCase__) self.assertEqual(student.config.encoder_layers , 1) self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers) def lowercase_ ( self : str)-> Optional[int]: '''simple docstring''' __lowerCAmelCase , *__lowerCAmelCase: Dict = create_student_by_copying_alternating_layers(UpperCAmelCase__ , tempfile.mkdtemp() , e=1 , d=1) self.assertEqual(student.config.encoder_layers , 1) self.assertEqual(student.config.decoder_layers , 1) def lowercase_ ( self : List[Any])-> Optional[int]: '''simple docstring''' with self.assertRaises(UpperCAmelCase__): create_student_by_copying_alternating_layers(UpperCAmelCase__ , tempfile.mkdtemp() , e=UpperCAmelCase__ , d=UpperCAmelCase__)
346
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase : Any = {"""configuration_xlnet""": ["""XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : int = ["""XLNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : int = ["""XLNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Union[str, Any] = [ """XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLNetForMultipleChoice""", """XLNetForQuestionAnswering""", """XLNetForQuestionAnsweringSimple""", """XLNetForSequenceClassification""", """XLNetForTokenClassification""", """XLNetLMHeadModel""", """XLNetModel""", """XLNetPreTrainedModel""", """load_tf_weights_in_xlnet""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Dict = [ """TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLNetForMultipleChoice""", """TFXLNetForQuestionAnsweringSimple""", """TFXLNetForSequenceClassification""", """TFXLNetForTokenClassification""", """TFXLNetLMHeadModel""", """TFXLNetMainLayer""", """TFXLNetModel""", """TFXLNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys _lowerCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
87
0
"""simple docstring""" SCREAMING_SNAKE_CASE_ = { """Pillow""": """Pillow<10.0.0""", """accelerate""": """accelerate>=0.20.3""", """av""": """av==9.2.0""", """beautifulsoup4""": """beautifulsoup4""", """black""": """black~=23.1""", """codecarbon""": """codecarbon==1.2.0""", """cookiecutter""": """cookiecutter==1.7.3""", """dataclasses""": """dataclasses""", """datasets""": """datasets!=2.5.0""", """decord""": """decord==0.6.0""", """deepspeed""": """deepspeed>=0.9.3""", """diffusers""": """diffusers""", """dill""": """dill<0.3.5""", """evaluate""": """evaluate>=0.2.0""", """fairscale""": """fairscale>0.3""", """faiss-cpu""": """faiss-cpu""", """fastapi""": """fastapi""", """filelock""": """filelock""", """flax""": """flax>=0.4.1,<=0.7.0""", """ftfy""": """ftfy""", """fugashi""": """fugashi>=1.0""", """GitPython""": """GitPython<3.1.19""", """hf-doc-builder""": """hf-doc-builder>=0.3.0""", """huggingface-hub""": """huggingface-hub>=0.14.1,<1.0""", """importlib_metadata""": """importlib_metadata""", """ipadic""": """ipadic>=1.0.0,<2.0""", """isort""": """isort>=5.5.4""", """jax""": """jax>=0.2.8,!=0.3.2,<=0.4.13""", """jaxlib""": """jaxlib>=0.1.65,<=0.4.13""", """jieba""": """jieba""", """kenlm""": """kenlm""", """keras-nlp""": """keras-nlp>=0.3.1""", """librosa""": """librosa""", """nltk""": """nltk""", """natten""": """natten>=0.14.6""", """numpy""": """numpy>=1.17""", """onnxconverter-common""": """onnxconverter-common""", """onnxruntime-tools""": """onnxruntime-tools>=1.4.2""", """onnxruntime""": """onnxruntime>=1.4.0""", """opencv-python""": """opencv-python""", """optuna""": """optuna""", """optax""": """optax>=0.0.8,<=0.1.4""", """packaging""": """packaging>=20.0""", """parameterized""": """parameterized""", """phonemizer""": """phonemizer""", """protobuf""": """protobuf""", """psutil""": """psutil""", """pyyaml""": """pyyaml>=5.1""", """pydantic""": """pydantic<2""", """pytest""": """pytest>=7.2.0""", """pytest-timeout""": """pytest-timeout""", """pytest-xdist""": """pytest-xdist""", """python""": """python>=3.8.0""", """ray[tune]""": """ray[tune]""", """regex""": """regex!=2019.12.17""", """requests""": """requests""", """rhoknp""": """rhoknp>=1.1.0,<1.3.1""", """rjieba""": """rjieba""", """rouge-score""": """rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1""", """ruff""": """ruff>=0.0.241,<=0.0.259""", """sacrebleu""": """sacrebleu>=1.4.12,<2.0.0""", """sacremoses""": """sacremoses""", """safetensors""": """safetensors>=0.3.1""", """sagemaker""": """sagemaker>=2.31.0""", """scikit-learn""": """scikit-learn""", """sentencepiece""": """sentencepiece>=0.1.91,!=0.1.92""", """sigopt""": """sigopt""", """starlette""": """starlette""", """sudachipy""": """sudachipy>=0.6.6""", """sudachidict_core""": """sudachidict_core>=20220729""", """tensorflow-cpu""": """tensorflow-cpu>=2.6,<2.14""", """tensorflow""": """tensorflow>=2.6,<2.14""", """tensorflow-text""": """tensorflow-text<2.14""", """tf2onnx""": """tf2onnx""", """timeout-decorator""": """timeout-decorator""", """timm""": """timm""", """tokenizers""": """tokenizers>=0.11.1,!=0.11.3,<0.14""", """torch""": """torch>=1.9,!=1.12.0""", """torchaudio""": """torchaudio""", """torchvision""": """torchvision""", """pyctcdecode""": """pyctcdecode>=0.4.0""", """tqdm""": """tqdm>=4.27""", """unidic""": """unidic>=1.0.2""", """unidic_lite""": """unidic_lite>=1.0.7""", """urllib3""": """urllib3<2.0.0""", """uvicorn""": """uvicorn""", }
373
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 : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : Union[str, Any] = { """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""", """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''mobilenet_v1''' def __init__( self : Optional[int] , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : Optional[Any]=224 , UpperCAmelCase__ : Optional[int]=1.0 , UpperCAmelCase__ : Optional[int]=8 , UpperCAmelCase__ : Tuple="relu6" , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Dict=0.999 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : Optional[int]=0.001 , **UpperCAmelCase__ : Dict , ) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase__) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''') A__ = num_channels A__ = image_size A__ = depth_multiplier A__ = min_depth A__ = hidden_act A__ = tf_padding A__ = classifier_dropout_prob A__ = initializer_range A__ = layer_norm_eps class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = version.parse('''1.11''' ) @property def SCREAMING_SNAKE_CASE ( self : Any) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict([('''pixel_values''', {0: '''batch'''})]) @property def SCREAMING_SNAKE_CASE ( self : List[str]) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})]) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})]) @property def SCREAMING_SNAKE_CASE ( self : int) ->float: '''simple docstring''' return 1e-4
87
0
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() lowercase : Optional[Any] = logging.get_logger(__name__) def snake_case__ ( lowerCamelCase_ ): A : Dict = torch.load(lowercase_ , map_location='''cpu''' ) if "model" in sd.keys(): A : Optional[int] = torch.load(lowercase_ , map_location='''cpu''' )['''model'''] # pop unnecessary weights A : Tuple = [ '''decoder.version''', '''decoder.output_projection.weight''', ] for key in keys_to_delete: if key in sd: sd.pop(lowercase_ ) A : str = { '''decoder.project_in_dim.weight''': '''decoder.project_in.weight''', '''decoder.project_out_dim.weight''': '''decoder.project_out.weight''', '''decoder.layer_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.layer_norm.bias''': '''decoder.final_layer_norm.bias''', } for old_key, new_key in keys_to_rename.items(): if old_key in sd: A : List[Any] = sd.pop(lowercase_ ) A : Dict = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: A : int = sd[key] # We split QKV in separate Q,K,V A : Dict = key.replace('''.qkv_proj.''' , '''.q_proj.''' ) A : List[Any] = key.replace('''.qkv_proj.''' , '''.k_proj.''' ) A : str = key.replace('''.qkv_proj.''' , '''.v_proj.''' ) A : Optional[int] = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 A , A , A : Dict = torch.split(lowercase_ , depth // 3 , dim=0 ) A : List[str] = q A : Optional[Any] = k A : Dict = v del sd[key] return sd @torch.no_grad() def snake_case__ ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None ): A : int = load_checkpoint(lowercase_ ) if config is not None: A : Optional[int] = OPTConfig.from_pretrained(lowercase_ ) else: A : Optional[int] = OPTConfig() A : Optional[int] = OPTModel(lowercase_ ).half().eval() model.load_state_dict(lowercase_ ) # Check results Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) model.save_pretrained(lowercase_ ) if __name__ == "__main__": lowercase : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--fairseq_path", type=str, help=( "path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:" " https://huggingface.co/models?other=opt_metasq" ), ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--hf_config", default=None, type=str, help="Define HF config.") lowercase : Tuple = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
542
import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase : Dict = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_sentencepiece_available(): import sentencepiece as sp _lowerCamelCase : str = 5 _lowerCamelCase : int = 10 @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = SpeechaTextTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = True def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' super().setUp() A__ = sp.SentencePieceProcessor() spm_model.Load(UpperCAmelCase__) A__ = ['''<s>''', '''<pad>''', '''</s>''', '''<unk>'''] vocab += [spm_model.IdToPiece(id_) for id_ in range(len(UpperCAmelCase__))] A__ = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__)))) A__ = Path(self.tmpdirname) save_json(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''vocab_file''']) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''spm_file''']) A__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' A__ = '''<pad>''' A__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__) , UpperCAmelCase__) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__) , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<s>''') self.assertEqual(vocab_keys[1] , '''<pad>''') self.assertEqual(vocab_keys[-1] , '''j''') self.assertEqual(len(UpperCAmelCase__) , 1_001) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[str]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_001) def SCREAMING_SNAKE_CASE ( self : int) ->List[str]: '''simple docstring''' A__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname) A__ = tokenizer.tokenize('''This is a test''') self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__) , [289, 50, 14, 174, 386] , ) A__ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( UpperCAmelCase__ , [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''', '''é''', '''.'''] , ) A__ = tokenizer.convert_tokens_to_ids(UpperCAmelCase__) self.assertListEqual(UpperCAmelCase__ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8]) A__ = tokenizer.convert_ids_to_tokens(UpperCAmelCase__) self.assertListEqual( UpperCAmelCase__ , [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>''', '''.'''] , ) @slow def SCREAMING_SNAKE_CASE ( self : int) ->List[Any]: '''simple docstring''' A__ = {'''input_ids''': [[3_791, 797, 31, 11, 64, 797, 31, 2_429, 433, 12, 1_176, 12, 20, 786, 915, 142, 2_413, 240, 37, 3_238, 797, 31, 11, 35, 93, 915, 142, 2_413, 240, 37, 5_540, 567, 1_276, 93, 37, 610, 40, 62, 455, 657, 1_042, 123, 780, 177, 37, 309, 241, 1_298, 514, 20, 292, 2_737, 114, 2_469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3_388, 511, 459, 4, 3_555, 40, 321, 302, 705, 4, 3_388, 511, 583, 326, 5, 5, 5, 62, 3_310, 560, 177, 2_680, 217, 1_508, 32, 31, 853, 418, 64, 583, 511, 1_605, 62, 35, 93, 560, 177, 2_680, 217, 1_508, 1_521, 64, 583, 511, 519, 62, 20, 1_515, 764, 20, 149, 261, 5_625, 7_972, 20, 5_540, 567, 1_276, 93, 3_925, 1_675, 11, 15, 802, 7_972, 576, 217, 1_508, 11, 35, 93, 1_253, 2_441, 15, 289, 652, 31, 416, 321, 3_842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2_681, 1_153, 3_434, 20, 5_540, 37, 567, 126, 1_253, 2_441, 3_376, 449, 210, 431, 1_563, 177, 767, 5_540, 11, 1_203, 472, 11, 2_953, 685, 285, 364, 706, 1_153, 20, 6_799, 20, 2_869, 20, 4_464, 126, 40, 2_429, 20, 1_040, 866, 2_664, 418, 20, 318, 20, 1_726, 186, 20, 265, 522, 35, 93, 2_191, 4_634, 20, 1_040, 12, 6_799, 15, 228, 2_356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2_575, 2_666, 684, 1_582, 1_176, 12, 627, 149, 619, 20, 4_902, 563, 11, 20, 149, 261, 3_420, 2_356, 174, 142, 4_714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''facebook/s2t-small-mustc-en-de-st''' , revision='''a14f04cf0776c02f62a8cb800cf7909e15ea23ad''' , ) @require_sentencepiece class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = '''valhalla/s2t_mustc_multilinguial_medium''' UpperCAmelCase__ = '''C\'est trop cool''' UpperCAmelCase__ = '''Esto es genial''' @classmethod def SCREAMING_SNAKE_CASE ( cls : Dict) ->Dict: '''simple docstring''' A__ = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name) return cls def SCREAMING_SNAKE_CASE ( self : str) ->Dict: '''simple docstring''' self.assertEqual(self.tokenizer.lang_code_to_id['''pt'''] , 4) self.assertEqual(self.tokenizer.lang_code_to_id['''ru'''] , 6) self.assertEqual(self.tokenizer.lang_code_to_id['''it'''] , 9) self.assertEqual(self.tokenizer.lang_code_to_id['''de'''] , 11) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Dict: '''simple docstring''' self.assertEqual(self.tokenizer.vocab_size , 10_000) def SCREAMING_SNAKE_CASE ( self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertIn(UpperCAmelCase__ , self.tokenizer.all_special_ids) A__ = [ES_CODE, 4, 1_601, 47, 7_647, 2] A__ = self.tokenizer.decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__) A__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCAmelCase__) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__) self.assertNotIn(self.tokenizer.eos_token , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->str: '''simple docstring''' A__ = '''fr''' A__ = self.tokenizer(self.french_text).input_ids self.assertEqual(encoded[0] , UpperCAmelCase__) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->int: '''simple docstring''' A__ = '''fr''' self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE]) A__ = '''es''' self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE])
87
0
'''simple docstring''' import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self : Tuple , snake_case : int , snake_case : int ): """simple docstring""" _snake_case : List[Any] = jnp.ones((batch_size, length) ) / length return scores def __UpperCAmelCase ( self : Dict ): """simple docstring""" _snake_case : List[str] = None _snake_case : str = 20 _snake_case : int = self._get_uniform_logits(batch_size=2 , length=UpperCAmelCase__ ) # tweak scores to not be uniform anymore _snake_case : int = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch _snake_case : Union[str, Any] = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax _snake_case : str = jax.nn.softmax(UpperCAmelCase__ , axis=-1 ) _snake_case : Dict = FlaxTemperatureLogitsWarper(temperature=0.5 ) _snake_case : Any = FlaxTemperatureLogitsWarper(temperature=1.3 ) _snake_case : Optional[int] = jax.nn.softmax(temp_dist_warper_sharper(UpperCAmelCase__ , scores.copy() , cur_len=UpperCAmelCase__ ) , axis=-1 ) _snake_case : Optional[Any] = jax.nn.softmax(temp_dist_warper_smoother(UpperCAmelCase__ , scores.copy() , cur_len=UpperCAmelCase__ ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" _snake_case : Union[str, Any] = None _snake_case : Optional[Any] = 10 _snake_case : Any = 2 # create ramp distribution _snake_case : Tuple = np.broadcast_to(np.arange(UpperCAmelCase__ )[None, :] , (batch_size, vocab_size) ).copy() _snake_case : int = ramp_logits[1:, : vocab_size // 2] + vocab_size _snake_case : str = FlaxTopKLogitsWarper(3 ) _snake_case : List[Any] = top_k_warp(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case _snake_case : Optional[int] = 5 _snake_case : Tuple = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) _snake_case : Optional[int] = np.broadcast_to(np.arange(UpperCAmelCase__ )[None, :] , (batch_size, length) ).copy() _snake_case : int = top_k_warp_safety_check(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def __UpperCAmelCase ( self : Dict ): """simple docstring""" _snake_case : Any = None _snake_case : Optional[Any] = 10 _snake_case : Dict = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) _snake_case : Dict = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) _snake_case : Tuple = FlaxTopPLogitsWarper(0.8 ) _snake_case : int = np.exp(top_p_warp(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 _snake_case : List[Any] = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) ) # check edge cases with negative and extreme logits _snake_case : Tuple = np.broadcast_to(np.arange(UpperCAmelCase__ )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme _snake_case : List[Any] = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept _snake_case : Union[str, Any] = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) _snake_case : List[str] = top_p_warp(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" _snake_case : Dict = 20 _snake_case : Any = 4 _snake_case : Tuple = 0 _snake_case : List[Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=UpperCAmelCase__ ) # check that min length is applied at length 5 _snake_case : List[str] = ids_tensor((batch_size, 20) , vocab_size=20 ) _snake_case : List[Any] = 5 _snake_case : Optional[Any] = self._get_uniform_logits(UpperCAmelCase__ , UpperCAmelCase__ ) _snake_case : int = min_dist_processor(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('inf' )] ) # check that min length is not applied anymore at length 15 _snake_case : Tuple = self._get_uniform_logits(UpperCAmelCase__ , UpperCAmelCase__ ) _snake_case : Optional[int] = 15 _snake_case : List[Any] = min_dist_processor(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) self.assertFalse(jnp.isinf(UpperCAmelCase__ ).any() ) def __UpperCAmelCase ( self : Optional[int] ): """simple docstring""" _snake_case : Tuple = 20 _snake_case : Any = 4 _snake_case : Union[str, Any] = 0 _snake_case : Optional[int] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase__ ) # check that all scores are -inf except the bos_token_id score _snake_case : int = ids_tensor((batch_size, 1) , vocab_size=20 ) _snake_case : str = 1 _snake_case : Any = self._get_uniform_logits(UpperCAmelCase__ , UpperCAmelCase__ ) _snake_case : str = logits_processor(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 _snake_case : Optional[Any] = 3 _snake_case : List[Any] = self._get_uniform_logits(UpperCAmelCase__ , UpperCAmelCase__ ) _snake_case : Union[str, Any] = logits_processor(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) self.assertFalse(jnp.isinf(UpperCAmelCase__ ).any() ) def __UpperCAmelCase ( self : int ): """simple docstring""" _snake_case : List[str] = 20 _snake_case : int = 4 _snake_case : Any = 0 _snake_case : Optional[Any] = 5 _snake_case : Dict = FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ ) # check that all scores are -inf except the eos_token_id when max_length is reached _snake_case : int = ids_tensor((batch_size, 4) , vocab_size=20 ) _snake_case : Any = 4 _snake_case : List[str] = self._get_uniform_logits(UpperCAmelCase__ , UpperCAmelCase__ ) _snake_case : Optional[int] = logits_processor(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached _snake_case : List[str] = 3 _snake_case : Union[str, Any] = self._get_uniform_logits(UpperCAmelCase__ , UpperCAmelCase__ ) _snake_case : Any = logits_processor(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) self.assertFalse(jnp.isinf(UpperCAmelCase__ ).any() ) def __UpperCAmelCase ( self : Dict ): """simple docstring""" _snake_case : Union[str, Any] = 4 _snake_case : int = 10 _snake_case : str = 15 _snake_case : Optional[Any] = 2 _snake_case : Optional[int] = 1 _snake_case : Union[str, Any] = 15 # dummy input_ids and scores _snake_case : List[str] = ids_tensor((batch_size, sequence_length) , UpperCAmelCase__ ) _snake_case : Any = input_ids.copy() _snake_case : Optional[Any] = self._get_uniform_logits(UpperCAmelCase__ , UpperCAmelCase__ ) _snake_case : List[Any] = scores.copy() # instantiate all dist processors _snake_case : Dict = FlaxTemperatureLogitsWarper(temperature=0.5 ) _snake_case : Optional[Any] = FlaxTopKLogitsWarper(3 ) _snake_case : Optional[Any] = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors _snake_case : Union[str, Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=UpperCAmelCase__ ) _snake_case : List[Any] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase__ ) _snake_case : List[str] = FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ ) _snake_case : Dict = 10 # no processor list _snake_case : Optional[int] = temp_dist_warp(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) _snake_case : Tuple = top_k_warp(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) _snake_case : Any = top_p_warp(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) _snake_case : List[Any] = min_dist_proc(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) _snake_case : List[Any] = bos_dist_proc(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) _snake_case : Any = eos_dist_proc(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) # with processor list _snake_case : Optional[int] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) _snake_case : Tuple = processor(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) # scores should be equal self.assertTrue(jnp.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def __UpperCAmelCase ( self : Dict ): """simple docstring""" _snake_case : Tuple = 4 _snake_case : str = 10 _snake_case : List[str] = 15 _snake_case : List[Any] = 2 _snake_case : List[Any] = 1 _snake_case : List[Any] = 15 # dummy input_ids and scores _snake_case : Optional[int] = ids_tensor((batch_size, sequence_length) , UpperCAmelCase__ ) _snake_case : List[Any] = input_ids.copy() _snake_case : List[str] = self._get_uniform_logits(UpperCAmelCase__ , UpperCAmelCase__ ) _snake_case : List[Any] = scores.copy() # instantiate all dist processors _snake_case : Dict = FlaxTemperatureLogitsWarper(temperature=0.5 ) _snake_case : Dict = FlaxTopKLogitsWarper(3 ) _snake_case : int = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors _snake_case : Any = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=UpperCAmelCase__ ) _snake_case : Dict = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase__ ) _snake_case : Dict = FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ ) _snake_case : List[str] = 10 # no processor list def run_no_processor_list(snake_case : Optional[int] , snake_case : Any , snake_case : Union[str, Any] ): _snake_case : Any = temp_dist_warp(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) _snake_case : Dict = top_k_warp(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) _snake_case : int = top_p_warp(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) _snake_case : Optional[int] = min_dist_proc(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) _snake_case : List[Any] = bos_dist_proc(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) _snake_case : List[Any] = eos_dist_proc(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) return scores # with processor list def run_processor_list(snake_case : Union[str, Any] , snake_case : str , snake_case : Dict ): _snake_case : int = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) _snake_case : Dict = processor(UpperCAmelCase__ , UpperCAmelCase__ , cur_len=UpperCAmelCase__ ) return scores _snake_case : List[Any] = jax.jit(UpperCAmelCase__ ) _snake_case : List[Any] = jax.jit(UpperCAmelCase__ ) _snake_case : List[Any] = jitted_run_no_processor_list(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) _snake_case : Dict = jitted_run_processor_list(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # scores should be equal self.assertTrue(jnp.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
517
from __future__ import annotations import requests def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" A__ = f"""https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty""" return requests.get(lowercase_ ).json() def SCREAMING_SNAKE_CASE ( lowercase_ = 10 ) -> list[dict]: """simple docstring""" A__ = '''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty''' A__ = requests.get(lowercase_ ).json()[:max_stories] return [get_hackernews_story(lowercase_ ) for story_id in story_ids] def SCREAMING_SNAKE_CASE ( lowercase_ = 10 ) -> str: """simple docstring""" A__ = hackernews_top_stories(lowercase_ ) return "\n".join('''* [{title}]({url})'''.format(**lowercase_ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
87
0
'''simple docstring''' import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def UpperCamelCase ( a , a ) -> Dict: '''simple docstring''' if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer __magic_name__ = flax_key_tuple[:-1] + ('''weight''',) __magic_name__ = torch.permute(lowercase_ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(lowercase_ ): # linear layer __magic_name__ = flax_key_tuple[:-1] + ('''weight''',) __magic_name__ = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: __magic_name__ = flax_key_tuple[:-1] + ('''weight''',) return flax_key_tuple, flax_tensor def UpperCamelCase ( a , a , a ) -> int: '''simple docstring''' if "metadata" in layer: __magic_name__ = layer.split('''metadata''' ) __magic_name__ = ''''''.join(split_layer[0] )[:-1] __magic_name__ = [tuple(('''metadata''' + split_layer[1]).split('''/''' ) )] elif "kvstore" in layer: __magic_name__ = layer.split('''kvstore''' ) __magic_name__ = ''''''.join(split_layer[0] )[:-1] __magic_name__ = [tuple(('''kvstore''' + split_layer[1]).split('''/''' ) )] else: __magic_name__ = layer.split('''/''' ) __magic_name__ = '''/'''.join(split_layer[:-1] ) __magic_name__ = (split_layer[-1],) if "kvstore/path" in layer: __magic_name__ = F'''{switch_checkpoint_path}/{checkpoint_info[layer]}''' elif "kvstore/driver" in layer: __magic_name__ = '''file''' else: __magic_name__ = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def UpperCamelCase ( a , a ) -> int: '''simple docstring''' __magic_name__ = rename_keys(lowercase_ ) __magic_name__ = {} for k, v in current_block.items(): __magic_name__ = v __magic_name__ = new_current_block torch.save(lowercase_ , lowercase_ ) def UpperCamelCase ( a , a , a , a , a = WEIGHTS_NAME ) -> Any: '''simple docstring''' __magic_name__ = convert_file_size_to_int(lowercase_ ) __magic_name__ = [] __magic_name__ = {} __magic_name__ = 0 __magic_name__ = 0 os.makedirs(lowercase_ , exist_ok=lowercase_ ) with gfile.GFile(switch_checkpoint_path + '''/checkpoint''' , '''rb''' ) as fp: __magic_name__ = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target'''] __magic_name__ = flatten_dict(lowercase_ , sep='''/''' ) __magic_name__ = {} for layer in checkpoint_info.keys(): __magic_name__ , __magic_name__ , __magic_name__ = get_key_and_tensorstore_dict( lowercase_ , lowercase_ , lowercase_ ) if curr_real_layer_name in all_layers: __magic_name__ = content else: __magic_name__ = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file __magic_name__ = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() __magic_name__ = torch.tensor(lowercase_ ) __magic_name__ = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts __magic_name__ , __magic_name__ = rename_base_flax_keys(tuple(key.split('''/''' ) ) , lowercase_ ) __magic_name__ = '''/'''.join(lowercase_ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: __magic_name__ = os.path.join( lowercase_ , weights_name.replace('''.bin''' , F'''-{len(lowercase_ )+1:05d}-of-???.bin''' ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) del current_block __magic_name__ = {} __magic_name__ = 0 __magic_name__ = raw_weights.to(getattr(lowercase_ , lowercase_ ) ) current_block_size += weight_size total_size += weight_size # Add the last block __magic_name__ = os.path.join(lowercase_ , weights_name.replace('''.bin''' , F'''-{len(lowercase_ )+1:05d}-of-???.bin''' ) ) rename_and_save_block(lowercase_ , lowercase_ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(lowercase_ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index __magic_name__ = {} __magic_name__ = {} for idx, shard in enumerate(lowercase_ ): __magic_name__ = weights_name.replace( '''.bin''' , F'''-{idx+1:05d}-of-{len(lowercase_ ):05d}.bin''' ) # len(sharded_state_dicts):05d} __magic_name__ = os.path.join(lowercase_ , weights_name.replace('''.bin''' , F'''-{idx+1:05d}-of-???.bin''' ) ) os.rename(lowercase_ , os.path.join(lowercase_ , lowercase_ ) ) __magic_name__ = shard for key in shard: __magic_name__ = shard_file # Add the metadata __magic_name__ = {'''total_size''': total_size} __magic_name__ = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(lowercase_ , lowercase_ ) , '''w''' , encoding='''utf-8''' ) as f: __magic_name__ = json.dumps(lowercase_ , indent=2 , sort_keys=lowercase_ ) + '''\n''' f.write(lowercase_ ) return metadata, index if __name__ == "__main__": _lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size") parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted", type=str, required=False, help="Path to the output pytorch model.", ) _lowerCAmelCase = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def UpperCamelCase ( ) -> Any: '''simple docstring''' from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer __magic_name__ = SwitchTransformersConfig.from_pretrained('''google/switch-base-8''' ) config.save_pretrained('''/home/arthur_huggingface_co/transformers/switch_converted''' ) __magic_name__ = SwitchTransformersForConditionalGeneration.from_pretrained( '''/home/arthur_huggingface_co/transformers/switch_converted''' , device_map='''auto''' ) __magic_name__ = TaTokenizer.from_pretrained('''t5-small''' ) __magic_name__ = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''' __magic_name__ = tokenizer(lowercase_ , return_tensors='''pt''' ).input_ids __magic_name__ = model.generate(lowercase_ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
432
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType _lowerCamelCase : Optional[List[str]] = None _lowerCamelCase : int = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image _lowerCamelCase : Union[str, Any] = [ np.dtype("""|b1"""), np.dtype("""|u1"""), np.dtype("""<u2"""), np.dtype(""">u2"""), np.dtype("""<i2"""), np.dtype(""">i2"""), np.dtype("""<u4"""), np.dtype(""">u4"""), np.dtype("""<i4"""), np.dtype(""">i4"""), np.dtype("""<f4"""), np.dtype(""">f4"""), np.dtype("""<f8"""), np.dtype(""">f8"""), ] @dataclass class UpperCamelCase_ : '''simple docstring''' UpperCAmelCase__ = True UpperCAmelCase__ = None # Automatically constructed UpperCAmelCase__ = "PIL.Image.Image" UpperCAmelCase__ = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) UpperCAmelCase__ = field(default='''Image''' , init=UpperCAmelCase__ , repr=UpperCAmelCase__ ) def __call__( self : List[str]) ->List[str]: '''simple docstring''' return self.pa_type def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"]) ->dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''') if isinstance(UpperCAmelCase__ , UpperCAmelCase__): A__ = np.array(UpperCAmelCase__) if isinstance(UpperCAmelCase__ , UpperCAmelCase__): return {"path": value, "bytes": None} elif isinstance(UpperCAmelCase__ , UpperCAmelCase__): return {"path": None, "bytes": value} elif isinstance(UpperCAmelCase__ , np.ndarray): # convert the image array to PNG/TIFF bytes return encode_np_array(UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , PIL.Image.Image): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(UpperCAmelCase__) 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 return {"bytes": None, "path": value.get('''path''')} elif value.get('''bytes''') is not None or value.get('''path''') is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get('''bytes'''), "path": value.get('''path''')} else: raise ValueError( f"""An image sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""") def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : dict , UpperCAmelCase__ : str=None) ->"PIL.Image.Image": '''simple docstring''' if not self.decode: raise RuntimeError('''Decoding is disabled for this feature. Please use Image(decode=True) instead.''') if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support decoding images, please install \'Pillow\'.''') if token_per_repo_id is None: A__ = {} A__ , A__ = value['''path'''], value['''bytes'''] if bytes_ is None: if path is None: raise ValueError(f"""An image should have one of 'path' or 'bytes' but both are None in {value}.""") else: if is_local_path(UpperCAmelCase__): A__ = PIL.Image.open(UpperCAmelCase__) else: A__ = path.split('''::''')[-1] try: A__ = string_to_dict(UpperCAmelCase__ , config.HUB_DATASETS_URL)['''repo_id'''] A__ = token_per_repo_id.get(UpperCAmelCase__) except ValueError: A__ = None with xopen(UpperCAmelCase__ , '''rb''' , use_auth_token=UpperCAmelCase__) as f: A__ = BytesIO(f.read()) A__ = PIL.Image.open(bytes_) else: A__ = PIL.Image.open(BytesIO(bytes_)) image.load() # to avoid "Too many open files" errors return image def SCREAMING_SNAKE_CASE ( self : Dict) ->Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Value return ( self if self.decode else { "bytes": Value('''binary'''), "path": Value('''string'''), } ) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[pa.StringArray, pa.StructArray, pa.ListArray]) ->pa.StructArray: '''simple docstring''' if pa.types.is_string(storage.type): A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.binary()) A__ = pa.StructArray.from_arrays([bytes_array, storage] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_binary(storage.type): A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays([storage, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_struct(storage.type): if storage.type.get_field_index('''bytes''') >= 0: A__ = storage.field('''bytes''') else: A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.binary()) if storage.type.get_field_index('''path''') >= 0: A__ = storage.field('''path''') else: A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_list(storage.type): A__ = pa.array( [encode_np_array(np.array(UpperCAmelCase__))['''bytes'''] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null()) return array_cast(UpperCAmelCase__ , self.pa_type) def SCREAMING_SNAKE_CASE ( self : List[Any] , UpperCAmelCase__ : pa.StructArray) ->pa.StructArray: '''simple docstring''' @no_op_if_value_is_null def path_to_bytes(UpperCAmelCase__ : Dict): with xopen(UpperCAmelCase__ , '''rb''') as f: A__ = f.read() return bytes_ A__ = 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() , ) A__ = pa.array( [os.path.basename(UpperCAmelCase__) if path is not None else None for path in storage.field('''path''').to_pylist()] , type=pa.string() , ) A__ = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null()) return array_cast(UpperCAmelCase__ , self.pa_type) def SCREAMING_SNAKE_CASE ( ) -> List[str]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() A__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def SCREAMING_SNAKE_CASE ( lowercase_ ) -> bytes: """simple docstring""" A__ = BytesIO() if image.format in list_image_compression_formats(): A__ = image.format else: A__ = '''PNG''' if image.mode in ['''1''', '''L''', '''LA''', '''RGB''', '''RGBA'''] else '''TIFF''' image.save(lowercase_ , format=lowercase_ ) return buffer.getvalue() def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" if hasattr(lowercase_ , '''filename''' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(lowercase_ )} def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) A__ = array.dtype A__ = dtype.byteorder if dtype.byteorder != '''=''' else _NATIVE_BYTEORDER A__ = dtype.kind A__ = dtype.itemsize A__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: A__ = np.dtype('''|u1''' ) if dtype_kind not in ["u", "i"]: raise TypeError( f"""Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.""" ) if dtype is not dest_dtype: warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: A__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: A__ = dtype_byteorder + dtype_kind + str(lowercase_ ) A__ = np.dtype(lowercase_ ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f"""Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}""" ) A__ = PIL.Image.fromarray(array.astype(lowercase_ ) ) return {"path": None, "bytes": image_to_bytes(lowercase_ )} def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[dict]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) if objs: A__ , A__ = first_non_null_value(lowercase_ ) if isinstance(lowercase_ , lowercase_ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(lowercase_ , np.ndarray ): A__ = no_op_if_value_is_null(lowercase_ ) return [obj_to_image_dict_func(lowercase_ ) for obj in objs] elif isinstance(lowercase_ , PIL.Image.Image ): A__ = no_op_if_value_is_null(lowercase_ ) return [obj_to_image_dict_func(lowercase_ ) for obj in objs] else: return objs else: return objs
87
0
'''simple docstring''' import numpy as np def UpperCamelCase_( snake_case : int , snake_case : List[Any] ): '''simple docstring''' return np.where(vector > 0 , lowercase_ , (alpha * (np.exp(lowercase_ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
400
from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) UpperCAmelCase__ = ( { '''feature-extraction''': TFMobileBertModel, '''fill-mask''': TFMobileBertForMaskedLM, '''question-answering''': TFMobileBertForQuestionAnswering, '''text-classification''': TFMobileBertForSequenceClassification, '''token-classification''': TFMobileBertForTokenClassification, '''zero-shot''': TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase__ = False UpperCAmelCase__ = False def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str=False) ->Optional[Any]: '''simple docstring''' A__ = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__) if return_labels: if model_class in get_values(UpperCAmelCase__): A__ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa) return inputs_dict class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int=13 , UpperCAmelCase__ : str=7 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=99 , UpperCAmelCase__ : List[str]=32 , UpperCAmelCase__ : Optional[int]=32 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Optional[Any]=37 , UpperCAmelCase__ : Optional[int]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : List[Any]=512 , UpperCAmelCase__ : Tuple=16 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : Dict=0.02 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Tuple=None , ) ->Any: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = use_token_type_ids A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = type_vocab_size A__ = type_sequence_label_size A__ = initializer_range A__ = num_labels A__ = num_choices A__ = scope A__ = embedding_size def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Tuple: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) A__ = None if self.use_token_type_ids: A__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) A__ = None A__ = None A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size] , self.type_sequence_label_size) A__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) A__ = ids_tensor([self.batch_size] , self.num_choices) A__ = MobileBertConfig( 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 , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any]) ->Any: '''simple docstring''' A__ = TFMobileBertModel(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) A__ = [input_ids, input_mask] A__ = model(UpperCAmelCase__) A__ = model(UpperCAmelCase__) 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 SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Tuple) ->Optional[Any]: '''simple docstring''' A__ = TFMobileBertForMaskedLM(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any]) ->int: '''simple docstring''' A__ = TFMobileBertForNextSentencePrediction(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int) ->List[Any]: '''simple docstring''' A__ = TFMobileBertForPreTraining(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) 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 SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple) ->Dict: '''simple docstring''' A__ = self.num_labels A__ = TFMobileBertForSequenceClassification(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int) ->Dict: '''simple docstring''' A__ = self.num_choices A__ = TFMobileBertForMultipleChoice(config=UpperCAmelCase__) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1) , (1, self.num_choices, 1)) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1) , (1, self.num_choices, 1)) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 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(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int]) ->int: '''simple docstring''' A__ = self.num_labels A__ = TFMobileBertForTokenClassification(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any]) ->Union[str, Any]: '''simple docstring''' A__ = TFMobileBertForQuestionAnswering(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def SCREAMING_SNAKE_CASE ( self : Any) ->str: '''simple docstring''' A__ = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = config_and_inputs A__ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE ( self : Any) ->Union[str, Any]: '''simple docstring''' A__ = TFMobileBertModelTest.TFMobileBertModelTester(self) A__ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[str]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*UpperCAmelCase__) @slow def SCREAMING_SNAKE_CASE ( self : str) ->List[Any]: '''simple docstring''' for model_name in ["google/mobilebert-uncased"]: A__ = TFMobileBertModel.from_pretrained(UpperCAmelCase__) self.assertIsNotNone(UpperCAmelCase__) @require_tf class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Any: '''simple docstring''' A__ = TFMobileBertForPreTraining.from_pretrained('''google/mobilebert-uncased''') A__ = tf.constant([[0, 1, 2, 3, 4, 5]]) A__ = model(UpperCAmelCase__)[0] A__ = [1, 6, 30_522] self.assertEqual(output.shape , UpperCAmelCase__) A__ = tf.constant( [ [ [-4.5919547, -9.248295, -9.645256], [-6.7306175, -6.440284, -6.6052837], [-7.2743506, -6.7847915, -6.024673], ] ]) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4)
87
0
'''simple docstring''' from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo snake_case_ : Union[str, Any] = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ snake_case_ : Union[str, Any] = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ snake_case_ : str = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): '''simple docstring''' def a ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def a ( self , A_ , A_ , A_ = 1 , A_ = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=UpperCAmelCase__ , hypotheses=UpperCAmelCase__ , min_len=UpperCAmelCase__ , max_len=UpperCAmelCase__ ) }
138
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int=13 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : str=224 , UpperCAmelCase__ : str=30 , UpperCAmelCase__ : Tuple=400 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Union[str, Any]=[0.5, 0.5, 0.5] , UpperCAmelCase__ : Tuple=[0.5, 0.5, 0.5] , ) ->str: '''simple docstring''' A__ = size if size is not None else {'''height''': 18, '''width''': 18} A__ = parent A__ = batch_size A__ = num_channels A__ = image_size A__ = min_resolution A__ = max_resolution A__ = do_resize A__ = size A__ = do_normalize A__ = image_mean A__ = image_std def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = ViTImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE ( self : List[str]) ->str: '''simple docstring''' A__ = EfficientFormerImageProcessorTester(self) @property def SCREAMING_SNAKE_CASE ( self : Dict) ->int: '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Dict: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_mean''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_std''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_normalize''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''')) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Dict: '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self : str) ->Optional[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random PIL images A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , torch.Tensor) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
87
0
from __future__ import annotations __magic_name__: Tuple = tuple[int, int, int] __magic_name__: Union[str, Any] = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __magic_name__: List[Any] = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- __magic_name__: str = """EGZWVONAHDCLFQMSIPJBYUKXTR""" __magic_name__: str = """FOBHMDKEXQNRAULPGSJVTYICZW""" __magic_name__: List[Any] = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- __magic_name__: Union[str, Any] = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- __magic_name__: Tuple = """RMDJXFUWGISLHVTCQNKYPBEZOA""" __magic_name__: Any = """SGLCPQWZHKXAREONTFBVIYJUDM""" __magic_name__: Optional[Any] = """HVSICLTYKQUBXDWAJZOMFGPREN""" __magic_name__: Dict = """RZWQHFMVDBKICJLNTUXAGYPSOE""" __magic_name__: List[str] = """LFKIJODBEGAMQPXVUHYSTCZRWN""" __magic_name__: Optional[int] = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def UpperCamelCase ( _A, _A, _A ): """simple docstring""" if (unique_rotsel := len(set(lowercase_ ) )) < 3: __magic_name__ : List[Any] = f'Please use 3 unique rotors (not {unique_rotsel})' raise Exception(lowercase_ ) # Checks if rotor positions are valid __magic_name__ ,__magic_name__ ,__magic_name__ : Any = rotpos if not 0 < rotorposa <= len(lowercase_ ): __magic_name__ : Any = f'First rotor position is not within range of 1..26 ({rotorposa}' raise ValueError(lowercase_ ) if not 0 < rotorposa <= len(lowercase_ ): __magic_name__ : Union[str, Any] = f'Second rotor position is not within range of 1..26 ({rotorposa})' raise ValueError(lowercase_ ) if not 0 < rotorposa <= len(lowercase_ ): __magic_name__ : Union[str, Any] = f'Third rotor position is not within range of 1..26 ({rotorposa})' raise ValueError(lowercase_ ) # Validates string and returns dict __magic_name__ : Tuple = _plugboard(lowercase_ ) return rotpos, rotsel, pbdict def UpperCamelCase ( _A ): """simple docstring""" if not isinstance(lowercase_, lowercase_ ): __magic_name__ : str = f'Plugboard setting isn\'t type string ({type(lowercase_ )})' raise TypeError(lowercase_ ) elif len(lowercase_ ) % 2 != 0: __magic_name__ : Dict = f'Odd number of symbols ({len(lowercase_ )})' raise Exception(lowercase_ ) elif pbstring == "": return {} pbstring.replace(""" """, """""" ) # Checks if all characters are unique __magic_name__ : str = set() for i in pbstring: if i not in abc: __magic_name__ : int = f'\'{i}\' not in list of symbols' raise Exception(lowercase_ ) elif i in tmppbl: __magic_name__ : List[Any] = f'Duplicate symbol ({i})' raise Exception(lowercase_ ) else: tmppbl.add(lowercase_ ) del tmppbl # Created the dictionary __magic_name__ : Dict = {} for j in range(0, len(lowercase_ ) - 1, 2 ): __magic_name__ : Union[str, Any] = pbstring[j + 1] __magic_name__ : List[str] = pbstring[j] return pb def UpperCamelCase ( _A, _A, _A = (rotora, rotora, rotora), _A = "", ): """simple docstring""" __magic_name__ : Any = text.upper() __magic_name__ ,__magic_name__ ,__magic_name__ : Optional[Any] = _validator( lowercase_, lowercase_, plugb.upper() ) __magic_name__ ,__magic_name__ ,__magic_name__ : List[Any] = rotor_position __magic_name__ ,__magic_name__ ,__magic_name__ : List[Any] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 __magic_name__ : int = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: __magic_name__ : Union[str, Any] = plugboard[symbol] # rotor ra -------------------------- __magic_name__ : Dict = abc.index(lowercase_ ) + rotorposa __magic_name__ : Optional[int] = rotora[index % len(lowercase_ )] # rotor rb -------------------------- __magic_name__ : Tuple = abc.index(lowercase_ ) + rotorposa __magic_name__ : List[str] = rotora[index % len(lowercase_ )] # rotor rc -------------------------- __magic_name__ : int = abc.index(lowercase_ ) + rotorposa __magic_name__ : Any = rotora[index % len(lowercase_ )] # reflector -------------------------- # this is the reason you don't need another machine to decipher __magic_name__ : Dict = reflector[symbol] # 2nd rotors __magic_name__ : Optional[int] = abc[rotora.index(lowercase_ ) - rotorposa] __magic_name__ : Tuple = abc[rotora.index(lowercase_ ) - rotorposa] __magic_name__ : str = abc[rotora.index(lowercase_ ) - rotorposa] # 2nd plugboard if symbol in plugboard: __magic_name__ : List[str] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(lowercase_ ): __magic_name__ : Union[str, Any] = 0 rotorposa += 1 if rotorposa >= len(lowercase_ ): __magic_name__ : Dict = 0 rotorposa += 1 if rotorposa >= len(lowercase_ ): __magic_name__ : List[Any] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(lowercase_ ) return "".join(lowercase_ ) if __name__ == "__main__": __magic_name__: Union[str, Any] = """This is my Python script that emulates the Enigma machine from WWII.""" __magic_name__: str = (1, 1, 1) __magic_name__: Optional[Any] = """pictures""" __magic_name__: List[str] = (rotora, rotora, rotora) __magic_name__: Any = enigma(message, rotor_pos, rotor_sel, pb) print("Encrypted message:", en) print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
324
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance _lowerCamelCase : Dict = 6_378_137.0 _lowerCamelCase : Union[str, Any] = 6_356_752.314_245 _lowerCamelCase : List[Any] = 6378137 def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> float: """simple docstring""" A__ = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude A__ = atan((1 - flattening) * tan(radians(lowercase_ ) ) ) A__ = atan((1 - flattening) * tan(radians(lowercase_ ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius A__ = haversine_distance(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) / EQUATORIAL_RADIUS # Intermediate P and Q values A__ = (b_lata + b_lata) / 2 A__ = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) A__ = (sin(lowercase_ ) ** 2) * (cos(lowercase_ ) ** 2) A__ = cos(sigma / 2 ) ** 2 A__ = (sigma - sin(lowercase_ )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) A__ = (cos(lowercase_ ) ** 2) * (sin(lowercase_ ) ** 2) A__ = sin(sigma / 2 ) ** 2 A__ = (sigma + sin(lowercase_ )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
87
0
import os def a__ ( __UpperCamelCase = "matrix.txt" ): with open(os.path.join(os.path.dirname(lowercase_ ) , lowercase_ ) ) as in_file: SCREAMING_SNAKE_CASE_ = in_file.read() SCREAMING_SNAKE_CASE_ = [[int(lowercase_ ) for cell in row.split("," )] for row in data.strip().splitlines()] SCREAMING_SNAKE_CASE_ = [[0 for cell in row] for row in grid] SCREAMING_SNAKE_CASE_ = len(grid[0] ) SCREAMING_SNAKE_CASE_ = [[0 for i in range(lowercase_ )] for j in range(lowercase_ )] SCREAMING_SNAKE_CASE_ = grid[0][0] for i in range(1 , lowercase_ ): SCREAMING_SNAKE_CASE_ = grid[0][i] + dp[0][i - 1] for i in range(1 , lowercase_ ): SCREAMING_SNAKE_CASE_ = grid[i][0] + dp[i - 1][0] for i in range(1 , lowercase_ ): for j in range(1 , lowercase_ ): SCREAMING_SNAKE_CASE_ = grid[i][j] + min(dp[i - 1][j] , dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(f"{solution() = }")
140
import heapq import sys import numpy as np _lowerCamelCase : Any = tuple[int, int] class UpperCamelCase_ : '''simple docstring''' def __init__( self : Any) ->str: '''simple docstring''' A__ = [] A__ = set() def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' if not self.empty(): return self.elements[0][0] else: return float('''inf''') def SCREAMING_SNAKE_CASE ( self : Tuple) ->str: '''simple docstring''' return len(self.elements) == 0 def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any]) ->List[str]: '''simple docstring''' if item not in self.set: heapq.heappush(self.elements , (priority, item)) self.set.add(UpperCAmelCase__) else: # update # print("update", item) A__ = [] ((A__) , (A__)) = heapq.heappop(self.elements) while x != item: temp.append((pri, x)) ((A__) , (A__)) = heapq.heappop(self.elements) temp.append((priority, item)) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx)) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : List[Any]) ->Union[str, Any]: '''simple docstring''' if item in self.set: self.set.remove(UpperCAmelCase__) A__ = [] ((A__) , (A__)) = heapq.heappop(self.elements) while x != item: temp.append((pro, x)) ((A__) , (A__)) = heapq.heappop(self.elements) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy)) def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[str]: '''simple docstring''' return self.elements[0][1] def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->int: '''simple docstring''' ((A__) , (A__)) = heapq.heappop(self.elements) self.set.remove(UpperCAmelCase__) return (priority, item) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = np.array(lowercase_ ) A__ = np.array(lowercase_ ) return np.linalg.norm(a - b ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" return consistent_heuristic(lowercase_ , lowercase_ ) // t def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Union[str, Any]: """simple docstring""" return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> Optional[int]: """simple docstring""" A__ = g_function[start] + Wa * heuristics[i](lowercase_ , lowercase_ ) return ans def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = np.chararray((n, n) ) for i in range(lowercase_ ): for j in range(lowercase_ ): A__ = '''*''' for i in range(lowercase_ ): for j in range(lowercase_ ): if (j, (n - 1) - i) in blocks: A__ = '''#''' A__ = '''-''' A__ = back_pointer[goal] while x != start: ((A__) , (A__)) = x # print(x) A__ = '''-''' A__ = back_pointer[x] A__ = '''-''' for i in range(lowercase_ ): for j in range(lowercase_ ): if (i, j) == (0, n - 1): print(grid[i][j] , end=''' ''' ) print('''<-- End position''' , end=''' ''' ) else: print(grid[i][j] , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) print('''PATH TAKEN BY THE ALGORITHM IS:-''' ) A__ = back_pointer[goal] while x != start: print(lowercase_ , end=''' ''' ) A__ = back_pointer[x] print(lowercase_ ) sys.exit() def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) -> Union[str, Any]: """simple docstring""" for itera in range(lowercase_ ): open_list[itera].remove_element(lowercase_ ) # print("s", s) # print("j", j) ((A__) , (A__)) = s A__ = (x - 1, y) A__ = (x + 1, y) A__ = (x, y + 1) A__ = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(lowercase_ ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(lowercase_ ) A__ = -1 A__ = float('''inf''' ) if valid(lowercase_ ) and g_function[neighbours] > g_function[s] + 1: A__ = g_function[s] + 1 A__ = s if neighbours not in close_list_anchor: open_list[0].put(lowercase_ , key(lowercase_ , 0 , lowercase_ , lowercase_ ) ) if neighbours not in close_list_inad: for var in range(1 , lowercase_ ): if key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) <= Wa * key( lowercase_ , 0 , lowercase_ , lowercase_ ): open_list[j].put( lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) def SCREAMING_SNAKE_CASE ( ) -> Optional[int]: """simple docstring""" A__ = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list _lowerCamelCase : Dict = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} _lowerCamelCase : Optional[Any] = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] _lowerCamelCase : Optional[int] = make_common_ground() _lowerCamelCase : Optional[Any] = blocks_blk # hyper parameters _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : List[Any] = 20 _lowerCamelCase : Any = 3 # one consistent and two other inconsistent # start and end destination _lowerCamelCase : str = (0, 0) _lowerCamelCase : Tuple = (n - 1, n - 1) _lowerCamelCase : int = 1 def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = {start: 0, goal: float('''inf''' )} A__ = {start: -1, goal: -1} A__ = [] A__ = set() for i in range(lowercase_ ): open_list.append(PriorityQueue() ) open_list[i].put(lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) A__ = [] A__ = [] while open_list[0].minkey() < float('''inf''' ): for i in range(1 , lowercase_ ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float('''inf''' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: A__ , A__ = open_list[i].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_inad.append(lowercase_ ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('''inf''' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: A__ = open_list[0].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , 0 , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_anchor.append(lowercase_ ) print('''No path found to goal''' ) print() for i in range(n - 1 , -1 , -1 ): for j in range(lowercase_ ): if (j, i) in blocks: print('''#''' , end=''' ''' ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print('''*''' , end=''' ''' ) else: print('''-''' , end=''' ''' ) else: print('''*''' , end=''' ''' ) if (j, i) == (n - 1, n - 1): print('''<-- End position''' , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
87
0
"""simple docstring""" from __future__ import annotations import requests def A_ ( snake_case__ ) -> dict: _UpperCamelCase :Any = f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(lowercase_ ).json() def A_ ( snake_case__ = 10 ) -> list[dict]: _UpperCamelCase :str = '''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty''' _UpperCamelCase :Tuple = requests.get(lowercase_ ).json()[:max_stories] return [get_hackernews_story(lowercase_ ) for story_id in story_ids] def A_ ( snake_case__ = 10 ) -> str: _UpperCamelCase :Union[str, Any] = hackernews_top_stories(lowercase_ ) return "\n".join('''* [{title}]({url})'''.format(**lowercase_ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
355
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowerCamelCase : Optional[Any] = """Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine""" def SCREAMING_SNAKE_CASE ( ) -> Dict: """simple docstring""" A__ = _ask_options( '''In which compute environment are you running?''' , ['''This machine''', '''AWS (Amazon SageMaker)'''] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A__ = get_sagemaker_input() else: A__ = get_cluster_input() return config def SCREAMING_SNAKE_CASE ( lowercase_=None ) -> List[Any]: """simple docstring""" if subparsers is not None: A__ = subparsers.add_parser('''config''' , description=lowercase_ ) else: A__ = argparse.ArgumentParser('''Accelerate config command''' , description=lowercase_ ) parser.add_argument( '''--config_file''' , default=lowercase_ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=lowercase_ ) return parser def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Any: """simple docstring""" A__ = get_user_input() if args.config_file is not None: A__ = args.config_file else: if not os.path.isdir(lowercase_ ): os.makedirs(lowercase_ ) A__ = default_yaml_config_file if config_file.endswith('''.json''' ): config.to_json_file(lowercase_ ) else: config.to_yaml_file(lowercase_ ) print(f"""accelerate configuration saved at {config_file}""" ) def SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: """simple docstring""" A__ = config_command_parser() A__ = parser.parse_args() config_command(lowercase_ ) if __name__ == "__main__": main()
87
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCamelCase__ = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } UpperCamelCase__ = { """moussaKam/mbarthez""": 1_024, """moussaKam/barthez""": 1_024, """moussaKam/barthez-orangesum-title""": 1_024, } UpperCamelCase__ = """▁""" class UpperCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase_ = VOCAB_FILES_NAMES UpperCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ = ['''input_ids''', '''attention_mask'''] def __init__( self : int , UpperCamelCase : List[str] , UpperCamelCase : int="<s>" , UpperCamelCase : str="</s>" , UpperCamelCase : Dict="</s>" , UpperCamelCase : Optional[int]="<s>" , UpperCamelCase : List[str]="<unk>" , UpperCamelCase : str="<pad>" , UpperCamelCase : str="<mask>" , UpperCamelCase : Optional[Dict[str, Any]] = None , **UpperCamelCase : List[str] , ): """simple docstring""" _lowercase : Tuple = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token _lowercase : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase__ , ) _lowercase : Optional[Any] = vocab_file _lowercase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(UpperCAmelCase__ ) ) _lowercase : Optional[int] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} _lowercase : Tuple = len(self.sp_model ) - 1 _lowercase : Optional[int] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def lowerCAmelCase_ ( self : Optional[Any] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _lowercase : List[Any] = [self.cls_token_id] _lowercase : List[str] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCAmelCase_ ( self : Dict , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None , UpperCamelCase : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase__ , token_ids_a=UpperCAmelCase__ , already_has_special_tokens=UpperCAmelCase__ ) if token_ids_a is None: return [1] + ([0] * len(UpperCAmelCase__ )) + [1] return [1] + ([0] * len(UpperCAmelCase__ )) + [1, 1] + ([0] * len(UpperCAmelCase__ )) + [1] def lowerCAmelCase_ ( self : List[str] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): """simple docstring""" _lowercase : int = [self.sep_token_id] _lowercase : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def lowerCAmelCase_ ( self : Union[str, Any] ): """simple docstring""" return len(self.sp_model ) def lowerCAmelCase_ ( self : Optional[int] ): """simple docstring""" _lowercase : Tuple = {self.convert_ids_to_tokens(UpperCAmelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCAmelCase_ ( self : Optional[int] , UpperCamelCase : str ): """simple docstring""" return self.sp_model.encode(UpperCAmelCase__ , out_type=UpperCAmelCase__ ) def lowerCAmelCase_ ( self : str , UpperCamelCase : Optional[int] ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _lowercase : Optional[Any] = self.sp_model.PieceToId(UpperCAmelCase__ ) return spm_id if spm_id else self.unk_token_id def lowerCAmelCase_ ( self : Optional[Any] , UpperCamelCase : List[str] ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(UpperCAmelCase__ ) def lowerCAmelCase_ ( self : Union[str, Any] , UpperCamelCase : int ): """simple docstring""" _lowercase : Dict = [] _lowercase : int = '''''' _lowercase : List[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase__ ) + token _lowercase : List[str] = True _lowercase : Union[str, Any] = [] else: current_sub_tokens.append(UpperCAmelCase__ ) _lowercase : str = False out_string += self.sp_model.decode(UpperCAmelCase__ ) return out_string.strip() def __getstate__( self : Optional[Any] ): """simple docstring""" _lowercase : Tuple = self.__dict__.copy() _lowercase : List[str] = None return state def __setstate__( self : List[Any] , UpperCamelCase : int ): """simple docstring""" _lowercase : str = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _lowercase : List[str] = {} _lowercase : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase_ ( self : Tuple , UpperCamelCase : str , UpperCamelCase : Optional[str] = None ): """simple docstring""" if not os.path.isdir(UpperCAmelCase__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return _lowercase : str = os.path.join( UpperCAmelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase__ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase__ , '''wb''' ) as fi: _lowercase : Tuple = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase__ ) return (out_vocab_file,)
322
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _lowerCamelCase : int = logging.get_logger("""transformers.models.speecht5""") def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Tuple: """simple docstring""" hf_model.apply_weight_norm() A__ = checkpoint['''input_conv.weight_g'''] A__ = checkpoint['''input_conv.weight_v'''] A__ = checkpoint['''input_conv.bias'''] for i in range(len(config.upsample_rates ) ): A__ = checkpoint[f"""upsamples.{i}.1.weight_g"""] A__ = checkpoint[f"""upsamples.{i}.1.weight_v"""] A__ = checkpoint[f"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_g"""] A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_v"""] A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.bias"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_g"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_v"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.bias"""] A__ = checkpoint['''output_conv.1.weight_g'''] A__ = checkpoint['''output_conv.1.weight_v'''] A__ = checkpoint['''output_conv.1.bias'''] hf_model.remove_weight_norm() @torch.no_grad() def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , ) -> str: """simple docstring""" if config_path is not None: A__ = SpeechTaHifiGanConfig.from_pretrained(lowercase_ ) else: A__ = SpeechTaHifiGanConfig() A__ = SpeechTaHifiGan(lowercase_ ) A__ = torch.load(lowercase_ ) load_weights(orig_checkpoint['''model''']['''generator'''] , lowercase_ , lowercase_ ) A__ = np.load(lowercase_ ) A__ = stats[0].reshape(-1 ) A__ = stats[1].reshape(-1 ) A__ = torch.from_numpy(lowercase_ ).float() A__ = torch.from_numpy(lowercase_ ).float() model.save_pretrained(lowercase_ ) if repo_id: print('''Pushing to the hub...''' ) model.push_to_hub(lowercase_ ) if __name__ == "__main__": _lowerCamelCase : Any = argparse.ArgumentParser() parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--stats_path""", required=True, default=None, type=str, help="""Path to stats.npy file""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) _lowerCamelCase : List[str] = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
87
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __A = { """configuration_convnext""": ["""CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvNextConfig""", """ConvNextOnnxConfig"""] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["""ConvNextFeatureExtractor"""] __A = ["""ConvNextImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ConvNextForImageClassification""", """ConvNextModel""", """ConvNextPreTrainedModel""", """ConvNextBackbone""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ """TFConvNextForImageClassification""", """TFConvNextModel""", """TFConvNextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure)
346
import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class UpperCamelCase_ : '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict=13 , UpperCAmelCase__ : Dict=7 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=99 , UpperCAmelCase__ : Union[str, Any]=32 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : List[Any]=37 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=50 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : List[str]=None , ) ->Union[str, Any]: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = initializer_range A__ = use_labels A__ = scope def SCREAMING_SNAKE_CASE ( self : int) ->Any: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) if self.use_labels: A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = self.get_config() return config, input_ids, input_mask, token_labels def SCREAMING_SNAKE_CASE ( self : int) ->int: '''simple docstring''' return BertGenerationConfig( 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 , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Union[str, Any]: '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = self.prepare_config_and_inputs() A__ = True A__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) A__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , **UpperCAmelCase__ : List[Any] , ) ->Dict: '''simple docstring''' A__ = BertGenerationEncoder(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__) A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[Any] , ) ->Dict: '''simple docstring''' A__ = True A__ = BertGenerationEncoder(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Optional[int] , ) ->Any: '''simple docstring''' A__ = True A__ = True A__ = BertGenerationDecoder(config=UpperCAmelCase__).to(UpperCAmelCase__).eval() # first forward pass A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ , ) A__ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size) A__ = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and A__ = torch.cat([input_ids, next_tokens] , dim=-1) A__ = torch.cat([input_mask, next_mask] , dim=-1) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] # select random slice A__ = ids_tensor((1,) , output_from_past.shape[-1]).item() A__ = output_from_no_past[:, -3:, random_slice_idx].detach() A__ = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3)) def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , *UpperCAmelCase__ : List[str] , ) ->List[Any]: '''simple docstring''' A__ = BertGenerationDecoder(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->List[str]: '''simple docstring''' A__ , A__ , A__ , A__ = self.prepare_config_and_inputs() A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () UpperCAmelCase__ = (BertGenerationDecoder,) if is_torch_available() else () UpperCAmelCase__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Dict: '''simple docstring''' A__ = BertGenerationEncoderTester(self) A__ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any]) ->int: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Optional[Any]: '''simple docstring''' A__ , A__ , A__ , A__ = self.model_tester.prepare_config_and_inputs() A__ = '''bert''' self.model_tester.create_and_check_model(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any: '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() A__ = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*UpperCAmelCase__) @slow def SCREAMING_SNAKE_CASE ( self : Dict) ->List[Any]: '''simple docstring''' A__ = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') self.assertIsNotNone(UpperCAmelCase__) @require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Any) ->Union[str, Any]: '''simple docstring''' A__ = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') A__ = torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]) with torch.no_grad(): A__ = model(UpperCAmelCase__)[0] A__ = torch.Size([1, 8, 1_024]) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4)) @require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' A__ = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') A__ = torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]) with torch.no_grad(): A__ = model(UpperCAmelCase__)[0] A__ = torch.Size([1, 8, 50_358]) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4))
87
0
"""simple docstring""" import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) logging.set_verbosity_info() def lowercase__ ( lowerCAmelCase : List[Any] , lowerCAmelCase : Dict ) -> int: """simple docstring""" if "xprophetnet" in prophetnet_checkpoint_path: UpperCAmelCase = XLMProphetNetForConditionalGenerationOld.from_pretrained(lowercase_ ) UpperCAmelCase , UpperCAmelCase = XLMProphetNetForConditionalGeneration.from_pretrained( lowercase_ , output_loading_info=lowercase_ ) else: UpperCAmelCase = ProphetNetForConditionalGenerationOld.from_pretrained(lowercase_ ) UpperCAmelCase , UpperCAmelCase = ProphetNetForConditionalGeneration.from_pretrained( lowercase_ , output_loading_info=lowercase_ ) UpperCAmelCase = ['key_proj', 'value_proj', 'query_proj'] UpperCAmelCase = { 'self_attn': 'ngram_self_attn', 'cross_attn': 'encoder_attn', 'cross_attn_layer_norm': 'encoder_attn_layer_norm', 'feed_forward_layer_norm': 'final_layer_norm', 'feed_forward': '', 'intermediate': 'fc1', 'output': 'fc2', 'key_proj': 'k_proj', 'query_proj': 'q_proj', 'value_proj': 'v_proj', 'word_embeddings': 'embed_tokens', 'embeddings_layer_norm': 'emb_layer_norm', 'relative_pos_embeddings': 'relative_linear', 'ngram_embeddings': 'ngram_input_embed', 'position_embeddings': 'embed_positions', } for key in loading_info["missing_keys"]: UpperCAmelCase = key.split('.' ) if attributes[0] == "lm_head": UpperCAmelCase = prophet UpperCAmelCase = prophet_old else: UpperCAmelCase = prophet.prophetnet UpperCAmelCase = prophet_old.model UpperCAmelCase = False for attribute in attributes: if attribute in mapping: UpperCAmelCase = mapping[attribute] if not hasattr(lowercase_ , lowercase_ ) and len(lowercase_ ) > 0: UpperCAmelCase = attribute elif hasattr(lowercase_ , lowercase_ ): UpperCAmelCase = attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" UpperCAmelCase = old_model.weight logger.info(F"{attribute} is initialized." ) UpperCAmelCase = True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" UpperCAmelCase = old_model.bias logger.info(F"{attribute} is initialized" ) UpperCAmelCase = True break elif attribute in special_keys and hasattr(lowercase_ , 'in_proj_weight' ): UpperCAmelCase = old_model.in_proj_weight.shape[0] // 3 UpperCAmelCase = getattr(lowercase_ , lowercase_ ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": UpperCAmelCase = nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) UpperCAmelCase = nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": UpperCAmelCase = nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) UpperCAmelCase = nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": UpperCAmelCase = nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) UpperCAmelCase = nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) UpperCAmelCase = True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 512, "We want 512 position_embeddings." UpperCAmelCase = nn.Parameter(old_model.embed_positions.weight[:512, :] ) UpperCAmelCase = True break if attribute.isdigit(): UpperCAmelCase = model[int(lowercase_ )] UpperCAmelCase = old_model[int(lowercase_ )] else: UpperCAmelCase = getattr(lowercase_ , lowercase_ ) if old_attribute == "": UpperCAmelCase = old_model else: if not hasattr(lowercase_ , lowercase_ ): raise ValueError(F"{old_model} does not have {old_attribute}" ) UpperCAmelCase = getattr(lowercase_ , lowercase_ ) if not is_key_init: raise ValueError(F"{key} was not correctly initialized!" ) print(F"Saving model to {pytorch_dump_folder_path}" ) prophet.save_pretrained(lowercase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--prophetnet_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.''' ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
373
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 _lowerCamelCase : int = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Dict: """simple docstring""" A__ = set() A__ = [] def parse_line(lowercase_ ): for line in fp: if isinstance(lowercase_ , lowercase_ ): A__ = 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(lowercase_ ) > 0: A__ = '''\n'''.join(lowercase_ ) # Only keep the warnings specified in `targets` if any(f""": {x}: """ in warning for x in targets ): selected_warnings.add(lowercase_ ) buffer.clear() continue else: A__ = line.strip() buffer.append(lowercase_ ) if from_gh: for filename in os.listdir(lowercase_ ): A__ = os.path.join(lowercase_ , lowercase_ ) if not os.path.isdir(lowercase_ ): # read the file if filename != "warnings.txt": continue with open(lowercase_ ) as fp: parse_line(lowercase_ ) else: try: with zipfile.ZipFile(lowercase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowercase_ ): # read the file if filename != "warnings.txt": continue with z.open(lowercase_ ) as fp: parse_line(lowercase_ ) 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 SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = set() A__ = [os.path.join(lowercase_ , lowercase_ ) for p in os.listdir(lowercase_ ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(lowercase_ , lowercase_ ) ) return selected_warnings if __name__ == "__main__": def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" return values.split(''',''' ) _lowerCamelCase : int = 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.""", ) _lowerCamelCase : List[Any] = parser.parse_args() _lowerCamelCase : List[str] = 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 _lowerCamelCase : 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("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts _lowerCamelCase : Any = extract_warnings(args.output_dir, args.targets) _lowerCamelCase : Optional[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)
87
0
from __future__ import annotations from collections import namedtuple def snake_case__ ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): A : Optional[int] = namedtuple('''result''' , '''name value''' ) if (voltage, current, power).count(0 ) != 1: raise ValueError('''Only one argument must be 0''' ) elif power < 0: raise ValueError( '''Power cannot be negative in any electrical/electronics system''' ) elif voltage == 0: return result('''voltage''' , power / current ) elif current == 0: return result('''current''' , power / voltage ) elif power == 0: return result('''power''' , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
542
class UpperCamelCase_ : # Public class to implement a graph '''simple docstring''' def __init__( self : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->None: '''simple docstring''' A__ = row A__ = col A__ = graph def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->bool: '''simple docstring''' return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->None: '''simple docstring''' A__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order A__ = [-1, 0, 1, -1, 1, -1, 0, 1] A__ = True # Make those cells visited for k in range(8): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__): self.diffs(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->int: # And finally, count all islands. '''simple docstring''' A__ = [[False for j in range(self.COL)] for i in range(self.ROW)] A__ = 0 for i in range(self.ROW): for j in range(self.COL): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) count += 1 return count
87
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ,unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = UnCLIPImageVariationPipeline SCREAMING_SNAKE_CASE__ : Optional[int] = IMAGE_VARIATION_PARAMS - {'''height''', '''width''', '''guidance_scale'''} SCREAMING_SNAKE_CASE__ : Any = IMAGE_VARIATION_BATCH_PARAMS SCREAMING_SNAKE_CASE__ : Optional[int] = [ '''generator''', '''return_dict''', '''decoder_num_inference_steps''', '''super_res_num_inference_steps''', ] SCREAMING_SNAKE_CASE__ : List[str] = False @property def __UpperCAmelCase ( self : Any ): """simple docstring""" return 32 @property def __UpperCAmelCase ( self : Optional[int] ): """simple docstring""" return 32 @property def __UpperCAmelCase ( self : str ): """simple docstring""" return self.time_input_dim @property def __UpperCAmelCase ( self : Any ): """simple docstring""" return self.time_input_dim * 4 @property def __UpperCAmelCase ( self : List[Any] ): """simple docstring""" return 100 @property def __UpperCAmelCase ( self : List[str] ): """simple docstring""" _snake_case : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def __UpperCAmelCase ( self : Optional[int] ): """simple docstring""" torch.manual_seed(0 ) _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=1000 , ) return CLIPTextModelWithProjection(UpperCAmelCase__ ) @property def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" torch.manual_seed(0 ) _snake_case : Dict = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) return CLIPVisionModelWithProjection(UpperCAmelCase__ ) @property def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" torch.manual_seed(0 ) _snake_case : int = { 'clip_embeddings_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'cross_attention_dim': self.cross_attention_dim, } _snake_case : str = UnCLIPTextProjModel(**UpperCAmelCase__ ) return model @property def __UpperCAmelCase ( self : Any ): """simple docstring""" torch.manual_seed(0 ) _snake_case : Union[str, Any] = { 'sample_size': 32, # RGB in channels 'in_channels': 3, # Out channels is double in channels because predicts mean and variance 'out_channels': 6, 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': 'identity', } _snake_case : List[Any] = UNetaDConditionModel(**UpperCAmelCase__ ) return model @property def __UpperCAmelCase ( self : int ): """simple docstring""" return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def __UpperCAmelCase ( self : int ): """simple docstring""" torch.manual_seed(0 ) _snake_case : Any = UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def __UpperCAmelCase ( self : int ): """simple docstring""" torch.manual_seed(1 ) _snake_case : List[str] = UNetaDModel(**self.dummy_super_res_kwargs ) return model def __UpperCAmelCase ( self : int ): """simple docstring""" _snake_case : Optional[Any] = self.dummy_decoder _snake_case : str = self.dummy_text_proj _snake_case : Any = self.dummy_text_encoder _snake_case : Optional[int] = self.dummy_tokenizer _snake_case : str = self.dummy_super_res_first _snake_case : Union[str, Any] = self.dummy_super_res_last _snake_case : Optional[Any] = UnCLIPScheduler( variance_type='learned_range' , prediction_type='epsilon' , num_train_timesteps=1000 , ) _snake_case : Union[str, Any] = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='epsilon' , num_train_timesteps=1000 , ) _snake_case : List[Any] = CLIPImageProcessor(crop_size=32 , size=32 ) _snake_case : Dict = self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def __UpperCAmelCase ( self : Optional[Any] , snake_case : int , snake_case : Union[str, Any]=0 , snake_case : Dict=True ): """simple docstring""" _snake_case : Any = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ ) if str(UpperCAmelCase__ ).startswith('mps' ): _snake_case : Optional[int] = torch.manual_seed(UpperCAmelCase__ ) else: _snake_case : Dict = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) if pil_image: _snake_case : Optional[int] = input_image * 0.5 + 0.5 _snake_case : Optional[int] = input_image.clamp(0 , 1 ) _snake_case : Union[str, Any] = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() _snake_case : Union[str, Any] = DiffusionPipeline.numpy_to_pil(UpperCAmelCase__ )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def __UpperCAmelCase ( self : str ): """simple docstring""" _snake_case : str = 'cpu' _snake_case : str = self.get_dummy_components() _snake_case : str = self.pipeline_class(**UpperCAmelCase__ ) _snake_case : Optional[int] = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _snake_case : int = self.get_dummy_inputs(UpperCAmelCase__ , pil_image=UpperCAmelCase__ ) _snake_case : Optional[int] = pipe(**UpperCAmelCase__ ) _snake_case : int = output.images _snake_case : Dict = self.get_dummy_inputs(UpperCAmelCase__ , pil_image=UpperCAmelCase__ ) _snake_case : Optional[int] = pipe( **UpperCAmelCase__ , return_dict=UpperCAmelCase__ , )[0] _snake_case : Optional[int] = image[0, -3:, -3:, -1] _snake_case : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _snake_case : str = np.array( [ 0.9997, 0.0002, 0.9997, 0.9997, 0.9969, 0.0023, 0.9997, 0.9969, 0.9970, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCAmelCase ( self : Optional[int] ): """simple docstring""" _snake_case : Union[str, Any] = 'cpu' _snake_case : Optional[Any] = self.get_dummy_components() _snake_case : Union[str, Any] = self.pipeline_class(**UpperCAmelCase__ ) _snake_case : str = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _snake_case : str = self.get_dummy_inputs(UpperCAmelCase__ , pil_image=UpperCAmelCase__ ) _snake_case : Any = pipe(**UpperCAmelCase__ ) _snake_case : List[Any] = output.images _snake_case : List[Any] = self.get_dummy_inputs(UpperCAmelCase__ , pil_image=UpperCAmelCase__ ) _snake_case : Union[str, Any] = pipe( **UpperCAmelCase__ , return_dict=UpperCAmelCase__ , )[0] _snake_case : List[Any] = image[0, -3:, -3:, -1] _snake_case : Tuple = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _snake_case : List[str] = np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCAmelCase ( self : Dict ): """simple docstring""" _snake_case : str = 'cpu' _snake_case : Optional[Any] = self.get_dummy_components() _snake_case : Union[str, Any] = self.pipeline_class(**UpperCAmelCase__ ) _snake_case : List[Any] = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _snake_case : Dict = self.get_dummy_inputs(UpperCAmelCase__ , pil_image=UpperCAmelCase__ ) _snake_case : Optional[int] = [ pipeline_inputs['image'], pipeline_inputs['image'], ] _snake_case : Any = pipe(**UpperCAmelCase__ ) _snake_case : str = output.images _snake_case : Union[str, Any] = self.get_dummy_inputs(UpperCAmelCase__ , pil_image=UpperCAmelCase__ ) _snake_case : Union[str, Any] = [ tuple_pipeline_inputs['image'], tuple_pipeline_inputs['image'], ] _snake_case : List[Any] = pipe( **UpperCAmelCase__ , return_dict=UpperCAmelCase__ , )[0] _snake_case : Optional[Any] = image[0, -3:, -3:, -1] _snake_case : List[str] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) _snake_case : Dict = np.array( [ 0.9997, 0.9989, 0.0008, 0.0021, 0.9960, 0.0018, 0.0014, 0.0002, 0.9933, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCAmelCase ( self : Union[str, Any] ): """simple docstring""" _snake_case : int = torch.device('cpu' ) class SCREAMING_SNAKE_CASE : '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 1 _snake_case : Optional[Any] = self.get_dummy_components() _snake_case : Union[str, Any] = self.pipeline_class(**UpperCAmelCase__ ) _snake_case : Tuple = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _snake_case : Dict = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) _snake_case : Any = pipe.decoder.dtype _snake_case : Dict = 1 _snake_case : str = ( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) _snake_case : Optional[Any] = pipe.prepare_latents( UpperCAmelCase__ , dtype=UpperCAmelCase__ , device=UpperCAmelCase__ , generator=UpperCAmelCase__ , latents=UpperCAmelCase__ , scheduler=DummyScheduler() ) _snake_case : Union[str, Any] = ( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) _snake_case : List[Any] = pipe.prepare_latents( UpperCAmelCase__ , dtype=UpperCAmelCase__ , device=UpperCAmelCase__ , generator=UpperCAmelCase__ , latents=UpperCAmelCase__ , scheduler=DummyScheduler() ) _snake_case : List[Any] = self.get_dummy_inputs(UpperCAmelCase__ , pil_image=UpperCAmelCase__ ) _snake_case : List[str] = pipe( **UpperCAmelCase__ , decoder_latents=UpperCAmelCase__ , super_res_latents=UpperCAmelCase__ ).images _snake_case : Optional[int] = self.get_dummy_inputs(UpperCAmelCase__ , pil_image=UpperCAmelCase__ ) # Don't pass image, instead pass embedding _snake_case : Optional[Any] = pipeline_inputs.pop('image' ) _snake_case : Optional[int] = pipe.image_encoder(UpperCAmelCase__ ).image_embeds _snake_case : List[Any] = pipe( **UpperCAmelCase__ , decoder_latents=UpperCAmelCase__ , super_res_latents=UpperCAmelCase__ , image_embeddings=UpperCAmelCase__ , ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1e-4 @skip_mps def __UpperCAmelCase ( self : Tuple ): """simple docstring""" _snake_case : List[str] = torch_device == 'cpu' # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor _snake_case : Tuple = 1e-2 self._test_attention_slicing_forward_pass( test_max_difference=UpperCAmelCase__ , expected_max_diff=UpperCAmelCase__ ) @skip_mps def __UpperCAmelCase ( self : List[str] ): """simple docstring""" _snake_case : Tuple = torch_device == 'cpu' _snake_case : List[Any] = True _snake_case : Union[str, Any] = [ 'decoder_num_inference_steps', 'super_res_num_inference_steps', ] self._test_inference_batch_single_identical( test_max_difference=UpperCAmelCase__ , relax_max_difference=UpperCAmelCase__ , additional_params_copy_to_batched_inputs=UpperCAmelCase__ , ) def __UpperCAmelCase ( self : Any ): """simple docstring""" _snake_case : Dict = [ 'decoder_num_inference_steps', 'super_res_num_inference_steps', ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes _snake_case : Tuple = [2, 3] self._test_inference_batch_consistent( batch_sizes=UpperCAmelCase__ , additional_params_copy_to_batched_inputs=UpperCAmelCase__ , ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=UpperCAmelCase__ ) @skip_mps def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" return super().test_dict_tuple_outputs_equivalent() @skip_mps def __UpperCAmelCase ( self : int ): """simple docstring""" return super().test_save_load_local() @skip_mps def __UpperCAmelCase ( self : Optional[int] ): """simple docstring""" return super().test_save_load_optional_components() @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self : Any ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" _snake_case : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png' ) _snake_case : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/unclip/karlo_v1_alpha_cat_variation_fp16.npy' ) _snake_case : str = UnCLIPImageVariationPipeline.from_pretrained( 'kakaobrain/karlo-v1-alpha-image-variations' , torch_dtype=torch.floataa ) _snake_case : List[Any] = pipeline.to(UpperCAmelCase__ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase__ ) _snake_case : Any = torch.Generator(device='cpu' ).manual_seed(0 ) _snake_case : Tuple = pipeline( UpperCAmelCase__ , generator=UpperCAmelCase__ , output_type='np' , ) _snake_case : Any = output.images[0] assert image.shape == (256, 256, 3) assert_mean_pixel_difference(UpperCAmelCase__ , UpperCAmelCase__ , 15 )
517
from __future__ import annotations import requests _lowerCamelCase : str = set( """approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod_post category clicked content_categories created_utc downs edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta is_original_content is_reddit_media_domain is_video link_flair_css_class link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title name permalink pwls quarantine saved score secure_media secure_media_embed selftext subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type total_awards_received ups upvote_ratio url user_reports""".split() ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = 1 , lowercase_ = "new" , lowercase_ = None ) -> dict: """simple docstring""" A__ = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(lowercase_ ) - valid_terms ) ): A__ = f"""Invalid search term: {invalid_search_terms}""" raise ValueError(lowercase_ ) A__ = requests.get( f"""https://reddit.com/r/{subreddit}/{age}.json?limit={limit}""" , headers={'''User-agent''': '''A random string'''} , ) if response.status_code == 429: raise requests.HTTPError A__ = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(lowercase_ )} A__ = {} for id_ in range(lowercase_ ): A__ = { item: data['''data''']['''children'''][id_]['''data'''][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("""learnpython""", wanted_data=["""title""", """url""", """selftext"""]))
87
0
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ,unittest.TestCase ): __SCREAMING_SNAKE_CASE :Optional[int] = DiTPipeline __SCREAMING_SNAKE_CASE :Dict = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS __SCREAMING_SNAKE_CASE :Tuple = PipelineTesterMixin.required_optional_params - { """latents""", """num_images_per_prompt""", """callback""", """callback_steps""", } __SCREAMING_SNAKE_CASE :List[str] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE :Tuple = False def snake_case__ ( self : int ): torch.manual_seed(0 ) __magic_name__ = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=UpperCAmelCase__ , activation_fn='''gelu-approximate''' , num_embeds_ada_norm=1000 , norm_type='''ada_norm_zero''' , norm_elementwise_affine=UpperCAmelCase__ , ) __magic_name__ = AutoencoderKL() __magic_name__ = DDIMScheduler() __magic_name__ = {'''transformer''': transformer.eval(), '''vae''': vae.eval(), '''scheduler''': scheduler} return components def snake_case__ ( self : Any , a__ : str , a__ : List[Any]=0 ): if str(UpperCAmelCase__ ).startswith('''mps''' ): __magic_name__ = torch.manual_seed(UpperCAmelCase__ ) else: __magic_name__ = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) __magic_name__ = { '''class_labels''': [1], '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def snake_case__ ( self : List[Any] ): __magic_name__ = '''cpu''' __magic_name__ = self.get_dummy_components() __magic_name__ = self.pipeline_class(**UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __magic_name__ = self.get_dummy_inputs(UpperCAmelCase__ ) __magic_name__ = pipe(**UpperCAmelCase__ ).images __magic_name__ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) __magic_name__ = np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457] ) __magic_name__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(UpperCAmelCase__ , 1E-3 ) def snake_case__ ( self : Any ): self._test_inference_batch_single_identical(relax_max_difference=UpperCAmelCase__ , expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def snake_case__ ( self : Any ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def snake_case__ ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case__ ( self : Tuple ): __magic_name__ = torch.manual_seed(0 ) __magic_name__ = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-256''' ) pipe.to('''cuda''' ) __magic_name__ = ['''vase''', '''umbrella''', '''white shark''', '''white wolf'''] __magic_name__ = pipe.get_label_ids(UpperCAmelCase__ ) __magic_name__ = pipe(UpperCAmelCase__ , generator=UpperCAmelCase__ , num_inference_steps=40 , output_type='''np''' ).images for word, image in zip(UpperCAmelCase__ , UpperCAmelCase__ ): __magic_name__ = load_numpy( F'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy''' ) assert np.abs((expected_image - image).max() ) < 1E-2 def snake_case__ ( self : Optional[int] ): __magic_name__ = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-512''' ) __magic_name__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to('''cuda''' ) __magic_name__ = ['''vase''', '''umbrella'''] __magic_name__ = pipe.get_label_ids(UpperCAmelCase__ ) __magic_name__ = torch.manual_seed(0 ) __magic_name__ = pipe(UpperCAmelCase__ , generator=UpperCAmelCase__ , num_inference_steps=25 , output_type='''np''' ).images for word, image in zip(UpperCAmelCase__ , UpperCAmelCase__ ): __magic_name__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' F'''/dit/{word}_512.npy''' ) assert np.abs((expected_image - image).max() ) < 1E-1
432
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = JukeboxTokenizer UpperCAmelCase__ = { '''artist''': '''Zac Brown Band''', '''genres''': '''Country''', '''lyrics''': '''I met a traveller from an antique land, Who said "Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away ''', } @require_torch def SCREAMING_SNAKE_CASE ( self : Dict) ->int: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''') A__ = tokenizer(**self.metas)['''input_ids'''] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 7_169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]]), torch.tensor([[0, 0, 0, 1_069, 11]]), torch.tensor([[0, 0, 0, 1_069, 11]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2])) @require_torch def SCREAMING_SNAKE_CASE ( self : List[str]) ->Optional[int]: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''') A__ = tokenizer(**self.metas)['''input_ids'''] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 1_069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]]), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]]), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2]))
87
0
'''simple docstring''' import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def UpperCamelCase_( snake_case : str ): '''simple docstring''' def wrapper(*snake_case : Tuple , **snake_case : Dict ): snake_case_ = timeit.default_timer() snake_case_ = func(*lowercase_ , **lowercase_ ) snake_case_ = timeit.default_timer() - starttime return delta snake_case_ = func.__name__ return wrapper def UpperCamelCase_( snake_case : Any , snake_case : List[Any]=1_0_0 , snake_case : List[str]=None ): '''simple docstring''' snake_case_ = [] snake_case_ = seq_shapes or {} for i in range(lowercase_ ): snake_case_ = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(lowercase_ , _ArrayXD ): snake_case_ = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(lowercase_ , datasets.Value ): if v.dtype == "string": snake_case_ = "The small grey turtle was surprisingly fast when challenged." else: snake_case_ = np.random.randint(1_0 , size=1 ).astype(v.dtype ).item() elif isinstance(lowercase_ , datasets.Sequence ): while isinstance(lowercase_ , datasets.Sequence ): snake_case_ = v.feature snake_case_ = seq_shapes[k] snake_case_ = np.random.rand(*lowercase_ ).astype(v.dtype ) snake_case_ = data dummy_data.append((i, example) ) return dummy_data def UpperCamelCase_( snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Optional[Any]=1_0_0 , snake_case : Any=None ): '''simple docstring''' snake_case_ = generate_examples(lowercase_ , num_examples=lowercase_ , seq_shapes=lowercase_ ) with ArrowWriter(features=lowercase_ , path=lowercase_ ) as writer: for key, record in dummy_data: snake_case_ = features.encode_example(lowercase_ ) writer.write(lowercase_ ) snake_case_ , snake_case_ = 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}.' ) snake_case_ = datasets.Dataset.from_file(filename=lowercase_ , info=datasets.DatasetInfo(features=lowercase_ ) ) return dataset
400
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : str = logging.get_logger(__name__) _lowerCamelCase : List[str] = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''openai-gpt''' UpperCAmelCase__ = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict=40_478 , UpperCAmelCase__ : str=512 , UpperCAmelCase__ : Union[str, Any]=768 , UpperCAmelCase__ : Optional[Any]=12 , UpperCAmelCase__ : Any=12 , UpperCAmelCase__ : Optional[Any]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : List[str]=1e-5 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Any="cls_index" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Optional[Any]=0.1 , **UpperCAmelCase__ : Dict , ) ->Any: '''simple docstring''' A__ = vocab_size A__ = n_positions A__ = n_embd A__ = n_layer A__ = n_head A__ = afn A__ = resid_pdrop A__ = embd_pdrop A__ = attn_pdrop A__ = layer_norm_epsilon A__ = initializer_range A__ = summary_type A__ = summary_use_proj A__ = summary_activation A__ = summary_first_dropout A__ = summary_proj_to_labels super().__init__(**UpperCAmelCase__)
87
0
'''simple docstring''' import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class A_ ( unittest.TestCase ): '''simple docstring''' def a ( self ): _UpperCamelCase = Vector([1, 2, 3] ) self.assertEqual(x.component(0 ) , 1 ) self.assertEqual(x.component(2 ) , 3 ) _UpperCamelCase = Vector() def a ( self ): _UpperCamelCase = Vector([0, 0, 0, 0, 0, 1] ) self.assertEqual(str(UpperCAmelCase__ ) , "(0,0,0,0,0,1)" ) def a ( self ): _UpperCamelCase = Vector([1, 2, 3, 4] ) self.assertEqual(len(UpperCAmelCase__ ) , 4 ) def a ( self ): _UpperCamelCase = Vector([1, 2] ) _UpperCamelCase = Vector([1, 2, 3, 4, 5] ) _UpperCamelCase = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) _UpperCamelCase = Vector([1, -1, 1, -1, 2, -3, 4, -5] ) self.assertAlmostEqual(x.euclidean_length() , 2.236 , 3 ) self.assertAlmostEqual(y.euclidean_length() , 7.416 , 3 ) self.assertEqual(z.euclidean_length() , 0 ) self.assertAlmostEqual(w.euclidean_length() , 7.616 , 3 ) def a ( self ): _UpperCamelCase = Vector([1, 2, 3] ) _UpperCamelCase = Vector([1, 1, 1] ) self.assertEqual((x + y).component(0 ) , 2 ) self.assertEqual((x + y).component(1 ) , 3 ) self.assertEqual((x + y).component(2 ) , 4 ) def a ( self ): _UpperCamelCase = Vector([1, 2, 3] ) _UpperCamelCase = Vector([1, 1, 1] ) self.assertEqual((x - y).component(0 ) , 0 ) self.assertEqual((x - y).component(1 ) , 1 ) self.assertEqual((x - y).component(2 ) , 2 ) def a ( self ): _UpperCamelCase = Vector([1, 2, 3] ) _UpperCamelCase = Vector([2, -1, 4] ) # for test of dot product _UpperCamelCase = Vector([1, -2, -1] ) self.assertEqual(str(x * 3.0 ) , "(3.0,6.0,9.0)" ) self.assertEqual((a * b) , 0 ) def a ( self ): self.assertEqual(str(zero_vector(10 ) ).count("0" ) , 10 ) def a ( self ): self.assertEqual(str(unit_basis_vector(3 , 1 ) ) , "(0,1,0)" ) def a ( self ): _UpperCamelCase = Vector([1, 2, 3] ) _UpperCamelCase = Vector([1, 0, 1] ) self.assertEqual(str(axpy(2 , UpperCAmelCase__ , UpperCAmelCase__ ) ) , "(3,4,7)" ) def a ( self ): _UpperCamelCase = Vector([1, 0, 0, 0, 0, 0] ) _UpperCamelCase = x.copy() self.assertEqual(str(UpperCAmelCase__ ) , str(UpperCAmelCase__ ) ) def a ( self ): _UpperCamelCase = Vector([1, 0, 0] ) x.change_component(0 , 0 ) x.change_component(1 , 1 ) self.assertEqual(str(UpperCAmelCase__ ) , "(0,1,0)" ) def a ( self ): _UpperCamelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n" , str(UpperCAmelCase__ ) ) def a ( self ): _UpperCamelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) _UpperCamelCase = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(minors[x][y] , a.minor(UpperCAmelCase__ , UpperCAmelCase__ ) ) def a ( self ): _UpperCamelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) _UpperCamelCase = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(cofactors[x][y] , a.cofactor(UpperCAmelCase__ , UpperCAmelCase__ ) ) def a ( self ): _UpperCamelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(-5 , a.determinant() ) def a ( self ): _UpperCamelCase = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3 ) _UpperCamelCase = Vector([1, 2, 3] ) self.assertEqual("(14,32,50)" , str(a * x ) ) self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n" , str(a * 2 ) ) def a ( self ): _UpperCamelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) a.change_component(0 , 2 , 5 ) self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n" , str(UpperCAmelCase__ ) ) def a ( self ): _UpperCamelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(7 , a.component(2 , 1 ) , 0.01 ) def a ( self ): _UpperCamelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) _UpperCamelCase = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n" , str(a + b ) ) def a ( self ): _UpperCamelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) _UpperCamelCase = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n" , str(a - b ) ) def a ( self ): self.assertEqual( "|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n" , str(square_zero_matrix(5 ) ) , ) if __name__ == "__main__": unittest.main()
138
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
import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() __magic_name__: List[str] = logging.get_logger(__name__) def UpperCamelCase ( _A, _A, _A ): """simple docstring""" __magic_name__ : Tuple = WavaVecaForSequenceClassification.from_pretrained(lowercase_, config=lowercase_ ) __magic_name__ : Dict = downstream_dict["""projector.weight"""] __magic_name__ : List[str] = downstream_dict["""projector.bias"""] __magic_name__ : List[Any] = downstream_dict["""model.post_net.linear.weight"""] __magic_name__ : List[str] = downstream_dict["""model.post_net.linear.bias"""] return model def UpperCamelCase ( _A, _A, _A ): """simple docstring""" __magic_name__ : Union[str, Any] = WavaVecaForAudioFrameClassification.from_pretrained(lowercase_, config=lowercase_ ) __magic_name__ : Dict = downstream_dict["""model.linear.weight"""] __magic_name__ : int = downstream_dict["""model.linear.bias"""] return model def UpperCamelCase ( _A, _A, _A ): """simple docstring""" __magic_name__ : List[str] = WavaVecaForXVector.from_pretrained(lowercase_, config=lowercase_ ) __magic_name__ : Any = downstream_dict["""connector.weight"""] __magic_name__ : List[str] = downstream_dict["""connector.bias"""] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): __magic_name__ : Union[str, Any] = downstream_dict[ f'model.framelevel_feature_extractor.module.{i}.kernel.weight' ] __magic_name__ : Optional[Any] = downstream_dict[f'model.framelevel_feature_extractor.module.{i}.kernel.bias'] __magic_name__ : Tuple = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""] __magic_name__ : Any = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""] __magic_name__ : int = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""] __magic_name__ : int = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""] __magic_name__ : Any = downstream_dict["""objective.W"""] return model @torch.no_grad() def UpperCamelCase ( _A, _A, _A, _A ): """simple docstring""" __magic_name__ : int = torch.load(lowercase_, map_location="""cpu""" ) __magic_name__ : Optional[int] = checkpoint["""Downstream"""] __magic_name__ : List[Any] = WavaVecaConfig.from_pretrained(lowercase_ ) __magic_name__ : Optional[int] = WavaVecaFeatureExtractor.from_pretrained( lowercase_, return_attention_mask=lowercase_, do_normalize=lowercase_ ) __magic_name__ : Optional[int] = hf_config.architectures[0] if arch.endswith("""ForSequenceClassification""" ): __magic_name__ : Tuple = convert_classification(lowercase_, lowercase_, lowercase_ ) elif arch.endswith("""ForAudioFrameClassification""" ): __magic_name__ : List[Any] = convert_diarization(lowercase_, lowercase_, lowercase_ ) elif arch.endswith("""ForXVector""" ): __magic_name__ : Optional[Any] = convert_xvector(lowercase_, lowercase_, lowercase_ ) else: raise NotImplementedError(f'S3PRL weights conversion is not supported for {arch}' ) if hf_config.use_weighted_layer_sum: __magic_name__ : Any = checkpoint["""Featurizer"""]["""weights"""] hf_feature_extractor.save_pretrained(lowercase_ ) hf_model.save_pretrained(lowercase_ ) if __name__ == "__main__": __magic_name__: Dict = argparse.ArgumentParser() parser.add_argument( "--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model." ) parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.") parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.") __magic_name__: List[str] = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
324
import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None ) -> Dict: """simple docstring""" if "." in tensor_name: A__ = tensor_name.split('''.''' ) for split in splits[:-1]: A__ = getattr(lowercase_ , lowercase_ ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) A__ = new_module A__ = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(f"""{module} does not have a parameter or a buffer named {tensor_name}.""" ) A__ = tensor_name in module._buffers A__ = getattr(lowercase_ , lowercase_ ) if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None: raise ValueError(f"""{tensor_name} is on the meta device, we need a `value` to put in on {device}.""" ) A__ = False A__ = False if is_buffer or not is_bitsandbytes_available(): A__ = False A__ = False else: A__ = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) A__ = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: A__ = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to('''cpu''' ) if value.dtype == torch.inta: A__ = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse( '''0.37.2''' ) if not is_abit_serializable: raise ValueError( '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ''' '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' ) else: A__ = torch.tensor(lowercase_ , device='''cpu''' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , lowercase_ ) and fpaa_statistics is None: A__ = new_value.T A__ = old_value.__dict__ if is_abit: A__ = bnb.nn.IntaParams(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) elif is_abit: A__ = bnb.nn.Paramsabit(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) A__ = new_value if fpaa_statistics is not None: setattr(module.weight , '''SCB''' , fpaa_statistics.to(lowercase_ ) ) else: if value is None: A__ = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): A__ = value.to(lowercase_ ) else: A__ = torch.tensor(lowercase_ , device=lowercase_ ) if is_buffer: A__ = new_value else: A__ = nn.Parameter(lowercase_ , requires_grad=old_value.requires_grad ) A__ = new_value def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=False ) -> Dict: """simple docstring""" for name, module in model.named_children(): if current_key_name is None: A__ = [] current_key_name.append(lowercase_ ) if (isinstance(lowercase_ , nn.Linear ) or isinstance(lowercase_ , lowercase_ )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '''.'''.join(lowercase_ ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(lowercase_ , lowercase_ ): A__ , A__ = module.weight.shape else: A__ = module.in_features A__ = module.out_features if quantization_config.quantization_method() == "llm_int8": A__ = bnb.nn.LinearabitLt( lowercase_ , lowercase_ , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) A__ = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: A__ = bnb.nn.Linearabit( lowercase_ , lowercase_ , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) A__ = True # Store the module class in case we need to transpose the weight later A__ = type(lowercase_ ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(lowercase_ ) if len(list(module.children() ) ) > 0: A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ , has_been_replaced=lowercase_ , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None ) -> Tuple: """simple docstring""" A__ = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert A__ , A__ = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Dict: """simple docstring""" warnings.warn( '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , lowercase_ , ) return replace_with_bnb_linear(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Optional[Any]: """simple docstring""" warnings.warn( '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , lowercase_ , ) return set_module_quantized_tensor_to_device(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]: """simple docstring""" A__ = deepcopy(lowercase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() A__ = find_tied_parameters(lowercase_ ) # For compatibility with Accelerate < 0.18 if isinstance(lowercase_ , lowercase_ ): A__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: A__ = sum(lowercase_ , [] ) A__ = len(lowercase_ ) > 0 # Check if it is a base model A__ = not hasattr(lowercase_ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head A__ = list(model.named_children() ) A__ = [list_modules[-1][0]] # add last module together with tied weights A__ = set(lowercase_ ) - set(lowercase_ ) A__ = list(set(lowercase_ ) ) + list(lowercase_ ) # remove ".weight" from the keys A__ = ['''.weight''', '''.bias'''] A__ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: A__ = name.replace(lowercase_ , '''''' ) filtered_module_names.append(lowercase_ ) return filtered_module_names
87
0
from __future__ import annotations A : int = [True] * 1_00_00_01 A : Optional[int] = 2 while i * i <= 1_00_00_00: if seive[i]: for j in range(i * i, 1_00_00_01, i): A : Optional[int] = False i += 1 def a__ ( __UpperCamelCase ): return seive[n] def a__ ( __UpperCamelCase ): return any(digit in "02468" for digit in str(lowercase_ ) ) def a__ ( __UpperCamelCase = 1_0_0_0_0_0_0 ): SCREAMING_SNAKE_CASE_ = [2] # result already includes the number 2. for num in range(3 , limit + 1 , 2 ): if is_prime(lowercase_ ) and not contains_an_even_digit(lowercase_ ): SCREAMING_SNAKE_CASE_ = str(lowercase_ ) SCREAMING_SNAKE_CASE_ = [int(str_num[j:] + str_num[:j] ) for j in range(len(lowercase_ ) )] if all(is_prime(lowercase_ ) for i in list_nums ): result.append(lowercase_ ) return result def a__ ( ): return len(find_circular_primes() ) if __name__ == "__main__": print(f"{len(find_circular_primes()) = }")
140
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) _lowerCamelCase : str = 299792458 # Symbols _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = symbols("""ct x y z""") def SCREAMING_SNAKE_CASE ( lowercase_ ) -> float: """simple docstring""" 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 ( lowercase_ ) -> float: """simple docstring""" return 1 / sqrt(1 - beta(lowercase_ ) ** 2 ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> np.ndarray: """simple docstring""" return np.array( [ [gamma(lowercase_ ), -gamma(lowercase_ ) * beta(lowercase_ ), 0, 0], [-gamma(lowercase_ ) * beta(lowercase_ ), gamma(lowercase_ ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = None ) -> np.ndarray: """simple docstring""" if event is None: A__ = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(lowercase_ ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: _lowerCamelCase : Tuple = transform(29979245) 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 _lowerCamelCase : int = {ct: c, x: 1, y: 1, z: 1} _lowerCamelCase : Any = [four_vector[i].subs(sub_dict) for i in range(4)] print(F'''\n{numerical_vector}''')
87
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase__ :Any = {"""configuration_xlnet""": ["""XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ :int = ["""XLNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ :int = ["""XLNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ :Union[str, Any] = [ """XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLNetForMultipleChoice""", """XLNetForQuestionAnswering""", """XLNetForQuestionAnsweringSimple""", """XLNetForSequenceClassification""", """XLNetForTokenClassification""", """XLNetLMHeadModel""", """XLNetModel""", """XLNetPreTrainedModel""", """load_tf_weights_in_xlnet""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ :Dict = [ """TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLNetForMultipleChoice""", """TFXLNetForQuestionAnsweringSimple""", """TFXLNetForSequenceClassification""", """TFXLNetForTokenClassification""", """TFXLNetLMHeadModel""", """TFXLNetMainLayer""", """TFXLNetModel""", """TFXLNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys UpperCamelCase__ :int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
355
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> list: """simple docstring""" if len(lowercase_ ) <= 1: return [tuple(lowercase_ )] A__ = [] def generate(lowercase_ , lowercase_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , lowercase_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even A__ , A__ = arr[k - 1], arr[i] else: # k is odd A__ , A__ = arr[k - 1], arr[0] generate(k - 1 , lowercase_ ) generate(len(lowercase_ ) , lowercase_ ) return res if __name__ == "__main__": _lowerCamelCase : int = input("""Enter numbers separated by a comma:\n""").strip() _lowerCamelCase : str = [int(item) for item in user_input.split(""",""")] print(heaps(arr))
87
0
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCamelCase__ = datasets.logging.get_logger(__name__) UpperCamelCase__ = """\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\", author = \"Moosavi, Nafise Sadat and Strube, Michael\", booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\", month = aug, year = \"2016\", address = \"Berlin, Germany\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/P16-1060\", doi = \"10.18653/v1/P16-1060\", pages = \"632--642\", } """ UpperCamelCase__ = """\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. """ UpperCamelCase__ = """ Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting 'keep_singletons=False', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs. min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: 'mentions': mentions 'muc': MUC metric [Vilain et al, 1995] 'bcub': B-cubed [Bagga and Baldwin, 1998] 'ceafe': CEAFe [Luo et al., 2005] 'lea': LEA [Moosavi and Strube, 2016] 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric('coval') >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -', ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)', ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)', ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -', ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -', ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {'mentions/recall': 1.0,[...] 'conll_score': 100.0} """ def UpperCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_=False , UpperCAmelCase_=False , UpperCAmelCase_=True , UpperCAmelCase_=False , UpperCAmelCase_="dummy_doc" ) -> Optional[int]: '''simple docstring''' _lowercase : List[Any] = {doc: key_lines} _lowercase : int = {doc: sys_lines} _lowercase : Optional[Any] = {} _lowercase : Optional[Any] = 0 _lowercase : Tuple = 0 _lowercase : Optional[Any] = 0 _lowercase : Optional[int] = 0 _lowercase : Union[str, Any] = 0 _lowercase : int = 0 _lowercase , _lowercase : List[Any] = reader.get_doc_mentions(lowercase_ , key_doc_lines[doc] , lowercase_ ) key_singletons_num += singletons_num if NP_only or min_span: _lowercase : Any = reader.set_annotated_parse_trees(lowercase_ , key_doc_lines[doc] , lowercase_ , lowercase_ ) _lowercase , _lowercase : str = reader.get_doc_mentions(lowercase_ , sys_doc_lines[doc] , lowercase_ ) sys_singletons_num += singletons_num if NP_only or min_span: _lowercase : str = reader.set_annotated_parse_trees(lowercase_ , key_doc_lines[doc] , lowercase_ , lowercase_ ) if remove_nested: _lowercase , _lowercase : Any = reader.remove_nested_coref_mentions(lowercase_ , lowercase_ ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters _lowercase , _lowercase : List[Any] = reader.remove_nested_coref_mentions(lowercase_ , lowercase_ ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters _lowercase : Union[str, Any] = reader.get_mention_assignments(lowercase_ , lowercase_ ) _lowercase : int = reader.get_mention_assignments(lowercase_ , lowercase_ ) _lowercase : List[str] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( '''Number of removed nested coreferring mentions in the key ''' F'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( '''Number of resulting singleton clusters in the key ''' F'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( F'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' '''files, respectively''' ) return doc_coref_infos def UpperCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) -> List[Any]: '''simple docstring''' _lowercase : Union[str, Any] = get_coref_infos(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) _lowercase : Any = {} _lowercase : Any = 0 _lowercase : Any = 0 for name, metric in metrics: _lowercase , _lowercase , _lowercase : Tuple = evaluator.evaluate_documents(lowercase_ , lowercase_ , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({F'{name}/recall': recall, F'{name}/precision': precision, F'{name}/f1': fa} ) logger.info( name.ljust(10 ) , F'Recall: {recall * 100:.2f}' , F' Precision: {precision * 100:.2f}' , F' F1: {fa * 100:.2f}' , ) if conll_subparts_num == 3: _lowercase : Optional[Any] = (conll / 3) * 100 logger.info(F'CoNLL score: {conll:.2f}' ) output_scores.update({'''conll_score''': conll} ) return output_scores def UpperCamelCase__ ( UpperCAmelCase_ ) -> Dict: '''simple docstring''' _lowercase : int = False for line in key_lines: if not line.startswith('''#''' ): if len(line.split() ) > 6: _lowercase : List[Any] = line.split()[5] if not parse_col == "-": _lowercase : Tuple = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase__ ( datasets.Metric ): '''simple docstring''' def lowerCAmelCase_ ( self : List[str] ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' ) ), '''references''': datasets.Sequence(datasets.Value('''string''' ) ), } ) , codebase_urls=['''https://github.com/ns-moosavi/coval'''] , reference_urls=[ '''https://github.com/ns-moosavi/coval''', '''https://www.aclweb.org/anthology/P16-1060''', '''http://www.conll.cemantix.org/2012/data.html''', ] , ) def lowerCAmelCase_ ( self : Optional[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Dict , UpperCamelCase : Any=True , UpperCamelCase : Any=False , UpperCamelCase : int=False , UpperCamelCase : Optional[Any]=False ): """simple docstring""" _lowercase : Optional[int] = [ ('''mentions''', evaluator.mentions), ('''muc''', evaluator.muc), ('''bcub''', evaluator.b_cubed), ('''ceafe''', evaluator.ceafe), ('''lea''', evaluator.lea), ] if min_span: _lowercase : List[Any] = util.check_gold_parse_annotation(UpperCAmelCase__ ) if not has_gold_parse: raise NotImplementedError('''References should have gold parse annotation to use \'min_span\'.''' ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" _lowercase : Union[str, Any] = evaluate( key_lines=UpperCAmelCase__ , sys_lines=UpperCAmelCase__ , metrics=UpperCAmelCase__ , NP_only=UpperCAmelCase__ , remove_nested=UpperCAmelCase__ , keep_singletons=UpperCAmelCase__ , min_span=UpperCAmelCase__ , ) return score
322
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Union[str, Any]: """simple docstring""" A__ = np.max(_outputs , axis=-1 , keepdims=lowercase_ ) A__ = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowercase_ ) class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''sigmoid''' UpperCAmelCase__ = '''softmax''' UpperCAmelCase__ = '''none''' @add_end_docstrings( UpperCAmelCase__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = False UpperCAmelCase__ = ClassificationFunction.NONE def __init__( self : Any , **UpperCAmelCase__ : Optional[Any]) ->str: '''simple docstring''' super().__init__(**UpperCAmelCase__) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) def SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int="" , **UpperCAmelCase__ : Any) ->int: '''simple docstring''' A__ = tokenizer_kwargs A__ = {} if hasattr(self.model.config , '''return_all_scores''') and return_all_scores is None: A__ = self.model.config.return_all_scores if isinstance(UpperCAmelCase__ , UpperCAmelCase__) or top_k is None: A__ = top_k A__ = False elif return_all_scores is not None: warnings.warn( '''`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of''' ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.''' , UpperCAmelCase__ , ) if return_all_scores: A__ = None else: A__ = 1 if isinstance(UpperCAmelCase__ , UpperCAmelCase__): A__ = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: A__ = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self : str , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : Optional[int]) ->Union[str, Any]: '''simple docstring''' A__ = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__) # TODO try and retrieve it in a nicer way from _sanitize_parameters. A__ = '''top_k''' not in kwargs if isinstance(args[0] , UpperCAmelCase__) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : Any , **UpperCAmelCase__ : str) ->Dict[str, GenericTensor]: '''simple docstring''' A__ = self.framework if isinstance(UpperCAmelCase__ , UpperCAmelCase__): return self.tokenizer(**UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__) and len(UpperCAmelCase__) == 1 and isinstance(inputs[0] , UpperCAmelCase__) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a''' ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.''') return self.tokenizer(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : Tuple) ->Tuple: '''simple docstring''' return self.model(**UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : str=True) ->Dict: '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: A__ = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: A__ = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''') and function_to_apply is None: A__ = self.model.config.function_to_apply else: A__ = ClassificationFunction.NONE A__ = model_outputs['''logits'''][0] A__ = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: A__ = sigmoid(UpperCAmelCase__) elif function_to_apply == ClassificationFunction.SOFTMAX: A__ = softmax(UpperCAmelCase__) elif function_to_apply == ClassificationFunction.NONE: A__ = outputs else: raise ValueError(f"""Unrecognized `function_to_apply` argument: {function_to_apply}""") if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} A__ = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(UpperCAmelCase__) ] if not _legacy: dict_scores.sort(key=lambda UpperCAmelCase__: x["score"] , reverse=UpperCAmelCase__) if top_k is not None: A__ = dict_scores[:top_k] return dict_scores
87
0
"""simple docstring""" from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case : def __init__( self : Tuple , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any]=3 , UpperCamelCase__ : Optional[Any]=3_2 , UpperCamelCase__ : Union[str, Any]=3 , UpperCamelCase__ : List[Any]=1_0 , UpperCamelCase__ : int=[1_0, 2_0, 3_0, 4_0] , UpperCamelCase__ : str=[1, 1, 2, 1] , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Any=True , UpperCamelCase__ : List[str]="relu" , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : Tuple=None , )-> List[Any]: '''simple docstring''' __lowerCAmelCase: Optional[Any] = parent __lowerCAmelCase: List[Any] = batch_size __lowerCAmelCase: int = image_size __lowerCAmelCase: Union[str, Any] = num_channels __lowerCAmelCase: Any = embeddings_size __lowerCAmelCase: List[Any] = hidden_sizes __lowerCAmelCase: int = depths __lowerCAmelCase: Tuple = is_training __lowerCAmelCase: str = use_labels __lowerCAmelCase: int = hidden_act __lowerCAmelCase: str = num_labels __lowerCAmelCase: Optional[int] = scope __lowerCAmelCase: Union[str, Any] = len(UpperCAmelCase__) def lowercase_ ( self : Union[str, Any])-> Tuple: '''simple docstring''' __lowerCAmelCase: Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __lowerCAmelCase: Optional[int] = None if self.use_labels: __lowerCAmelCase: Tuple = ids_tensor([self.batch_size] , self.num_labels) __lowerCAmelCase: Any = self.get_config() return config, pixel_values, labels def lowercase_ ( self : str)-> Any: '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def lowercase_ ( self : Optional[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any])-> Tuple: '''simple docstring''' __lowerCAmelCase: str = TFRegNetModel(config=UpperCAmelCase__) __lowerCAmelCase: int = model(UpperCAmelCase__ , training=UpperCAmelCase__) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def lowercase_ ( self : Dict , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict)-> Any: '''simple docstring''' __lowerCAmelCase: str = self.num_labels __lowerCAmelCase: Any = TFRegNetForImageClassification(UpperCAmelCase__) __lowerCAmelCase: List[Any] = model(UpperCAmelCase__ , labels=UpperCAmelCase__ , training=UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def lowercase_ ( self : Dict)-> Optional[int]: '''simple docstring''' __lowerCAmelCase: Dict = self.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase: Optional[int] = config_and_inputs __lowerCAmelCase: int = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class snake_case ( UpperCAmelCase__, UpperCAmelCase__, unittest.TestCase ): SCREAMING_SNAKE_CASE_ : str = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () SCREAMING_SNAKE_CASE_ : Optional[Any] = ( {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification} if is_tf_available() else {} ) SCREAMING_SNAKE_CASE_ : List[str] = False SCREAMING_SNAKE_CASE_ : Dict = False SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : Tuple = False SCREAMING_SNAKE_CASE_ : int = False def lowercase_ ( self : List[str])-> Tuple: '''simple docstring''' __lowerCAmelCase: int = TFRegNetModelTester(self) __lowerCAmelCase: Dict = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__) def lowercase_ ( self : List[str])-> Tuple: '''simple docstring''' return @unittest.skip(reason="RegNet does not use inputs_embeds") def lowercase_ ( self : Tuple)-> int: '''simple docstring''' pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , ) @slow def lowercase_ ( self : str)-> str: '''simple docstring''' super().test_keras_fit() @unittest.skip(reason="RegNet does not support input and output embeddings") def lowercase_ ( self : Dict)-> int: '''simple docstring''' pass def lowercase_ ( self : str)-> List[str]: '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase: str = model_class(UpperCAmelCase__) __lowerCAmelCase: List[Any] = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase: int = [*signature.parameters.keys()] __lowerCAmelCase: Optional[Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase__) def lowercase_ ( self : int)-> Tuple: '''simple docstring''' __lowerCAmelCase: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__) def lowercase_ ( self : Optional[Any])-> Dict: '''simple docstring''' def check_hidden_states_output(UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any]): __lowerCAmelCase: str = model_class(UpperCAmelCase__) __lowerCAmelCase: Tuple = model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__) , training=UpperCAmelCase__) __lowerCAmelCase: int = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __lowerCAmelCase: Any = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase__) , expected_num_stages + 1) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) __lowerCAmelCase , __lowerCAmelCase: int = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase: int = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: __lowerCAmelCase: Union[str, Any] = layer_type __lowerCAmelCase: int = True check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __lowerCAmelCase: int = True check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) def lowercase_ ( self : Dict)-> int: '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : Any , UpperCamelCase__ : Dict={}): __lowerCAmelCase: Union[str, Any] = model(UpperCAmelCase__ , return_dict=UpperCAmelCase__ , **UpperCAmelCase__) __lowerCAmelCase: int = model(UpperCAmelCase__ , return_dict=UpperCAmelCase__ , **UpperCAmelCase__).to_tuple() def recursive_check(UpperCamelCase__ : int , UpperCamelCase__ : List[str]): if isinstance(UpperCAmelCase__ , (List, Tuple)): for tuple_iterable_value, dict_iterable_value in zip(UpperCAmelCase__ , UpperCAmelCase__): recursive_check(UpperCAmelCase__ , UpperCAmelCase__) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(UpperCAmelCase__ , UpperCAmelCase__)) , msg=( "Tuple and dict output are not equal. Difference:" f" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}" ) , ) recursive_check(UpperCAmelCase__ , UpperCAmelCase__) for model_class in self.all_model_classes: __lowerCAmelCase: Optional[int] = model_class(UpperCAmelCase__) __lowerCAmelCase: str = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__) __lowerCAmelCase: Optional[Any] = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__) check_equivalence(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) __lowerCAmelCase: Optional[int] = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__) __lowerCAmelCase: int = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__) check_equivalence(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) __lowerCAmelCase: Dict = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__) __lowerCAmelCase: Optional[int] = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__) check_equivalence(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , {"output_hidden_states": True}) __lowerCAmelCase: str = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__) __lowerCAmelCase: Optional[Any] = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__) check_equivalence(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , {"output_hidden_states": True}) def lowercase_ ( self : Optional[int])-> int: '''simple docstring''' __lowerCAmelCase: List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__) @slow def lowercase_ ( self : List[Any])-> List[str]: '''simple docstring''' for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase: Dict = TFRegNetModel.from_pretrained(UpperCAmelCase__) self.assertIsNotNone(UpperCAmelCase__) def a__ ( ) -> Union[str, Any]: __lowerCAmelCase: Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def lowercase_ ( self : Dict)-> List[Any]: '''simple docstring''' return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def lowercase_ ( self : Union[str, Any])-> int: '''simple docstring''' __lowerCAmelCase: int = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) __lowerCAmelCase: Dict = self.default_image_processor __lowerCAmelCase: List[Any] = prepare_img() __lowerCAmelCase: str = image_processor(images=UpperCAmelCase__ , return_tensors="tf") # forward pass __lowerCAmelCase: List[Any] = model(**UpperCAmelCase__ , training=UpperCAmelCase__) # verify the logits __lowerCAmelCase: str = tf.TensorShape((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , UpperCAmelCase__) __lowerCAmelCase: List[Any] = tf.constant([-0.4180, -1.5051, -3.4836]) tf.debugging.assert_near(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1e-4)
346
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase : Any = {"""configuration_xlnet""": ["""XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : int = ["""XLNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : int = ["""XLNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Union[str, Any] = [ """XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLNetForMultipleChoice""", """XLNetForQuestionAnswering""", """XLNetForQuestionAnsweringSimple""", """XLNetForSequenceClassification""", """XLNetForTokenClassification""", """XLNetLMHeadModel""", """XLNetModel""", """XLNetPreTrainedModel""", """load_tf_weights_in_xlnet""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Dict = [ """TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLNetForMultipleChoice""", """TFXLNetForQuestionAnsweringSimple""", """TFXLNetForSequenceClassification""", """TFXLNetForTokenClassification""", """TFXLNetLMHeadModel""", """TFXLNetMainLayer""", """TFXLNetModel""", """TFXLNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys _lowerCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
87
0
"""simple docstring""" import heapq import sys import numpy as np SCREAMING_SNAKE_CASE_ = tuple[int, int] class _UpperCAmelCase : def __init__( self ) -> str: UpperCAmelCase = [] UpperCAmelCase = set() def a_ ( self ) -> List[str]: if not self.empty(): return self.elements[0][0] else: return float('inf' ) def a_ ( self ) -> str: return len(self.elements ) == 0 def a_ ( self , lowercase_ , lowercase_ ) -> List[str]: if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(UpperCAmelCase__ ) else: # update # print("update", item) UpperCAmelCase = [] ((UpperCAmelCase) , (UpperCAmelCase)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((UpperCAmelCase) , (UpperCAmelCase)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def a_ ( self , lowercase_ ) -> Union[str, Any]: if item in self.set: self.set.remove(UpperCAmelCase__ ) UpperCAmelCase = [] ((UpperCAmelCase) , (UpperCAmelCase)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((UpperCAmelCase) , (UpperCAmelCase)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def a_ ( self ) -> List[str]: return self.elements[0][1] def a_ ( self ) -> int: ((UpperCAmelCase) , (UpperCAmelCase)) = heapq.heappop(self.elements ) self.set.remove(UpperCAmelCase__ ) return (priority, item) def lowercase__ ( lowerCAmelCase : Any , lowerCAmelCase : Dict ) -> str: """simple docstring""" UpperCAmelCase = np.array(lowercase_ ) UpperCAmelCase = np.array(lowercase_ ) return np.linalg.norm(a - b ) def lowercase__ ( lowerCAmelCase : Tuple , lowerCAmelCase : str ) -> str: """simple docstring""" return consistent_heuristic(lowercase_ , lowercase_ ) // t def lowercase__ ( lowerCAmelCase : List[str] , lowerCAmelCase : str ) -> Union[str, Any]: """simple docstring""" return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def lowercase__ ( lowerCAmelCase : Any , lowerCAmelCase : Dict , lowerCAmelCase : Tuple , lowerCAmelCase : Optional[int] ) -> Optional[int]: """simple docstring""" UpperCAmelCase = g_function[start] + Wa * heuristics[i](lowercase_ , lowercase_ ) return ans def lowercase__ ( lowerCAmelCase : Optional[int] , lowerCAmelCase : Any , lowerCAmelCase : Any ) -> str: """simple docstring""" UpperCAmelCase = np.chararray((n, n) ) for i in range(lowercase_ ): for j in range(lowercase_ ): UpperCAmelCase = '*' for i in range(lowercase_ ): for j in range(lowercase_ ): if (j, (n - 1) - i) in blocks: UpperCAmelCase = '#' UpperCAmelCase = '-' UpperCAmelCase = back_pointer[goal] while x != start: ((UpperCAmelCase) , (UpperCAmelCase)) = x # print(x) UpperCAmelCase = '-' UpperCAmelCase = back_pointer[x] UpperCAmelCase = '-' for i in range(lowercase_ ): for j in range(lowercase_ ): if (i, j) == (0, n - 1): print(grid[i][j] , end=' ' ) print('<-- End position' , end=' ' ) else: print(grid[i][j] , end=' ' ) print() print('^' ) print('Start position' ) print() print('# is an obstacle' ) print('- is the path taken by algorithm' ) print('PATH TAKEN BY THE ALGORITHM IS:-' ) UpperCAmelCase = back_pointer[goal] while x != start: print(lowercase_ , end=' ' ) UpperCAmelCase = back_pointer[x] print(lowercase_ ) sys.exit() def lowercase__ ( lowerCAmelCase : Union[str, Any] ) -> Dict: """simple docstring""" if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def lowercase__ ( lowerCAmelCase : Tuple , lowerCAmelCase : List[str] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Dict , lowerCAmelCase : Optional[Any] , ) -> Union[str, Any]: """simple docstring""" for itera in range(lowercase_ ): open_list[itera].remove_element(lowercase_ ) # print("s", s) # print("j", j) ((UpperCAmelCase) , (UpperCAmelCase)) = s UpperCAmelCase = (x - 1, y) UpperCAmelCase = (x + 1, y) UpperCAmelCase = (x, y + 1) UpperCAmelCase = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(lowercase_ ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(lowercase_ ) UpperCAmelCase = -1 UpperCAmelCase = float('inf' ) if valid(lowercase_ ) and g_function[neighbours] > g_function[s] + 1: UpperCAmelCase = g_function[s] + 1 UpperCAmelCase = s if neighbours not in close_list_anchor: open_list[0].put(lowercase_ , key(lowercase_ , 0 , lowercase_ , lowercase_ ) ) if neighbours not in close_list_inad: for var in range(1 , lowercase_ ): if key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) <= Wa * key( lowercase_ , 0 , lowercase_ , lowercase_ ): open_list[j].put( lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) def lowercase__ ( ) -> Optional[int]: """simple docstring""" UpperCAmelCase = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list SCREAMING_SNAKE_CASE_ = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} SCREAMING_SNAKE_CASE_ = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] SCREAMING_SNAKE_CASE_ = make_common_ground() SCREAMING_SNAKE_CASE_ = blocks_blk # hyper parameters SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = 20 SCREAMING_SNAKE_CASE_ = 3 # one consistent and two other inconsistent # start and end destination SCREAMING_SNAKE_CASE_ = (0, 0) SCREAMING_SNAKE_CASE_ = (n - 1, n - 1) SCREAMING_SNAKE_CASE_ = 1 def lowercase__ ( lowerCAmelCase : int , lowerCAmelCase : Tuple , lowerCAmelCase : Tuple ) -> str: """simple docstring""" UpperCAmelCase = {start: 0, goal: float('inf' )} UpperCAmelCase = {start: -1, goal: -1} UpperCAmelCase = [] UpperCAmelCase = set() for i in range(lowercase_ ): open_list.append(PriorityQueue() ) open_list[i].put(lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) UpperCAmelCase = [] UpperCAmelCase = [] while open_list[0].minkey() < float('inf' ): for i in range(1 , lowercase_ ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float('inf' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: UpperCAmelCase , UpperCAmelCase = open_list[i].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_inad.append(lowercase_ ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('inf' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: UpperCAmelCase = open_list[0].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , 0 , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_anchor.append(lowercase_ ) print('No path found to goal' ) print() for i in range(n - 1 , -1 , -1 ): for j in range(lowercase_ ): if (j, i) in blocks: print('#' , end=' ' ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print('*' , end=' ' ) else: print('-' , end=' ' ) else: print('*' , end=' ' ) if (j, i) == (n - 1, n - 1): print('<-- End position' , end=' ' ) print() print('^' ) print('Start position' ) print() print('# is an obstacle' ) print('- is the path taken by algorithm' ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
373
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 : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : Union[str, Any] = { """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""", """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''mobilenet_v1''' def __init__( self : Optional[int] , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : Optional[Any]=224 , UpperCAmelCase__ : Optional[int]=1.0 , UpperCAmelCase__ : Optional[int]=8 , UpperCAmelCase__ : Tuple="relu6" , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Dict=0.999 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : Optional[int]=0.001 , **UpperCAmelCase__ : Dict , ) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase__) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''') A__ = num_channels A__ = image_size A__ = depth_multiplier A__ = min_depth A__ = hidden_act A__ = tf_padding A__ = classifier_dropout_prob A__ = initializer_range A__ = layer_norm_eps class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = version.parse('''1.11''' ) @property def SCREAMING_SNAKE_CASE ( self : Any) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict([('''pixel_values''', {0: '''batch'''})]) @property def SCREAMING_SNAKE_CASE ( self : List[str]) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})]) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})]) @property def SCREAMING_SNAKE_CASE ( self : int) ->float: '''simple docstring''' return 1e-4
87
0
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": lowercase : str = pd.read_csv("sample_data.csv", header=None) lowercase : List[Any] = df.shape[:1][0] # If you're using some other dataset input the target column lowercase : Tuple = df.iloc[:, 1:2] lowercase : Optional[Any] = actual_data.values.reshape(len_data, 1) lowercase : List[str] = MinMaxScaler().fit_transform(actual_data) lowercase : str = 10 lowercase : Optional[int] = 5 lowercase : Any = 20 lowercase : Optional[int] = len_data - periods * look_back lowercase : Optional[Any] = actual_data[:division] lowercase : Optional[Any] = actual_data[division - look_back :] lowercase : Optional[int] = [], [] lowercase : List[Any] = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) lowercase : Optional[int] = np.array(train_x) lowercase : str = np.array(test_x) lowercase : Tuple = np.array([list(i.ravel()) for i in train_y]) lowercase : Tuple = np.array([list(i.ravel()) for i in test_y]) lowercase : Any = Sequential() model.add(LSTM(1_28, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(1_28, 1))) model.add(Dense(forward_days)) model.compile(loss="mean_squared_error", optimizer="adam") lowercase : int = model.fit( x_train, y_train, epochs=1_50, verbose=1, shuffle=True, batch_size=4 ) lowercase : Optional[int] = model.predict(x_test)
542
import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase : Dict = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_sentencepiece_available(): import sentencepiece as sp _lowerCamelCase : str = 5 _lowerCamelCase : int = 10 @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = SpeechaTextTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = True def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' super().setUp() A__ = sp.SentencePieceProcessor() spm_model.Load(UpperCAmelCase__) A__ = ['''<s>''', '''<pad>''', '''</s>''', '''<unk>'''] vocab += [spm_model.IdToPiece(id_) for id_ in range(len(UpperCAmelCase__))] A__ = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__)))) A__ = Path(self.tmpdirname) save_json(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''vocab_file''']) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''spm_file''']) A__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' A__ = '''<pad>''' A__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__) , UpperCAmelCase__) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__) , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<s>''') self.assertEqual(vocab_keys[1] , '''<pad>''') self.assertEqual(vocab_keys[-1] , '''j''') self.assertEqual(len(UpperCAmelCase__) , 1_001) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[str]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_001) def SCREAMING_SNAKE_CASE ( self : int) ->List[str]: '''simple docstring''' A__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname) A__ = tokenizer.tokenize('''This is a test''') self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__) , [289, 50, 14, 174, 386] , ) A__ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( UpperCAmelCase__ , [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''', '''é''', '''.'''] , ) A__ = tokenizer.convert_tokens_to_ids(UpperCAmelCase__) self.assertListEqual(UpperCAmelCase__ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8]) A__ = tokenizer.convert_ids_to_tokens(UpperCAmelCase__) self.assertListEqual( UpperCAmelCase__ , [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>''', '''.'''] , ) @slow def SCREAMING_SNAKE_CASE ( self : int) ->List[Any]: '''simple docstring''' A__ = {'''input_ids''': [[3_791, 797, 31, 11, 64, 797, 31, 2_429, 433, 12, 1_176, 12, 20, 786, 915, 142, 2_413, 240, 37, 3_238, 797, 31, 11, 35, 93, 915, 142, 2_413, 240, 37, 5_540, 567, 1_276, 93, 37, 610, 40, 62, 455, 657, 1_042, 123, 780, 177, 37, 309, 241, 1_298, 514, 20, 292, 2_737, 114, 2_469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3_388, 511, 459, 4, 3_555, 40, 321, 302, 705, 4, 3_388, 511, 583, 326, 5, 5, 5, 62, 3_310, 560, 177, 2_680, 217, 1_508, 32, 31, 853, 418, 64, 583, 511, 1_605, 62, 35, 93, 560, 177, 2_680, 217, 1_508, 1_521, 64, 583, 511, 519, 62, 20, 1_515, 764, 20, 149, 261, 5_625, 7_972, 20, 5_540, 567, 1_276, 93, 3_925, 1_675, 11, 15, 802, 7_972, 576, 217, 1_508, 11, 35, 93, 1_253, 2_441, 15, 289, 652, 31, 416, 321, 3_842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2_681, 1_153, 3_434, 20, 5_540, 37, 567, 126, 1_253, 2_441, 3_376, 449, 210, 431, 1_563, 177, 767, 5_540, 11, 1_203, 472, 11, 2_953, 685, 285, 364, 706, 1_153, 20, 6_799, 20, 2_869, 20, 4_464, 126, 40, 2_429, 20, 1_040, 866, 2_664, 418, 20, 318, 20, 1_726, 186, 20, 265, 522, 35, 93, 2_191, 4_634, 20, 1_040, 12, 6_799, 15, 228, 2_356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2_575, 2_666, 684, 1_582, 1_176, 12, 627, 149, 619, 20, 4_902, 563, 11, 20, 149, 261, 3_420, 2_356, 174, 142, 4_714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''facebook/s2t-small-mustc-en-de-st''' , revision='''a14f04cf0776c02f62a8cb800cf7909e15ea23ad''' , ) @require_sentencepiece class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = '''valhalla/s2t_mustc_multilinguial_medium''' UpperCAmelCase__ = '''C\'est trop cool''' UpperCAmelCase__ = '''Esto es genial''' @classmethod def SCREAMING_SNAKE_CASE ( cls : Dict) ->Dict: '''simple docstring''' A__ = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name) return cls def SCREAMING_SNAKE_CASE ( self : str) ->Dict: '''simple docstring''' self.assertEqual(self.tokenizer.lang_code_to_id['''pt'''] , 4) self.assertEqual(self.tokenizer.lang_code_to_id['''ru'''] , 6) self.assertEqual(self.tokenizer.lang_code_to_id['''it'''] , 9) self.assertEqual(self.tokenizer.lang_code_to_id['''de'''] , 11) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Dict: '''simple docstring''' self.assertEqual(self.tokenizer.vocab_size , 10_000) def SCREAMING_SNAKE_CASE ( self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertIn(UpperCAmelCase__ , self.tokenizer.all_special_ids) A__ = [ES_CODE, 4, 1_601, 47, 7_647, 2] A__ = self.tokenizer.decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__) A__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCAmelCase__) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__) self.assertNotIn(self.tokenizer.eos_token , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->str: '''simple docstring''' A__ = '''fr''' A__ = self.tokenizer(self.french_text).input_ids self.assertEqual(encoded[0] , UpperCAmelCase__) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->int: '''simple docstring''' A__ = '''fr''' self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE]) A__ = '''es''' self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE])
87
0
'''simple docstring''' from manim import * class SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): '''simple docstring''' def __UpperCAmelCase ( self : List[str] ): """simple docstring""" _snake_case : Any = Rectangle(height=0.5 , width=0.5 ) _snake_case : int = Rectangle(height=0.25 , width=0.25 ) _snake_case : Dict = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) _snake_case : Optional[Any] = [mem.copy() for i in range(6 )] _snake_case : List[Any] = [mem.copy() for i in range(6 )] _snake_case : Any = VGroup(*UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0 ) _snake_case : str = VGroup(*UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0 ) _snake_case : Optional[int] = VGroup(UpperCAmelCase__ , UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0 ) _snake_case : int = Text('CPU' , font_size=24 ) _snake_case : List[Any] = Group(UpperCAmelCase__ , UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0.5 , aligned_edge=UpperCAmelCase__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(UpperCAmelCase__ ) _snake_case : str = [mem.copy() for i in range(4 )] _snake_case : Any = VGroup(*UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0 ) _snake_case : int = Text('GPU' , font_size=24 ) _snake_case : Dict = Group(UpperCAmelCase__ , UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0.5 , aligned_edge=UpperCAmelCase__ ) gpu.move_to([-1, -1, 0] ) self.add(UpperCAmelCase__ ) _snake_case : List[str] = [mem.copy() for i in range(6 )] _snake_case : str = VGroup(*UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0 ) _snake_case : str = Text('Model' , font_size=24 ) _snake_case : Optional[Any] = Group(UpperCAmelCase__ , UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0.5 , aligned_edge=UpperCAmelCase__ ) model.move_to([3, -1.0, 0] ) self.add(UpperCAmelCase__ ) _snake_case : Any = [] _snake_case : List[str] = [] _snake_case : Optional[Any] = [] for i, rect in enumerate(UpperCAmelCase__ ): rect.set_stroke(UpperCAmelCase__ ) _snake_case : Union[str, Any] = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(UpperCAmelCase__ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=UpperCAmelCase__ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=UpperCAmelCase__ , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=UpperCAmelCase__ , buff=0.0 ) self.add(UpperCAmelCase__ ) model_cpu_arr.append(UpperCAmelCase__ ) self.add(*UpperCAmelCase__ , *UpperCAmelCase__ , *UpperCAmelCase__ ) _snake_case : Tuple = [mem.copy() for i in range(6 )] _snake_case : Union[str, Any] = VGroup(*UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0 ) _snake_case : List[str] = Text('Loaded Checkpoint' , font_size=24 ) _snake_case : int = Group(UpperCAmelCase__ , UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0.5 , aligned_edge=UpperCAmelCase__ ) checkpoint.move_to([3, 0.5, 0] ) self.add(UpperCAmelCase__ ) _snake_case : Union[str, Any] = [] _snake_case : Optional[int] = [] for i, rect in enumerate(UpperCAmelCase__ ): _snake_case : Any = fill.copy().set_fill(UpperCAmelCase__ , opacity=0.7 ) target.move_to(UpperCAmelCase__ ) ckpt_arr.append(UpperCAmelCase__ ) _snake_case : Optional[Any] = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(UpperCAmelCase__ ) self.add(*UpperCAmelCase__ , *UpperCAmelCase__ ) _snake_case : Tuple = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) _snake_case : Optional[int] = MarkupText( F"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(UpperCAmelCase__ , UpperCAmelCase__ ) _snake_case : int = MarkupText( F"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(UpperCAmelCase__ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(UpperCAmelCase__ ) _snake_case : List[str] = MarkupText( F"""Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) _snake_case : str = [meta_mem.copy() for i in range(6 )] _snake_case : List[str] = [meta_mem.copy() for i in range(6 )] _snake_case : Tuple = VGroup(*UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0 ) _snake_case : Any = VGroup(*UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0 ) _snake_case : Any = VGroup(UpperCAmelCase__ , UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0 ) _snake_case : Union[str, Any] = Text('Disk' , font_size=24 ) _snake_case : List[str] = Group(UpperCAmelCase__ , UpperCAmelCase__ ).arrange(UpperCAmelCase__ , buff=0.5 , aligned_edge=UpperCAmelCase__ ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(UpperCAmelCase__ , run_time=3 ) , Write(UpperCAmelCase__ , run_time=1 ) , Create(UpperCAmelCase__ , run_time=1 ) ) _snake_case : str = [] for i, rect in enumerate(UpperCAmelCase__ ): _snake_case : str = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(UpperCAmelCase__ , run_time=1.5 ) ) self.play(*UpperCAmelCase__ ) self.play(FadeOut(UpperCAmelCase__ ) ) _snake_case : Any = MarkupText(F"""Then, the checkpoint is removed from memory\nthrough garbage collection.""" , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(UpperCAmelCase__ , run_time=3 ) ) self.play( FadeOut(UpperCAmelCase__ , UpperCAmelCase__ , *UpperCAmelCase__ , *UpperCAmelCase__ ) , ) self.wait()
517
from __future__ import annotations import requests def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" A__ = f"""https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty""" return requests.get(lowercase_ ).json() def SCREAMING_SNAKE_CASE ( lowercase_ = 10 ) -> list[dict]: """simple docstring""" A__ = '''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty''' A__ = requests.get(lowercase_ ).json()[:max_stories] return [get_hackernews_story(lowercase_ ) for story_id in story_ids] def SCREAMING_SNAKE_CASE ( lowercase_ = 10 ) -> str: """simple docstring""" A__ = hackernews_top_stories(lowercase_ ) return "\n".join('''* [{title}]({url})'''.format(**lowercase_ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
87
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowerCAmelCase = { """configuration_mobilevit""": ["""MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MobileViTConfig""", """MobileViTOnnxConfig"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = ["""MobileViTFeatureExtractor"""] _lowerCAmelCase = ["""MobileViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ """MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """MobileViTForImageClassification""", """MobileViTForSemanticSegmentation""", """MobileViTModel""", """MobileViTPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ """TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFMobileViTForImageClassification""", """TFMobileViTForSemanticSegmentation""", """TFMobileViTModel""", """TFMobileViTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
432
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType _lowerCamelCase : Optional[List[str]] = None _lowerCamelCase : int = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image _lowerCamelCase : Union[str, Any] = [ np.dtype("""|b1"""), np.dtype("""|u1"""), np.dtype("""<u2"""), np.dtype(""">u2"""), np.dtype("""<i2"""), np.dtype(""">i2"""), np.dtype("""<u4"""), np.dtype(""">u4"""), np.dtype("""<i4"""), np.dtype(""">i4"""), np.dtype("""<f4"""), np.dtype(""">f4"""), np.dtype("""<f8"""), np.dtype(""">f8"""), ] @dataclass class UpperCamelCase_ : '''simple docstring''' UpperCAmelCase__ = True UpperCAmelCase__ = None # Automatically constructed UpperCAmelCase__ = "PIL.Image.Image" UpperCAmelCase__ = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) UpperCAmelCase__ = field(default='''Image''' , init=UpperCAmelCase__ , repr=UpperCAmelCase__ ) def __call__( self : List[str]) ->List[str]: '''simple docstring''' return self.pa_type def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"]) ->dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''') if isinstance(UpperCAmelCase__ , UpperCAmelCase__): A__ = np.array(UpperCAmelCase__) if isinstance(UpperCAmelCase__ , UpperCAmelCase__): return {"path": value, "bytes": None} elif isinstance(UpperCAmelCase__ , UpperCAmelCase__): return {"path": None, "bytes": value} elif isinstance(UpperCAmelCase__ , np.ndarray): # convert the image array to PNG/TIFF bytes return encode_np_array(UpperCAmelCase__) elif isinstance(UpperCAmelCase__ , PIL.Image.Image): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(UpperCAmelCase__) 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 return {"bytes": None, "path": value.get('''path''')} elif value.get('''bytes''') is not None or value.get('''path''') is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get('''bytes'''), "path": value.get('''path''')} else: raise ValueError( f"""An image sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""") def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : dict , UpperCAmelCase__ : str=None) ->"PIL.Image.Image": '''simple docstring''' if not self.decode: raise RuntimeError('''Decoding is disabled for this feature. Please use Image(decode=True) instead.''') if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support decoding images, please install \'Pillow\'.''') if token_per_repo_id is None: A__ = {} A__ , A__ = value['''path'''], value['''bytes'''] if bytes_ is None: if path is None: raise ValueError(f"""An image should have one of 'path' or 'bytes' but both are None in {value}.""") else: if is_local_path(UpperCAmelCase__): A__ = PIL.Image.open(UpperCAmelCase__) else: A__ = path.split('''::''')[-1] try: A__ = string_to_dict(UpperCAmelCase__ , config.HUB_DATASETS_URL)['''repo_id'''] A__ = token_per_repo_id.get(UpperCAmelCase__) except ValueError: A__ = None with xopen(UpperCAmelCase__ , '''rb''' , use_auth_token=UpperCAmelCase__) as f: A__ = BytesIO(f.read()) A__ = PIL.Image.open(bytes_) else: A__ = PIL.Image.open(BytesIO(bytes_)) image.load() # to avoid "Too many open files" errors return image def SCREAMING_SNAKE_CASE ( self : Dict) ->Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Value return ( self if self.decode else { "bytes": Value('''binary'''), "path": Value('''string'''), } ) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[pa.StringArray, pa.StructArray, pa.ListArray]) ->pa.StructArray: '''simple docstring''' if pa.types.is_string(storage.type): A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.binary()) A__ = pa.StructArray.from_arrays([bytes_array, storage] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_binary(storage.type): A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays([storage, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_struct(storage.type): if storage.type.get_field_index('''bytes''') >= 0: A__ = storage.field('''bytes''') else: A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.binary()) if storage.type.get_field_index('''path''') >= 0: A__ = storage.field('''path''') else: A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null()) elif pa.types.is_list(storage.type): A__ = pa.array( [encode_np_array(np.array(UpperCAmelCase__))['''bytes'''] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) A__ = pa.array([None] * len(UpperCAmelCase__) , type=pa.string()) A__ = pa.StructArray.from_arrays( [bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null()) return array_cast(UpperCAmelCase__ , self.pa_type) def SCREAMING_SNAKE_CASE ( self : List[Any] , UpperCAmelCase__ : pa.StructArray) ->pa.StructArray: '''simple docstring''' @no_op_if_value_is_null def path_to_bytes(UpperCAmelCase__ : Dict): with xopen(UpperCAmelCase__ , '''rb''') as f: A__ = f.read() return bytes_ A__ = 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() , ) A__ = pa.array( [os.path.basename(UpperCAmelCase__) if path is not None else None for path in storage.field('''path''').to_pylist()] , type=pa.string() , ) A__ = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null()) return array_cast(UpperCAmelCase__ , self.pa_type) def SCREAMING_SNAKE_CASE ( ) -> List[str]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() A__ = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def SCREAMING_SNAKE_CASE ( lowercase_ ) -> bytes: """simple docstring""" A__ = BytesIO() if image.format in list_image_compression_formats(): A__ = image.format else: A__ = '''PNG''' if image.mode in ['''1''', '''L''', '''LA''', '''RGB''', '''RGBA'''] else '''TIFF''' image.save(lowercase_ , format=lowercase_ ) return buffer.getvalue() def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" if hasattr(lowercase_ , '''filename''' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(lowercase_ )} def SCREAMING_SNAKE_CASE ( lowercase_ ) -> dict: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) A__ = array.dtype A__ = dtype.byteorder if dtype.byteorder != '''=''' else _NATIVE_BYTEORDER A__ = dtype.kind A__ = dtype.itemsize A__ = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: A__ = np.dtype('''|u1''' ) if dtype_kind not in ["u", "i"]: raise TypeError( f"""Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.""" ) if dtype is not dest_dtype: warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: A__ = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: A__ = dtype_byteorder + dtype_kind + str(lowercase_ ) A__ = np.dtype(lowercase_ ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f"""Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}""" ) A__ = PIL.Image.fromarray(array.astype(lowercase_ ) ) return {"path": None, "bytes": image_to_bytes(lowercase_ )} def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[dict]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) if objs: A__ , A__ = first_non_null_value(lowercase_ ) if isinstance(lowercase_ , lowercase_ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(lowercase_ , np.ndarray ): A__ = no_op_if_value_is_null(lowercase_ ) return [obj_to_image_dict_func(lowercase_ ) for obj in objs] elif isinstance(lowercase_ , PIL.Image.Image ): A__ = no_op_if_value_is_null(lowercase_ ) return [obj_to_image_dict_func(lowercase_ ) for obj in objs] else: return objs else: return objs
87
0
'''simple docstring''' import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() _SCREAMING_SNAKE_CASE : Optional[Any] = [ """word_embeddings_layernorm.weight""", """word_embeddings_layernorm.bias""", """input_layernorm.weight""", """input_layernorm.bias""", """post_attention_layernorm.weight""", """post_attention_layernorm.bias""", """self_attention.dense.bias""", """mlp.dense_4h_to_h.bias""", """ln_f.weight""", """ln_f.bias""", ] _SCREAMING_SNAKE_CASE : int = [ """mlp.dense_4h_to_h.weight""", """self_attention.dense.weight""", ] def UpperCamelCase_( snake_case : Optional[Any] , snake_case : Union[str, Any] ): '''simple docstring''' snake_case_ = { "word_embeddings.weight": "word_embeddings.weight", "word_embeddings.norm.weight": "word_embeddings_layernorm.weight", "word_embeddings.norm.bias": "word_embeddings_layernorm.bias", "weight": "ln_f.weight", "bias": "ln_f.bias", } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks snake_case_ = int(re.match(r".*layer_(\d*).*" , lowercase_ )[1] ) layer_number -= 3 return f'h.{layer_number}.' + key def UpperCamelCase_( snake_case : List[str] ): '''simple docstring''' if dtype == torch.bool: return 1 / 8 snake_case_ = re.search(r"[^\d](\d+)$" , str(lowercase_ ) ) if bit_search is None: raise ValueError(f'`dtype` is not a valid dtype: {dtype}.' ) snake_case_ = int(bit_search.groups()[0] ) return bit_size // 8 def UpperCamelCase_( snake_case : str , snake_case : Optional[Any] , snake_case : Dict , snake_case : Union[str, Any] , snake_case : Optional[Any] ): '''simple docstring''' if bloom_config_file == "": snake_case_ = BloomConfig() else: snake_case_ = BloomConfig.from_json_file(lowercase_ ) if shard_model: snake_case_ = os.listdir(lowercase_ ) snake_case_ = sorted(filter(lambda snake_case : s.startswith("layer" ) and "model_00" in s , lowercase_ ) ) snake_case_ = {"weight_map": {}, "metadata": {}} snake_case_ = 0 snake_case_ = None snake_case_ = BloomConfig() for j, file in enumerate(lowercase_ ): print("Processing file: {}".format(lowercase_ ) ) snake_case_ = None for i in range(lowercase_ ): # load all TP files snake_case_ = file.replace("model_00" , f'model_0{i}' ) snake_case_ = torch.load(os.path.join(lowercase_ , lowercase_ ) , map_location="cpu" ) # Rename keys in the transformers names snake_case_ = list(temp.keys() ) for key in keys: snake_case_ = temp.pop(lowercase_ ) if tensors is None: snake_case_ = temp else: for key in tensors.keys(): if any(key.endswith(lowercase_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel snake_case_ = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks snake_case_ = torch.cat([tensors[key], temp[key]] , dim=lowercase_ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(lowercase_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): snake_case_ = tensors[key] / pretraining_tp torch.save( lowercase_ , os.path.join( lowercase_ , "pytorch_model_{}-of-{}.bin".format(str(j + 1 ).zfill(5 ) , str(len(lowercase_ ) ).zfill(5 ) ) , ) , ) for key in tensors.keys(): snake_case_ = tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: snake_case_ = "pytorch_model_{}-of-{}.bin".format( str(j + 1 ).zfill(5 ) , str(len(lowercase_ ) ).zfill(5 ) ) snake_case_ = BloomConfig() snake_case_ = pytorch_dump_folder_path + "/" + CONFIG_NAME snake_case_ = total_size with open(lowercase_ , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) with open(os.path.join(lowercase_ , WEIGHTS_NAME + ".index.json" ) , "w" , encoding="utf-8" ) as f: snake_case_ = json.dumps(lowercase_ , indent=2 , sort_keys=lowercase_ ) + "\n" f.write(lowercase_ ) else: snake_case_ = BloomModel(lowercase_ ) snake_case_ = os.listdir(lowercase_ ) snake_case_ = sorted(filter(lambda snake_case : s.startswith("layer" ) and "model_00" in s , lowercase_ ) ) snake_case_ = None for i, file in enumerate(lowercase_ ): snake_case_ = None for i in range(lowercase_ ): # load all TP files snake_case_ = file.replace("model_00" , f'model_0{i}' ) snake_case_ = torch.load(os.path.join(lowercase_ , lowercase_ ) , map_location="cpu" ) # Rename keys in the transformers names snake_case_ = list(temp.keys() ) for key in keys: snake_case_ = temp.pop(lowercase_ ) if tensors is None: snake_case_ = temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(lowercase_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel snake_case_ = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks snake_case_ = torch.cat([tensors[key], temp[key]] , dim=lowercase_ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(lowercase_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): snake_case_ = tensors[key] / pretraining_tp snake_case_ = model.load_state_dict(lowercase_ , strict=lowercase_ ) assert not other_keys.unexpected_keys, f'The keys {other_keys.unexpected_keys} are unexpected' if missing_keys is None: snake_case_ = set(other_keys.missing_keys ) else: snake_case_ = missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, f'The keys {missing_keys} are missing' # Save pytorch-model os.makedirs(lowercase_ , exist_ok=lowercase_ ) snake_case_ = pytorch_dump_folder_path + "/" + WEIGHTS_NAME snake_case_ = pytorch_dump_folder_path + "/" + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}' ) if config.torch_dtype is not None: snake_case_ = model.to(config.torch_dtype ) torch.save(model.state_dict() , lowercase_ ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(lowercase_ , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--bloom_checkpoint_path", default=None, type=str, required=True, help="Path to the Megatron-LM 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( "--bloom_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--shard_model", action="store_true", help="An optional setting to shard the output model \nThis enables sharding the converted checkpoint", ) parser.add_argument( "--pretraining_tp", default=4, type=int, help="Pretraining TP rank that has been used when training the model in Megatron-LM \n", ) _SCREAMING_SNAKE_CASE : Any = parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
400
from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) UpperCAmelCase__ = ( { '''feature-extraction''': TFMobileBertModel, '''fill-mask''': TFMobileBertForMaskedLM, '''question-answering''': TFMobileBertForQuestionAnswering, '''text-classification''': TFMobileBertForSequenceClassification, '''token-classification''': TFMobileBertForTokenClassification, '''zero-shot''': TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase__ = False UpperCAmelCase__ = False def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str=False) ->Optional[Any]: '''simple docstring''' A__ = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__) if return_labels: if model_class in get_values(UpperCAmelCase__): A__ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa) return inputs_dict class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int=13 , UpperCAmelCase__ : str=7 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=99 , UpperCAmelCase__ : List[str]=32 , UpperCAmelCase__ : Optional[int]=32 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Optional[Any]=37 , UpperCAmelCase__ : Optional[int]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : List[Any]=512 , UpperCAmelCase__ : Tuple=16 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : Dict=0.02 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Tuple=None , ) ->Any: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = use_token_type_ids A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = type_vocab_size A__ = type_sequence_label_size A__ = initializer_range A__ = num_labels A__ = num_choices A__ = scope A__ = embedding_size def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Tuple: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) A__ = None if self.use_token_type_ids: A__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) A__ = None A__ = None A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size] , self.type_sequence_label_size) A__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) A__ = ids_tensor([self.batch_size] , self.num_choices) A__ = MobileBertConfig( 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 , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any]) ->Any: '''simple docstring''' A__ = TFMobileBertModel(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) A__ = [input_ids, input_mask] A__ = model(UpperCAmelCase__) A__ = model(UpperCAmelCase__) 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 SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Tuple) ->Optional[Any]: '''simple docstring''' A__ = TFMobileBertForMaskedLM(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any]) ->int: '''simple docstring''' A__ = TFMobileBertForNextSentencePrediction(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int) ->List[Any]: '''simple docstring''' A__ = TFMobileBertForPreTraining(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) 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 SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple) ->Dict: '''simple docstring''' A__ = self.num_labels A__ = TFMobileBertForSequenceClassification(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int) ->Dict: '''simple docstring''' A__ = self.num_choices A__ = TFMobileBertForMultipleChoice(config=UpperCAmelCase__) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1) , (1, self.num_choices, 1)) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1) , (1, self.num_choices, 1)) A__ = tf.tile(tf.expand_dims(UpperCAmelCase__ , 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(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int]) ->int: '''simple docstring''' A__ = self.num_labels A__ = TFMobileBertForTokenClassification(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any]) ->Union[str, Any]: '''simple docstring''' A__ = TFMobileBertForQuestionAnswering(config=UpperCAmelCase__) A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def SCREAMING_SNAKE_CASE ( self : Any) ->str: '''simple docstring''' A__ = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = config_and_inputs A__ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE ( self : Any) ->Union[str, Any]: '''simple docstring''' A__ = TFMobileBertModelTest.TFMobileBertModelTester(self) A__ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Dict: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[str]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*UpperCAmelCase__) @slow def SCREAMING_SNAKE_CASE ( self : str) ->List[Any]: '''simple docstring''' for model_name in ["google/mobilebert-uncased"]: A__ = TFMobileBertModel.from_pretrained(UpperCAmelCase__) self.assertIsNotNone(UpperCAmelCase__) @require_tf class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Any: '''simple docstring''' A__ = TFMobileBertForPreTraining.from_pretrained('''google/mobilebert-uncased''') A__ = tf.constant([[0, 1, 2, 3, 4, 5]]) A__ = model(UpperCAmelCase__)[0] A__ = [1, 6, 30_522] self.assertEqual(output.shape , UpperCAmelCase__) A__ = tf.constant( [ [ [-4.5919547, -9.248295, -9.645256], [-6.7306175, -6.440284, -6.6052837], [-7.2743506, -6.7847915, -6.024673], ] ]) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4)
87
0
'''simple docstring''' class A_ : # Public class to implement a graph '''simple docstring''' def __init__( self , A_ , A_ , A_ ): _UpperCamelCase = row _UpperCamelCase = col _UpperCamelCase = graph def a ( self , A_ , A_ , A_ ): return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def a ( self , A_ , A_ , A_ ): _UpperCamelCase = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order _UpperCamelCase = [-1, 0, 1, -1, 1, -1, 0, 1] _UpperCamelCase = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__ ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__ ) def a ( self ): # And finally, count all islands. _UpperCamelCase = [[False for j in range(self.COL )] for i in range(self.ROW )] _UpperCamelCase = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) count += 1 return count
138
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int=13 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : str=224 , UpperCAmelCase__ : str=30 , UpperCAmelCase__ : Tuple=400 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Union[str, Any]=[0.5, 0.5, 0.5] , UpperCAmelCase__ : Tuple=[0.5, 0.5, 0.5] , ) ->str: '''simple docstring''' A__ = size if size is not None else {'''height''': 18, '''width''': 18} A__ = parent A__ = batch_size A__ = num_channels A__ = image_size A__ = min_resolution A__ = max_resolution A__ = do_resize A__ = size A__ = do_normalize A__ = image_mean A__ = image_std def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]: '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = ViTImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE ( self : List[str]) ->str: '''simple docstring''' A__ = EfficientFormerImageProcessorTester(self) @property def SCREAMING_SNAKE_CASE ( self : Dict) ->int: '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Dict: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_mean''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_std''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_normalize''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize''')) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''')) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Dict: '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self : str) ->Optional[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random PIL images A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors A__ = prepare_image_inputs(self.image_proc_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , torch.Tensor) # Test not batched input A__ = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
87
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __magic_name__: Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__: Union[str, Any] = ["""BartphoTokenizer"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys __magic_name__: int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
324
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance _lowerCamelCase : Dict = 6_378_137.0 _lowerCamelCase : Union[str, Any] = 6_356_752.314_245 _lowerCamelCase : List[Any] = 6378137 def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> float: """simple docstring""" A__ = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude A__ = atan((1 - flattening) * tan(radians(lowercase_ ) ) ) A__ = atan((1 - flattening) * tan(radians(lowercase_ ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius A__ = haversine_distance(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) / EQUATORIAL_RADIUS # Intermediate P and Q values A__ = (b_lata + b_lata) / 2 A__ = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) A__ = (sin(lowercase_ ) ** 2) * (cos(lowercase_ ) ** 2) A__ = cos(sigma / 2 ) ** 2 A__ = (sigma - sin(lowercase_ )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) A__ = (cos(lowercase_ ) ** 2) * (sin(lowercase_ ) ** 2) A__ = sin(sigma / 2 ) ** 2 A__ = (sigma + sin(lowercase_ )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
87
0
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging A : Dict = logging.get_logger(__name__) A : Union[str, Any] = { """vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", } A : Tuple = { """vocab_file""": {"""ctrl""": """https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"""}, """merges_file""": {"""ctrl""": """https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"""}, } A : Optional[int] = { """ctrl""": 2_56, } A : Tuple = { """Pregnancy""": 16_86_29, """Christianity""": 76_75, """Explain""": 10_64_23, """Fitness""": 6_34_40, """Saving""": 6_31_63, """Ask""": 2_71_71, """Ass""": 9_59_85, """Joke""": 16_35_09, """Questions""": 4_56_22, """Thoughts""": 4_96_05, """Retail""": 5_23_42, """Feminism""": 16_43_38, """Writing""": 1_19_92, """Atheism""": 19_22_63, """Netflix""": 4_86_16, """Computing""": 3_96_39, """Opinion""": 4_32_13, """Alone""": 4_49_67, """Funny""": 5_89_17, """Gaming""": 4_03_58, """Human""": 40_88, """India""": 13_31, """Joker""": 7_71_38, """Diet""": 3_62_06, """Legal""": 1_18_59, """Norman""": 49_39, """Tip""": 7_26_89, """Weight""": 5_23_43, """Movies""": 4_62_73, """Running""": 2_34_25, """Science""": 20_90, """Horror""": 3_77_93, """Confession""": 6_05_72, """Finance""": 1_22_50, """Politics""": 1_63_60, """Scary""": 19_19_85, """Support""": 1_26_54, """Technologies""": 3_25_16, """Teenage""": 6_61_60, """Event""": 3_27_69, """Learned""": 6_74_60, """Notion""": 18_27_70, """Wikipedia""": 3_75_83, """Books""": 66_65, """Extract""": 7_60_50, """Confessions""": 10_27_01, """Conspiracy""": 7_59_32, """Links""": 6_36_74, """Narcissus""": 15_04_25, """Relationship""": 5_47_66, """Relationships""": 13_47_96, """Reviews""": 4_16_71, """News""": 42_56, """Translation""": 2_68_20, """multilingual""": 12_84_06, } def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = set() SCREAMING_SNAKE_CASE_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE_ = char SCREAMING_SNAKE_CASE_ = set(lowercase_ ) return pairs class lowerCamelCase (UpperCAmelCase__ ): """simple docstring""" lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = CONTROL_CODES def __init__( self : Optional[int] , __magic_name__ : Union[str, Any] , __magic_name__ : str , __magic_name__ : Union[str, Any]="<unk>" , **__magic_name__ : Any ) -> Dict: super().__init__(unk_token=UpperCAmelCase__ , **UpperCAmelCase__ ) with open(UpperCAmelCase__ , encoding="utf-8" ) as vocab_handle: SCREAMING_SNAKE_CASE_ = json.load(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.encoder.items()} with open(UpperCAmelCase__ , encoding="utf-8" ) as merges_handle: SCREAMING_SNAKE_CASE_ = merges_handle.read().split("\n" )[1:-1] SCREAMING_SNAKE_CASE_ = [tuple(merge.split() ) for merge in merges] SCREAMING_SNAKE_CASE_ = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) SCREAMING_SNAKE_CASE_ = {} @property def __A ( self : str ) -> Tuple: return len(self.encoder ) def __A ( self : str ) -> Tuple: return dict(self.encoder , **self.added_tokens_encoder ) def __A ( self : Dict , __magic_name__ : str ) -> Any: if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE_ = tuple(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = tuple(list(word[:-1] ) + [word[-1] + "</w>"] ) SCREAMING_SNAKE_CASE_ = get_pairs(UpperCAmelCase__ ) if not pairs: return token while True: SCREAMING_SNAKE_CASE_ = min(UpperCAmelCase__ , key=lambda __magic_name__ : self.bpe_ranks.get(UpperCAmelCase__ , float("inf" ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = bigram SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 0 while i < len(UpperCAmelCase__ ): try: SCREAMING_SNAKE_CASE_ = word.index(UpperCAmelCase__ , UpperCAmelCase__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE_ = j if word[i] == first and i < len(UpperCAmelCase__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE_ = tuple(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = new_word if len(UpperCAmelCase__ ) == 1: break else: SCREAMING_SNAKE_CASE_ = get_pairs(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = "@@ ".join(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = word[:-4] SCREAMING_SNAKE_CASE_ = word return word def __A ( self : str , __magic_name__ : Optional[Any] ) -> Any: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = re.findall(r"\S+\n?" , UpperCAmelCase__ ) for token in words: split_tokens.extend(list(self.bpe(UpperCAmelCase__ ).split(" " ) ) ) return split_tokens def __A ( self : Optional[int] , __magic_name__ : Tuple ) -> Dict: return self.encoder.get(UpperCAmelCase__ , self.encoder.get(self.unk_token ) ) def __A ( self : Any , __magic_name__ : Optional[int] ) -> str: return self.decoder.get(UpperCAmelCase__ , self.unk_token ) def __A ( self : Tuple , __magic_name__ : Optional[Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = " ".join(UpperCAmelCase__ ).replace("@@ " , "" ).strip() return out_string def __A ( self : Tuple , __magic_name__ : str , __magic_name__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(UpperCAmelCase__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE_ = os.path.join( UpperCAmelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE_ = os.path.join( UpperCAmelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(UpperCAmelCase__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) + "\n" ) SCREAMING_SNAKE_CASE_ = 0 with open(UpperCAmelCase__ , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __magic_name__ : kv[1] ): if index != token_index: logger.warning( F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' " Please check that the tokenizer is not corrupted!" ) SCREAMING_SNAKE_CASE_ = token_index writer.write(" ".join(UpperCAmelCase__ ) + "\n" ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
140
import heapq import sys import numpy as np _lowerCamelCase : Any = tuple[int, int] class UpperCamelCase_ : '''simple docstring''' def __init__( self : Any) ->str: '''simple docstring''' A__ = [] A__ = set() def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' if not self.empty(): return self.elements[0][0] else: return float('''inf''') def SCREAMING_SNAKE_CASE ( self : Tuple) ->str: '''simple docstring''' return len(self.elements) == 0 def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any]) ->List[str]: '''simple docstring''' if item not in self.set: heapq.heappush(self.elements , (priority, item)) self.set.add(UpperCAmelCase__) else: # update # print("update", item) A__ = [] ((A__) , (A__)) = heapq.heappop(self.elements) while x != item: temp.append((pri, x)) ((A__) , (A__)) = heapq.heappop(self.elements) temp.append((priority, item)) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx)) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : List[Any]) ->Union[str, Any]: '''simple docstring''' if item in self.set: self.set.remove(UpperCAmelCase__) A__ = [] ((A__) , (A__)) = heapq.heappop(self.elements) while x != item: temp.append((pro, x)) ((A__) , (A__)) = heapq.heappop(self.elements) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy)) def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[str]: '''simple docstring''' return self.elements[0][1] def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->int: '''simple docstring''' ((A__) , (A__)) = heapq.heappop(self.elements) self.set.remove(UpperCAmelCase__) return (priority, item) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = np.array(lowercase_ ) A__ = np.array(lowercase_ ) return np.linalg.norm(a - b ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" return consistent_heuristic(lowercase_ , lowercase_ ) // t def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Union[str, Any]: """simple docstring""" return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> Optional[int]: """simple docstring""" A__ = g_function[start] + Wa * heuristics[i](lowercase_ , lowercase_ ) return ans def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = np.chararray((n, n) ) for i in range(lowercase_ ): for j in range(lowercase_ ): A__ = '''*''' for i in range(lowercase_ ): for j in range(lowercase_ ): if (j, (n - 1) - i) in blocks: A__ = '''#''' A__ = '''-''' A__ = back_pointer[goal] while x != start: ((A__) , (A__)) = x # print(x) A__ = '''-''' A__ = back_pointer[x] A__ = '''-''' for i in range(lowercase_ ): for j in range(lowercase_ ): if (i, j) == (0, n - 1): print(grid[i][j] , end=''' ''' ) print('''<-- End position''' , end=''' ''' ) else: print(grid[i][j] , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) print('''PATH TAKEN BY THE ALGORITHM IS:-''' ) A__ = back_pointer[goal] while x != start: print(lowercase_ , end=''' ''' ) A__ = back_pointer[x] print(lowercase_ ) sys.exit() def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) -> Union[str, Any]: """simple docstring""" for itera in range(lowercase_ ): open_list[itera].remove_element(lowercase_ ) # print("s", s) # print("j", j) ((A__) , (A__)) = s A__ = (x - 1, y) A__ = (x + 1, y) A__ = (x, y + 1) A__ = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(lowercase_ ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(lowercase_ ) A__ = -1 A__ = float('''inf''' ) if valid(lowercase_ ) and g_function[neighbours] > g_function[s] + 1: A__ = g_function[s] + 1 A__ = s if neighbours not in close_list_anchor: open_list[0].put(lowercase_ , key(lowercase_ , 0 , lowercase_ , lowercase_ ) ) if neighbours not in close_list_inad: for var in range(1 , lowercase_ ): if key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) <= Wa * key( lowercase_ , 0 , lowercase_ , lowercase_ ): open_list[j].put( lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) def SCREAMING_SNAKE_CASE ( ) -> Optional[int]: """simple docstring""" A__ = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list _lowerCamelCase : Dict = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} _lowerCamelCase : Optional[Any] = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] _lowerCamelCase : Optional[int] = make_common_ground() _lowerCamelCase : Optional[Any] = blocks_blk # hyper parameters _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : List[Any] = 20 _lowerCamelCase : Any = 3 # one consistent and two other inconsistent # start and end destination _lowerCamelCase : str = (0, 0) _lowerCamelCase : Tuple = (n - 1, n - 1) _lowerCamelCase : int = 1 def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = {start: 0, goal: float('''inf''' )} A__ = {start: -1, goal: -1} A__ = [] A__ = set() for i in range(lowercase_ ): open_list.append(PriorityQueue() ) open_list[i].put(lowercase_ , key(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) ) A__ = [] A__ = [] while open_list[0].minkey() < float('''inf''' ): for i in range(1 , lowercase_ ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float('''inf''' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: A__ , A__ = open_list[i].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_inad.append(lowercase_ ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('''inf''' ): do_something(lowercase_ , lowercase_ , lowercase_ ) else: A__ = open_list[0].top_show() visited.add(lowercase_ ) expand_state( lowercase_ , 0 , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) close_list_anchor.append(lowercase_ ) print('''No path found to goal''' ) print() for i in range(n - 1 , -1 , -1 ): for j in range(lowercase_ ): if (j, i) in blocks: print('''#''' , end=''' ''' ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print('''*''' , end=''' ''' ) else: print('''-''' , end=''' ''' ) else: print('''*''' , end=''' ''' ) if (j, i) == (n - 1, n - 1): print('''<-- End position''' , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
87
0
"""simple docstring""" import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm UpperCamelCase__ :Any = re.compile("""[^A-Za-z_0-9]""") # parameters used in DuplicationIndex UpperCamelCase__ :int = 10 UpperCamelCase__ :Dict = 256 def A_ ( snake_case__ ) -> Optional[MinHash]: if len(lowercase_ ) < MIN_NUM_TOKENS: return None _UpperCamelCase :Dict = MinHash(num_perm=lowercase_ ) for token in set(lowercase_ ): min_hash.update(token.encode() ) return min_hash def A_ ( snake_case__ ) -> Set[str]: return {t for t in NON_ALPHA.split(lowercase_ ) if len(t.strip() ) > 0} class A: """simple docstring""" def __init__( self , *, SCREAMING_SNAKE_CASE__ = 0.8_5 , ) -> int: """simple docstring""" _UpperCamelCase :List[Any] = duplication_jaccard_threshold _UpperCamelCase :List[str] = NUM_PERM _UpperCamelCase :int = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) _UpperCamelCase :Optional[int] = defaultdict(UpperCAmelCase__ ) def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> None: """simple docstring""" _UpperCamelCase :List[Any] = self._index.query(UpperCAmelCase__ ) if code_key in self._index.keys: print(f"Duplicate key {code_key}" ) return self._index.insert(UpperCAmelCase__ , UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(UpperCAmelCase__ ) break else: self._duplicate_clusters[close_duplicates[0]].add(UpperCAmelCase__ ) def _UpperCamelCase( self ) -> List[List[Dict]]: """simple docstring""" _UpperCamelCase :List[str] = [] for base, duplicates in self._duplicate_clusters.items(): _UpperCamelCase :Any = [base] + list(UpperCAmelCase__ ) # reformat the cluster to be a list of dict _UpperCamelCase :int = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(UpperCAmelCase__ ) return duplicate_clusters def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ ) -> None: """simple docstring""" _UpperCamelCase :int = self.get_duplicate_clusters() with open(UpperCAmelCase__ , '''w''' ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) def A_ ( snake_case__ ) -> Optional[Any]: _UpperCamelCase , _UpperCamelCase :List[str] = element _UpperCamelCase :Optional[int] = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def A_ ( snake_case__ ) -> List[Any]: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowercase_ , max_queue_size=1_00_00 ) , chunksize=1_00 , ): if data is not None: yield data def A_ ( snake_case__ , snake_case__ ) -> Dict: _UpperCamelCase :List[str] = DuplicationIndex(duplication_jaccard_threshold=lowercase_ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowercase_ ) ) , max_queue_size=1_00 ) ): di.add(lowercase_ , lowercase_ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def A_ ( snake_case__ , snake_case__ ) -> float: _UpperCamelCase :Optional[Any] = get_tokens(lowercase_ ) _UpperCamelCase :Optional[Any] = get_tokens(lowercase_ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) UpperCamelCase__ :Any = None def A_ ( snake_case__ , snake_case__ ) -> Optional[int]: _UpperCamelCase :Tuple = [] for elementa in cluster: _UpperCamelCase :Union[str, Any] = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: _UpperCamelCase :Optional[Any] = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(lowercase_ , lowercase_ ) >= jaccard_threshold: elementa["copies"] += 1 break else: _UpperCamelCase :Any = 1 extremes.append(lowercase_ ) return extremes def A_ ( snake_case__ , snake_case__ , snake_case__ ) -> List[str]: global _shared_dataset _UpperCamelCase :int = dataset _UpperCamelCase :Optional[Any] = [] _UpperCamelCase :List[Any] = partial(_find_cluster_extremes_shared , jaccard_threshold=lowercase_ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowercase_ , lowercase_ , ) , total=len(lowercase_ ) , ): extremes_list.append(lowercase_ ) return extremes_list def A_ ( snake_case__ , snake_case__ = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: _UpperCamelCase :List[Any] = make_duplicate_clusters(lowercase_ , lowercase_ ) _UpperCamelCase :Tuple = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} _UpperCamelCase :int = {} _UpperCamelCase :List[str] = find_extremes(lowercase_ , lowercase_ , lowercase_ ) for extremes in extremes_clusters: for element in extremes: _UpperCamelCase :List[str] = element _UpperCamelCase :Tuple = duplicate_indices - set(extreme_dict.keys() ) _UpperCamelCase :Union[str, Any] = dataset.filter(lambda snake_case__ , snake_case__ : idx not in remove_indices , with_indices=lowercase_ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: _UpperCamelCase :List[str] = element['''base_index'''] in extreme_dict if element["is_extreme"]: _UpperCamelCase :str = extreme_dict[element['''base_index''']]['''copies'''] print(f"Original dataset size: {len(lowercase_ )}" ) print(f"Number of duplicate clusters: {len(lowercase_ )}" ) print(f"Files in duplicate cluster: {len(lowercase_ )}" ) print(f"Unique files in duplicate cluster: {len(lowercase_ )}" ) print(f"Filtered dataset size: {len(lowercase_ )}" ) return ds_filter, duplicate_clusters
355
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowerCamelCase : Optional[Any] = """Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine""" def SCREAMING_SNAKE_CASE ( ) -> Dict: """simple docstring""" A__ = _ask_options( '''In which compute environment are you running?''' , ['''This machine''', '''AWS (Amazon SageMaker)'''] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A__ = get_sagemaker_input() else: A__ = get_cluster_input() return config def SCREAMING_SNAKE_CASE ( lowercase_=None ) -> List[Any]: """simple docstring""" if subparsers is not None: A__ = subparsers.add_parser('''config''' , description=lowercase_ ) else: A__ = argparse.ArgumentParser('''Accelerate config command''' , description=lowercase_ ) parser.add_argument( '''--config_file''' , default=lowercase_ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , ) if subparsers is not None: parser.set_defaults(func=lowercase_ ) return parser def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Any: """simple docstring""" A__ = get_user_input() if args.config_file is not None: A__ = args.config_file else: if not os.path.isdir(lowercase_ ): os.makedirs(lowercase_ ) A__ = default_yaml_config_file if config_file.endswith('''.json''' ): config.to_json_file(lowercase_ ) else: config.to_yaml_file(lowercase_ ) print(f"""accelerate configuration saved at {config_file}""" ) def SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: """simple docstring""" A__ = config_command_parser() A__ = parser.parse_args() config_command(lowercase_ ) if __name__ == "__main__": main()
87
0
import math def UpperCamelCase__ ( UpperCAmelCase_ = 100 ) -> int: '''simple docstring''' _lowercase : Dict = sum(i * i for i in range(1 , n + 1 ) ) _lowercase : List[str] = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(F"""{solution() = }""")
322
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _lowerCamelCase : int = logging.get_logger("""transformers.models.speecht5""") def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Tuple: """simple docstring""" hf_model.apply_weight_norm() A__ = checkpoint['''input_conv.weight_g'''] A__ = checkpoint['''input_conv.weight_v'''] A__ = checkpoint['''input_conv.bias'''] for i in range(len(config.upsample_rates ) ): A__ = checkpoint[f"""upsamples.{i}.1.weight_g"""] A__ = checkpoint[f"""upsamples.{i}.1.weight_v"""] A__ = checkpoint[f"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_g"""] A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_v"""] A__ = checkpoint[f"""blocks.{i}.convs1.{j}.1.bias"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_g"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_v"""] A__ = checkpoint[f"""blocks.{i}.convs2.{j}.1.bias"""] A__ = checkpoint['''output_conv.1.weight_g'''] A__ = checkpoint['''output_conv.1.weight_v'''] A__ = checkpoint['''output_conv.1.bias'''] hf_model.remove_weight_norm() @torch.no_grad() def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , ) -> str: """simple docstring""" if config_path is not None: A__ = SpeechTaHifiGanConfig.from_pretrained(lowercase_ ) else: A__ = SpeechTaHifiGanConfig() A__ = SpeechTaHifiGan(lowercase_ ) A__ = torch.load(lowercase_ ) load_weights(orig_checkpoint['''model''']['''generator'''] , lowercase_ , lowercase_ ) A__ = np.load(lowercase_ ) A__ = stats[0].reshape(-1 ) A__ = stats[1].reshape(-1 ) A__ = torch.from_numpy(lowercase_ ).float() A__ = torch.from_numpy(lowercase_ ).float() model.save_pretrained(lowercase_ ) if repo_id: print('''Pushing to the hub...''' ) model.push_to_hub(lowercase_ ) if __name__ == "__main__": _lowerCamelCase : Any = argparse.ArgumentParser() parser.add_argument("""--checkpoint_path""", required=True, default=None, type=str, help="""Path to original checkpoint""") parser.add_argument("""--stats_path""", required=True, default=None, type=str, help="""Path to stats.npy file""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--pytorch_dump_folder_path""", required=True, default=None, type=str, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) _lowerCamelCase : List[str] = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
87
0
"""simple docstring""" # Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar __A = TypeVar("T") class snake_case ( Generic[T] ): def __init__( self : Union[str, Any] , UpperCamelCase__ : bool = True)-> None: '''simple docstring''' __lowerCAmelCase: str = {} # dictionary of lists __lowerCAmelCase: Any = directed def lowercase_ ( self : str , UpperCamelCase__ : T , UpperCamelCase__ : T)-> GraphAdjacencyList[T]: '''simple docstring''' if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(UpperCAmelCase__) self.adj_list[destination_vertex].append(UpperCAmelCase__) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(UpperCAmelCase__) __lowerCAmelCase: str = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(UpperCAmelCase__) __lowerCAmelCase: Optional[Any] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: __lowerCAmelCase: Union[str, Any] = [destination_vertex] __lowerCAmelCase: List[Any] = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(UpperCAmelCase__) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(UpperCAmelCase__) __lowerCAmelCase: Any = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: __lowerCAmelCase: int = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: __lowerCAmelCase: List[Any] = [destination_vertex] __lowerCAmelCase: List[Any] = [] return self def __repr__( self : Union[str, Any])-> str: '''simple docstring''' return pformat(self.adj_list)
346
import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class UpperCamelCase_ : '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict=13 , UpperCAmelCase__ : Dict=7 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=99 , UpperCAmelCase__ : Union[str, Any]=32 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : List[Any]=37 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=50 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : List[str]=None , ) ->Union[str, Any]: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = initializer_range A__ = use_labels A__ = scope def SCREAMING_SNAKE_CASE ( self : int) ->Any: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) if self.use_labels: A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = self.get_config() return config, input_ids, input_mask, token_labels def SCREAMING_SNAKE_CASE ( self : int) ->int: '''simple docstring''' return BertGenerationConfig( 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 , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : List[str]) ->Union[str, Any]: '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = self.prepare_config_and_inputs() A__ = True A__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) A__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , **UpperCAmelCase__ : List[Any] , ) ->Dict: '''simple docstring''' A__ = BertGenerationEncoder(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__) A__ = model(UpperCAmelCase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[Any] , ) ->Dict: '''simple docstring''' A__ = True A__ = BertGenerationEncoder(config=UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Optional[int] , ) ->Any: '''simple docstring''' A__ = True A__ = True A__ = BertGenerationDecoder(config=UpperCAmelCase__).to(UpperCAmelCase__).eval() # first forward pass A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ , ) A__ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size) A__ = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and A__ = torch.cat([input_ids, next_tokens] , dim=-1) A__ = torch.cat([input_mask, next_mask] , dim=-1) A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] A__ = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] # select random slice A__ = ids_tensor((1,) , output_from_past.shape[-1]).item() A__ = output_from_no_past[:, -3:, random_slice_idx].detach() A__ = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3)) def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , *UpperCAmelCase__ : List[str] , ) ->List[Any]: '''simple docstring''' A__ = BertGenerationDecoder(UpperCAmelCase__) model.to(UpperCAmelCase__) model.eval() A__ = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->List[str]: '''simple docstring''' A__ , A__ , A__ , A__ = self.prepare_config_and_inputs() A__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () UpperCAmelCase__ = (BertGenerationDecoder,) if is_torch_available() else () UpperCAmelCase__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Dict: '''simple docstring''' A__ = BertGenerationEncoderTester(self) A__ = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[str]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any]) ->int: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Optional[Any]: '''simple docstring''' A__ , A__ , A__ , A__ = self.model_tester.prepare_config_and_inputs() A__ = '''bert''' self.model_tester.create_and_check_model(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : int) ->Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any: '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() A__ = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*UpperCAmelCase__) @slow def SCREAMING_SNAKE_CASE ( self : Dict) ->List[Any]: '''simple docstring''' A__ = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') self.assertIsNotNone(UpperCAmelCase__) @require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Any) ->Union[str, Any]: '''simple docstring''' A__ = BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') A__ = torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]) with torch.no_grad(): A__ = model(UpperCAmelCase__)[0] A__ = torch.Size([1, 8, 1_024]) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4)) @require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' A__ = BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') A__ = torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]) with torch.no_grad(): A__ = model(UpperCAmelCase__)[0] A__ = torch.Size([1, 8, 50_358]) self.assertEqual(output.shape , UpperCAmelCase__) A__ = torch.tensor( [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4))
87
0
"""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 _UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ShapEPipeline __SCREAMING_SNAKE_CASE : Any = ["prompt"] __SCREAMING_SNAKE_CASE : Dict = ["prompt"] __SCREAMING_SNAKE_CASE : Optional[int] = [ "num_images_per_prompt", "num_inference_steps", "generator", "latents", "guidance_scale", "frame_size", "output_type", "return_dict", ] __SCREAMING_SNAKE_CASE : int = False @property def a_ ( self ) -> List[Any]: return 3_2 @property def a_ ( self ) -> int: return 3_2 @property def a_ ( self ) -> Optional[Any]: return self.time_input_dim * 4 @property def a_ ( self ) -> str: return 8 @property def a_ ( self ) -> Optional[int]: UpperCAmelCase = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def a_ ( self ) -> List[Any]: torch.manual_seed(0 ) UpperCAmelCase = 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=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModelWithProjection(UpperCAmelCase__ ) @property def a_ ( self ) -> Union[str, Any]: torch.manual_seed(0 ) UpperCAmelCase = { 'num_attention_heads': 2, 'attention_head_dim': 1_6, 'embedding_dim': self.time_input_dim, 'num_embeddings': 3_2, '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, } UpperCAmelCase = PriorTransformer(**UpperCAmelCase__ ) return model @property def a_ ( self ) -> List[str]: torch.manual_seed(0 ) UpperCAmelCase = { 'param_shapes': ( (self.renderer_dim, 9_3), (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': 1_2, 'background': ( 0.1, 0.1, 0.1, ), } UpperCAmelCase = ShapERenderer(**UpperCAmelCase__ ) return model def a_ ( self ) -> List[Any]: UpperCAmelCase = self.dummy_prior UpperCAmelCase = self.dummy_text_encoder UpperCAmelCase = self.dummy_tokenizer UpperCAmelCase = self.dummy_renderer UpperCAmelCase = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1_0_2_4 , prediction_type='sample' , use_karras_sigmas=UpperCAmelCase__ , clip_sample=UpperCAmelCase__ , clip_sample_range=1.0 , ) UpperCAmelCase = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def a_ ( self , lowercase_ , lowercase_=0 ) -> Union[str, Any]: if str(UpperCAmelCase__ ).startswith('mps' ): UpperCAmelCase = torch.manual_seed(UpperCAmelCase__ ) else: UpperCAmelCase = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) UpperCAmelCase = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 3_2, 'output_type': 'np', } return inputs def a_ ( self ) -> Union[str, Any]: UpperCAmelCase = 'cpu' UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = self.pipeline_class(**UpperCAmelCase__ ) UpperCAmelCase = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) UpperCAmelCase = pipe(**self.get_dummy_inputs(UpperCAmelCase__ ) ) UpperCAmelCase = output.images[0] UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (2_0, 3_2, 3_2, 3) UpperCAmelCase = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def a_ ( self ) -> int: self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def a_ ( self ) -> List[str]: UpperCAmelCase = torch_device == 'cpu' UpperCAmelCase = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=UpperCAmelCase__ , relax_max_difference=UpperCAmelCase__ , ) def a_ ( self ) -> Union[str, Any]: UpperCAmelCase = self.get_dummy_components() UpperCAmelCase = self.pipeline_class(**UpperCAmelCase__ ) UpperCAmelCase = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) UpperCAmelCase = 1 UpperCAmelCase = 2 UpperCAmelCase = self.get_dummy_inputs(UpperCAmelCase__ ) for key in inputs.keys(): if key in self.batch_params: UpperCAmelCase = batch_size * [inputs[key]] UpperCAmelCase = pipe(**UpperCAmelCase__ , num_images_per_prompt=UpperCAmelCase__ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _UpperCAmelCase ( unittest.TestCase ): def a_ ( self ) -> List[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self ) -> Optional[int]: UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) UpperCAmelCase = ShapEPipeline.from_pretrained('openai/shap-e' ) UpperCAmelCase = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) UpperCAmelCase = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) UpperCAmelCase = pipe( 'a shark' , generator=UpperCAmelCase__ , guidance_scale=1_5.0 , num_inference_steps=6_4 , frame_size=6_4 , output_type='np' , ).images[0] assert images.shape == (2_0, 6_4, 6_4, 3) assert_mean_pixel_difference(UpperCAmelCase__ , UpperCAmelCase__ )
373
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 _lowerCamelCase : int = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Dict: """simple docstring""" A__ = set() A__ = [] def parse_line(lowercase_ ): for line in fp: if isinstance(lowercase_ , lowercase_ ): A__ = 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(lowercase_ ) > 0: A__ = '''\n'''.join(lowercase_ ) # Only keep the warnings specified in `targets` if any(f""": {x}: """ in warning for x in targets ): selected_warnings.add(lowercase_ ) buffer.clear() continue else: A__ = line.strip() buffer.append(lowercase_ ) if from_gh: for filename in os.listdir(lowercase_ ): A__ = os.path.join(lowercase_ , lowercase_ ) if not os.path.isdir(lowercase_ ): # read the file if filename != "warnings.txt": continue with open(lowercase_ ) as fp: parse_line(lowercase_ ) else: try: with zipfile.ZipFile(lowercase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowercase_ ): # read the file if filename != "warnings.txt": continue with z.open(lowercase_ ) as fp: parse_line(lowercase_ ) 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 SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" A__ = set() A__ = [os.path.join(lowercase_ , lowercase_ ) for p in os.listdir(lowercase_ ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(lowercase_ , lowercase_ ) ) return selected_warnings if __name__ == "__main__": def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" return values.split(''',''' ) _lowerCamelCase : int = 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.""", ) _lowerCamelCase : List[Any] = parser.parse_args() _lowerCamelCase : List[str] = 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 _lowerCamelCase : 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("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts _lowerCamelCase : Any = extract_warnings(args.output_dir, args.targets) _lowerCamelCase : Optional[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)
87
0
import pickle import numpy as np from matplotlib import pyplot as plt class __lowercase : """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=0.2 , __UpperCAmelCase=0.2 ) -> List[str]: A : int = bp_numa A : List[str] = bp_numa A : Union[str, Any] = bp_numa A : Optional[Any] = conva_get[:2] A : Tuple = conva_get[2] A : Any = size_pa A : Optional[Any] = rate_w A : Any = rate_t A : Any = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] A : Tuple = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) A : Any = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) A : Any = -2 * np.random.rand(self.conva[1] ) + 1 A : Dict = -2 * np.random.rand(self.num_bpa ) + 1 A : Optional[Any] = -2 * np.random.rand(self.num_bpa ) + 1 def snake_case ( self , __UpperCAmelCase ) -> int: A : Dict = { '''num_bp1''': self.num_bpa, '''num_bp2''': self.num_bpa, '''num_bp3''': self.num_bpa, '''conv1''': self.conva, '''step_conv1''': self.step_conva, '''size_pooling1''': self.size_poolinga, '''rate_weight''': self.rate_weight, '''rate_thre''': self.rate_thre, '''w_conv1''': self.w_conva, '''wkj''': self.wkj, '''vji''': self.vji, '''thre_conv1''': self.thre_conva, '''thre_bp2''': self.thre_bpa, '''thre_bp3''': self.thre_bpa, } with open(UpperCAmelCase__ , '''wb''' ) as f: pickle.dump(UpperCAmelCase__ , UpperCAmelCase__ ) print(f'Model saved: {save_path}' ) @classmethod def snake_case ( cls , __UpperCAmelCase ) -> Optional[Any]: with open(UpperCAmelCase__ , '''rb''' ) as f: A : Tuple = pickle.load(UpperCAmelCase__ ) # noqa: S301 A : Dict = model_dic.get('''conv1''' ) conv_get.append(model_dic.get('''step_conv1''' ) ) A : List[Any] = model_dic.get('''size_pooling1''' ) A : str = model_dic.get('''num_bp1''' ) A : Any = model_dic.get('''num_bp2''' ) A : Optional[int] = model_dic.get('''num_bp3''' ) A : Optional[Any] = model_dic.get('''rate_weight''' ) A : int = model_dic.get('''rate_thre''' ) # create model instance A : str = CNN(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # modify model parameter A : Dict = model_dic.get('''w_conv1''' ) A : List[Any] = model_dic.get('''wkj''' ) A : Union[str, Any] = model_dic.get('''vji''' ) A : Dict = model_dic.get('''thre_conv1''' ) A : Dict = model_dic.get('''thre_bp2''' ) A : Optional[Any] = model_dic.get('''thre_bp3''' ) return conv_ins def snake_case ( self , __UpperCAmelCase ) -> List[str]: return 1 / (1 + np.exp(-1 * x )) def snake_case ( self , __UpperCAmelCase ) -> List[Any]: return round(UpperCAmelCase__ , 3 ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[str]: A : int = convs[0] A : Tuple = convs[1] A : Tuple = np.shape(UpperCAmelCase__ )[0] # get the data slice of original image data, data_focus A : Tuple = [] for i_focus in range(0 , size_data - size_conv + 1 , UpperCAmelCase__ ): for j_focus in range(0 , size_data - size_conv + 1 , UpperCAmelCase__ ): A : Union[str, Any] = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(UpperCAmelCase__ ) # calculate the feature map of every single kernel, and saved as list of matrix A : str = [] A : Dict = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(UpperCAmelCase__ ): A : int = [] for i_focus in range(len(UpperCAmelCase__ ) ): A : Optional[Any] = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(UpperCAmelCase__ ) ) A : str = np.asmatrix(UpperCAmelCase__ ).reshape( UpperCAmelCase__ , UpperCAmelCase__ ) data_featuremap.append(UpperCAmelCase__ ) # expanding the data slice to One dimenssion A : Tuple = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(UpperCAmelCase__ ) ) A : Union[str, Any] = np.asarray(UpperCAmelCase__ ) return focus_list, data_featuremap def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase="average_pool" ) -> int: A : int = len(featuremaps[0] ) A : Optional[int] = int(size_map / size_pooling ) A : Union[str, Any] = [] for i_map in range(len(UpperCAmelCase__ ) ): A : int = featuremaps[i_map] A : Union[str, Any] = [] for i_focus in range(0 , UpperCAmelCase__ , UpperCAmelCase__ ): for j_focus in range(0 , UpperCAmelCase__ , UpperCAmelCase__ ): A : str = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(UpperCAmelCase__ ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(UpperCAmelCase__ ) ) A : Tuple = np.asmatrix(UpperCAmelCase__ ).reshape(UpperCAmelCase__ , UpperCAmelCase__ ) featuremap_pooled.append(UpperCAmelCase__ ) return featuremap_pooled def snake_case ( self , __UpperCAmelCase ) -> List[Any]: A : Union[str, Any] = [] for i in range(len(UpperCAmelCase__ ) ): A : List[Any] = np.shape(data[i] ) A : Optional[int] = data[i].reshape(1 , shapes[0] * shapes[1] ) A : Union[str, Any] = data_listed.getA().tolist()[0] data_expanded.extend(UpperCAmelCase__ ) A : str = np.asarray(UpperCAmelCase__ ) return data_expanded def snake_case ( self , __UpperCAmelCase ) -> Dict: A : Dict = np.asarray(UpperCAmelCase__ ) A : Optional[int] = np.shape(UpperCAmelCase__ ) A : int = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Union[str, Any]: A : str = [] A : Optional[Any] = 0 for i_map in range(UpperCAmelCase__ ): A : Dict = np.ones((size_map, size_map) ) for i in range(0 , UpperCAmelCase__ , UpperCAmelCase__ ): for j in range(0 , UpperCAmelCase__ , UpperCAmelCase__ ): A : Tuple = pd_pool[ i_pool ] A : Optional[Any] = i_pool + 1 A : Optional[int] = np.multiply( UpperCAmelCase__ , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(UpperCAmelCase__ ) return pd_all def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=bool ) -> Dict: print('''----------------------Start Training-------------------------''' ) print((''' - - Shape: Train_Data ''', np.shape(UpperCAmelCase__ )) ) print((''' - - Shape: Teach_Data ''', np.shape(UpperCAmelCase__ )) ) A : Optional[Any] = 0 A : Any = [] A : List[str] = 1_00_00 while rp < n_repeat and mse >= error_accuracy: A : str = 0 print(f'-------------Learning Time {rp}--------------' ) for p in range(len(UpperCAmelCase__ ) ): # print('------------Learning Image: %d--------------'%p) A : List[Any] = np.asmatrix(datas_train[p] ) A : Tuple = np.asarray(datas_teach[p] ) A , A : List[str] = self.convolute( UpperCAmelCase__ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) A : List[Any] = self.pooling(UpperCAmelCase__ , self.size_poolinga ) A : Union[str, Any] = np.shape(UpperCAmelCase__ ) A : Tuple = self._expand(UpperCAmelCase__ ) A : int = data_bp_input A : Optional[int] = np.dot(UpperCAmelCase__ , self.vji.T ) - self.thre_bpa A : Tuple = self.sig(UpperCAmelCase__ ) A : List[Any] = np.dot(UpperCAmelCase__ , self.wkj.T ) - self.thre_bpa A : int = self.sig(UpperCAmelCase__ ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- A : Optional[int] = np.multiply( (data_teach - bp_outa) , np.multiply(UpperCAmelCase__ , (1 - bp_outa) ) ) A : Dict = np.multiply( np.dot(UpperCAmelCase__ , self.wkj ) , np.multiply(UpperCAmelCase__ , (1 - bp_outa) ) ) A : Optional[Any] = np.dot(UpperCAmelCase__ , self.vji ) A : int = pd_i_all / (self.size_poolinga * self.size_poolinga) A : Union[str, Any] = pd_conva_pooled.T.getA().tolist() A : Dict = self._calculate_gradient_from_pool( UpperCAmelCase__ , UpperCAmelCase__ , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): A : Union[str, Any] = self._expand_mat(pd_conva_all[k_conv] ) A : List[Any] = self.rate_weight * np.dot(UpperCAmelCase__ , UpperCAmelCase__ ) A : List[Any] = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) A : str = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer A : str = self.wkj + pd_k_all.T * bp_outa * self.rate_weight A : str = self.vji + pd_j_all.T * bp_outa * self.rate_weight A : Optional[int] = self.thre_bpa - pd_k_all * self.rate_thre A : Any = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image A : Any = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) A : Optional[Any] = rp + 1 A : Any = error_count / patterns all_mse.append(UpperCAmelCase__ ) def draw_error(): A : List[Any] = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(UpperCAmelCase__ , '''+-''' ) plt.plot(UpperCAmelCase__ , '''r--''' ) plt.xlabel('''Learning Times''' ) plt.ylabel('''All_mse''' ) plt.grid(UpperCAmelCase__ , alpha=0.5 ) plt.show() print('''------------------Training Complished---------------------''' ) print((''' - - Training epoch: ''', rp, f' - - Mse: {mse:.6f}') ) if draw_e: draw_error() return mse def snake_case ( self , __UpperCAmelCase ) -> str: A : Optional[Any] = [] print('''-------------------Start Testing-------------------------''' ) print((''' - - Shape: Test_Data ''', np.shape(UpperCAmelCase__ )) ) for p in range(len(UpperCAmelCase__ ) ): A : Any = np.asmatrix(datas_test[p] ) A , A : Optional[int] = self.convolute( UpperCAmelCase__ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) A : str = self.pooling(UpperCAmelCase__ , self.size_poolinga ) A : int = self._expand(UpperCAmelCase__ ) A : Union[str, Any] = data_bp_input A : Tuple = bp_outa * self.vji.T - self.thre_bpa A : List[Any] = self.sig(UpperCAmelCase__ ) A : Optional[int] = bp_outa * self.wkj.T - self.thre_bpa A : str = self.sig(UpperCAmelCase__ ) produce_out.extend(bp_outa.getA().tolist() ) A : List[str] = [list(map(self.do_round , UpperCAmelCase__ ) ) for each in produce_out] return np.asarray(UpperCAmelCase__ ) def snake_case ( self , __UpperCAmelCase ) -> int: A : Dict = np.asmatrix(UpperCAmelCase__ ) A , A : List[Any] = self.convolute( UpperCAmelCase__ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) A : str = self.pooling(UpperCAmelCase__ , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
542
class UpperCamelCase_ : # Public class to implement a graph '''simple docstring''' def __init__( self : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->None: '''simple docstring''' A__ = row A__ = col A__ = graph def SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->bool: '''simple docstring''' return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : list[list[bool]]) ->None: '''simple docstring''' A__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order A__ = [-1, 0, 1, -1, 1, -1, 0, 1] A__ = True # Make those cells visited for k in range(8): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__): self.diffs(i + row_nbr[k] , j + col_nbr[k] , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->int: # And finally, count all islands. '''simple docstring''' A__ = [[False for j in range(self.COL)] for i in range(self.ROW)] A__ = 0 for i in range(self.ROW): for j in range(self.COL): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) count += 1 return count
87
0
'''simple docstring''' import re def lowerCamelCase__ ( a__) -> str: """simple docstring""" if len(re.findall('[ATCG]' , lowercase_)) != len(lowercase_): raise ValueError('Invalid Strand') return dna.translate(dna.maketrans('ATCG' , 'TAGC')) if __name__ == "__main__": import doctest doctest.testmod()
517
from __future__ import annotations import requests _lowerCamelCase : str = set( """approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod_post category clicked content_categories created_utc downs edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta is_original_content is_reddit_media_domain is_video link_flair_css_class link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title name permalink pwls quarantine saved score secure_media secure_media_embed selftext subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type total_awards_received ups upvote_ratio url user_reports""".split() ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = 1 , lowercase_ = "new" , lowercase_ = None ) -> dict: """simple docstring""" A__ = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(lowercase_ ) - valid_terms ) ): A__ = f"""Invalid search term: {invalid_search_terms}""" raise ValueError(lowercase_ ) A__ = requests.get( f"""https://reddit.com/r/{subreddit}/{age}.json?limit={limit}""" , headers={'''User-agent''': '''A random string'''} , ) if response.status_code == 429: raise requests.HTTPError A__ = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(lowercase_ )} A__ = {} for id_ in range(lowercase_ ): A__ = { item: data['''data''']['''children'''][id_]['''data'''][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("""learnpython""", wanted_data=["""title""", """url""", """selftext"""]))
87
0
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase = { """configuration_mctct""": ["""MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MCTCTConfig"""], """feature_extraction_mctct""": ["""MCTCTFeatureExtractor"""], """processing_mctct""": ["""MCTCTProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ """MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST""", """MCTCTForCTC""", """MCTCTModel""", """MCTCTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
432
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = JukeboxTokenizer UpperCAmelCase__ = { '''artist''': '''Zac Brown Band''', '''genres''': '''Country''', '''lyrics''': '''I met a traveller from an antique land, Who said "Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away ''', } @require_torch def SCREAMING_SNAKE_CASE ( self : Dict) ->int: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''') A__ = tokenizer(**self.metas)['''input_ids'''] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 7_169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]]), torch.tensor([[0, 0, 0, 1_069, 11]]), torch.tensor([[0, 0, 0, 1_069, 11]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2])) @require_torch def SCREAMING_SNAKE_CASE ( self : List[str]) ->Optional[int]: '''simple docstring''' import torch A__ = JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''') A__ = tokenizer(**self.metas)['''input_ids'''] # fmt: off A__ = [ torch.tensor([[ 0, 0, 0, 1_069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]]), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]]), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]]), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0])) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1])) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2]))
87
0
'''simple docstring''' import math from collections.abc import Iterator from itertools import takewhile def UpperCamelCase_( snake_case : Union[str, Any] ): '''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(lowercase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCamelCase_( ): '''simple docstring''' snake_case_ = 2 while True: if is_prime(lowercase_ ): yield num num += 1 def UpperCamelCase_( snake_case : Optional[int] = 2_0_0_0_0_0_0 ): '''simple docstring''' return sum(takewhile(lambda snake_case : x < n , prime_generator() ) ) if __name__ == "__main__": print(F"{solution() = }")
400
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : str = logging.get_logger(__name__) _lowerCamelCase : List[str] = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = '''openai-gpt''' UpperCAmelCase__ = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict=40_478 , UpperCAmelCase__ : str=512 , UpperCAmelCase__ : Union[str, Any]=768 , UpperCAmelCase__ : Optional[Any]=12 , UpperCAmelCase__ : Any=12 , UpperCAmelCase__ : Optional[Any]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : List[str]=1e-5 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Any="cls_index" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Optional[Any]=0.1 , **UpperCAmelCase__ : Dict , ) ->Any: '''simple docstring''' A__ = vocab_size A__ = n_positions A__ = n_embd A__ = n_layer A__ = n_head A__ = afn A__ = resid_pdrop A__ = embd_pdrop A__ = attn_pdrop A__ = layer_norm_epsilon A__ = initializer_range A__ = summary_type A__ = summary_use_proj A__ = summary_activation A__ = summary_first_dropout A__ = summary_proj_to_labels super().__init__(**UpperCAmelCase__)
87
0
'''simple docstring''' import unittest from transformers import AutoTokenizer, FalconConfig, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, ) class A_ : '''simple docstring''' def __init__( self , A_ , A_=3 , A_=7 , A_=True , A_=True , A_=False , A_=True , A_=99 , A_=32 , A_=5 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=5_12 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=4 , A_=None , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_mask _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_labels _UpperCamelCase = num_choices _UpperCamelCase = scope def a ( self ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = None if self.use_input_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None if self.use_labels: _UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) _UpperCamelCase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def a ( self ): return FalconConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=UpperCAmelCase__ , ) def a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): _UpperCamelCase = FalconModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _UpperCamelCase = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) _UpperCamelCase = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): _UpperCamelCase = True _UpperCamelCase = FalconModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _UpperCamelCase = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) _UpperCamelCase = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) _UpperCamelCase = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): _UpperCamelCase = FalconForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _UpperCamelCase = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ): _UpperCamelCase = True _UpperCamelCase = True _UpperCamelCase = FalconForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # first forward pass _UpperCamelCase = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ , ) _UpperCamelCase = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _UpperCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) _UpperCamelCase = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and _UpperCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) _UpperCamelCase = torch.cat([input_mask, next_mask] , dim=-1 ) _UpperCamelCase = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )["hidden_states"][0] _UpperCamelCase = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )["hidden_states"][0] # select random slice _UpperCamelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item() _UpperCamelCase = output_from_no_past[:, -3:, random_slice_idx].detach() _UpperCamelCase = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) ) def a ( self ): _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class A_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' _lowerCAmelCase = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) _lowerCAmelCase = (FalconForCausalLM,) if is_torch_available() else () _lowerCAmelCase = ( { """feature-extraction""": FalconModel, """text-classification""": FalconForSequenceClassification, """text-generation""": FalconForCausalLM, """question-answering""": FalconForQuestionAnswering, """token-classification""": FalconForTokenClassification, """zero-shot""": FalconForSequenceClassification, } if is_torch_available() else {} ) _lowerCAmelCase = False _lowerCAmelCase = False def a ( self ): _UpperCamelCase = FalconModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37 ) def a ( self ): self.config_tester.run_common_tests() def a ( self ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def a ( self ): _UpperCamelCase , *_UpperCamelCase = self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: _UpperCamelCase = alibi self.model_tester.create_and_check_model(UpperCAmelCase__ , *UpperCAmelCase__ ) def a ( self ): _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase = 3 _UpperCamelCase = input_dict["input_ids"] _UpperCamelCase = input_ids.ne(1 ).to(UpperCAmelCase__ ) _UpperCamelCase = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _UpperCamelCase = FalconForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _UpperCamelCase = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def a ( self ): _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase = 3 _UpperCamelCase = "single_label_classification" _UpperCamelCase = input_dict["input_ids"] _UpperCamelCase = input_ids.ne(1 ).to(UpperCAmelCase__ ) _UpperCamelCase = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _UpperCamelCase = FalconForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _UpperCamelCase = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def a ( self ): _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase = input_dict["input_ids"] _UpperCamelCase = FalconForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _UpperCamelCase = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) _UpperCamelCase = input_ids.shape[0] _UpperCamelCase = model._convert_to_rw_cache(result.past_key_values ) _UpperCamelCase = model._convert_cache_to_standard_format(UpperCAmelCase__ , UpperCAmelCase__ ) for layer in range(len(UpperCAmelCase__ ) ): for tensor_idx in range(2 ): self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 ) self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 ) self.assertTrue( torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) ) def a ( self ): _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase = 3 _UpperCamelCase = "multi_label_classification" _UpperCamelCase = input_dict["input_ids"] _UpperCamelCase = input_ids.ne(1 ).to(UpperCAmelCase__ ) _UpperCamelCase = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) _UpperCamelCase = FalconForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() _UpperCamelCase = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def a ( self ): for model_class in self.all_generative_model_classes: _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(UpperCAmelCase__ , "use_cache" ): return _UpperCamelCase = model_class(UpperCAmelCase__ ).to(UpperCAmelCase__ ) if "use_cache" not in inputs: _UpperCamelCase = True _UpperCamelCase = model(**UpperCAmelCase__ ) # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format) if "past_key_values" not in outputs: return _UpperCamelCase = ( getattr(UpperCAmelCase__ , "decoder_layers" , UpperCAmelCase__ ) or getattr(UpperCAmelCase__ , "num_decoder_layers" , UpperCAmelCase__ ) or config.num_hidden_layers ) _UpperCamelCase = getattr(UpperCAmelCase__ , "num_kv_heads" , config.num_attention_heads ) _UpperCamelCase = getattr(UpperCAmelCase__ , "d_model" , config.hidden_size ) _UpperCamelCase = embed_dim // num_attention_heads _UpperCamelCase = outputs["past_key_values"] self.assertEqual(len(UpperCAmelCase__ ) , UpperCAmelCase__ ) _UpperCamelCase , _UpperCamelCase = inputs["input_ids"].shape for i in range(UpperCAmelCase__ ): if config.new_decoder_architecture: _UpperCamelCase = config.num_attention_heads elif config.multi_query: _UpperCamelCase = 1 self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2 self.assertEqual( past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) self.assertEqual( past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' @slow def a ( self ): _UpperCamelCase = AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b" ) _UpperCamelCase = FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b" ) model.eval() model.to(UpperCAmelCase__ ) _UpperCamelCase = tokenizer("My favorite food is" , return_tensors="pt" ).to(UpperCAmelCase__ ) _UpperCamelCase = ( "My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday." ) _UpperCamelCase = model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=19 ) _UpperCamelCase = tokenizer.batch_decode(UpperCAmelCase__ )[0] self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def a ( self ): for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: _UpperCamelCase = AutoTokenizer.from_pretrained(UpperCAmelCase__ ) _UpperCamelCase = FalconForCausalLM.from_pretrained(UpperCAmelCase__ ) model.eval() model.to(UpperCAmelCase__ ) _UpperCamelCase = tokenizer("My favorite food is" , return_tensors="pt" ).to(UpperCAmelCase__ ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=4 ) model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=4 ) model.generate(**UpperCAmelCase__ , num_beams=2 , max_new_tokens=4 ) @slow def a ( self ): with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: _UpperCamelCase = AutoTokenizer.from_pretrained(UpperCAmelCase__ ) _UpperCamelCase = FalconForCausalLM.from_pretrained(UpperCAmelCase__ ) model.eval() model.to(device=UpperCAmelCase__ ) _UpperCamelCase = tokenizer("My favorite food is" , return_tensors="pt" ).to(UpperCAmelCase__ ) # Test results are the same with and without cache _UpperCamelCase = model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=20 , use_cache=UpperCAmelCase__ ) _UpperCamelCase = model.generate(**UpperCAmelCase__ , do_sample=UpperCAmelCase__ , max_new_tokens=20 , use_cache=UpperCAmelCase__ ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
138
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