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
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib lowerCAmelCase_ = get_logger() lowerCAmelCase_ = None class __lowerCAmelCase ( TensorFormatter[Mapping, '''jax.Array''', Mapping] ): def __init__(self , __magic_name__=None , __magic_name__=None , **__magic_name__ ) -> Tuple: '''simple docstring''' super().__init__(features=__magic_name__ ) import jax from jaxlib.xla_client import Device if isinstance(__magic_name__ , __magic_name__ ): raise ValueError( F'''Expected {device} to be a `str` not {type(__magic_name__ )}, as `jaxlib.xla_extension.Device` ''' '''is not serializable neither with `pickle` nor with `dill`. Instead you can surround ''' '''the device with `str()` to get its string identifier that will be internally mapped ''' '''to the actual `jaxlib.xla_extension.Device`.''' ) snake_case_ : Any = device if isinstance(__magic_name__ , __magic_name__ ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: snake_case_ : Dict = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F'''Device with string identifier {self.device} not listed among the available ''' F'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ''' F'''device: {str(jax.devices()[0] )}.''' ) snake_case_ : Any = str(jax.devices()[0] ) snake_case_ : int = jnp_array_kwargs @staticmethod def lowerCamelCase () -> Dict[str, "jaxlib.xla_extension.Device"]: '''simple docstring''' import jax return {str(__magic_name__ ): device for device in jax.devices()} def lowerCamelCase (self , __magic_name__ ) -> List[Any]: '''simple docstring''' import jax import jax.numpy as jnp if isinstance(__magic_name__ , __magic_name__ ) and column: if all( isinstance(__magic_name__ , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(__magic_name__ , axis=0 ) return column def lowerCamelCase (self , __magic_name__ ) -> Optional[Any]: '''simple docstring''' import jax import jax.numpy as jnp if isinstance(__magic_name__ , (str, bytes, type(__magic_name__ )) ): return value elif isinstance(__magic_name__ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() snake_case_ : Any = {} if isinstance(__magic_name__ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: snake_case_ : List[Any] = {'''dtype''': jnp.intaa} else: snake_case_ : Dict = {'''dtype''': jnp.intaa} elif isinstance(__magic_name__ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): snake_case_ : Any = {'''dtype''': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(__magic_name__ , PIL.Image.Image ): snake_case_ : Dict = np.asarray(__magic_name__ ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: snake_case_ : str = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(__magic_name__ , **{**default_dtype, **self.jnp_array_kwargs} ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(__magic_name__ , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(__magic_name__ , '''__array__''' ) and not isinstance(__magic_name__ , jax.Array ): snake_case_ : Optional[int] = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(__magic_name__ , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(__magic_name__ ) for substruct in data_struct] ) elif isinstance(__magic_name__ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(__magic_name__ ) for substruct in data_struct] ) return self._tensorize(__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' return map_nested(self._recursive_tensorize , __magic_name__ , map_list=__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Mapping: '''simple docstring''' snake_case_ : Union[str, Any] = self.numpy_arrow_extractor().extract_row(__magic_name__ ) snake_case_ : str = self.python_features_decoder.decode_row(__magic_name__ ) return self.recursive_tensorize(__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> "jax.Array": '''simple docstring''' snake_case_ : Dict = self.numpy_arrow_extractor().extract_column(__magic_name__ ) snake_case_ : str = self.python_features_decoder.decode_column(__magic_name__ , pa_table.column_names[0] ) snake_case_ : List[Any] = self.recursive_tensorize(__magic_name__ ) snake_case_ : Dict = self._consolidate(__magic_name__ ) return column def lowerCamelCase (self , __magic_name__ ) -> Mapping: '''simple docstring''' snake_case_ : List[Any] = self.numpy_arrow_extractor().extract_batch(__magic_name__ ) snake_case_ : Any = self.python_features_decoder.decode_batch(__magic_name__ ) snake_case_ : Any = self.recursive_tensorize(__magic_name__ ) for column_name in batch: snake_case_ : str = self._consolidate(batch[column_name] ) return batch
60
from __future__ import annotations a_ : str = [] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for i in range(len(_UpperCAmelCase)): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase)): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , -1 , -1)): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , len(_UpperCAmelCase))): if board[i][j] == 1: return False return True def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if row >= len(_UpperCAmelCase): solution.append(_UpperCAmelCase) printboard(_UpperCAmelCase) print() return True for i in range(len(_UpperCAmelCase)): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 solve(_UpperCAmelCase , row + 1) SCREAMING_SNAKE_CASE = 0 return False def lowerCamelCase__ (_UpperCAmelCase): for i in range(len(_UpperCAmelCase)): for j in range(len(_UpperCAmelCase)): if board[i][j] == 1: print('Q' , end=' ') else: print('.' , end=' ') print() # n=int(input("The no. of queens")) a_ : Tuple = 8 a_ : int = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
73
0
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["image_processor", "tokenizer"] snake_case__ = "AutoImageProcessor" snake_case__ = "AutoTokenizer" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Dict=None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Union[str, Any]: lowerCAmelCase__ = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = kwargs.pop("feature_extractor" ) lowerCAmelCase__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.image_processor lowerCAmelCase__ = False def __call__( self : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> str: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = kwargs.pop("images" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = kwargs.pop("text" , SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: lowerCAmelCase__ = args[0] lowerCAmelCase__ = args[1:] if images is None and text is None: raise ValueError("You need to specify either an `images` or `text` input to process." ) if images is not None: lowerCAmelCase__ = self.image_processor(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None: lowerCAmelCase__ = self.tokenizer(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is None: return inputs elif images is None: return encodings else: lowerCAmelCase__ = encodings["input_ids"] return inputs def a ( self : List[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[Any]: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : str , *SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> str: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @contextmanager def a ( self : str ) -> Tuple: warnings.warn( "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your " "labels by using the argument `text` of the regular `__call__` method (either in the same call as " "your images inputs, or in a separate call." ) lowerCAmelCase__ = True lowerCAmelCase__ = self.tokenizer yield lowerCAmelCase__ = self.image_processor lowerCAmelCase__ = False def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None ) -> Optional[Any]: if added_vocab is None: lowerCAmelCase__ = self.tokenizer.get_added_vocab() lowerCAmelCase__ = {} while tokens: lowerCAmelCase__ = re.search(r"<s_(.*?)>" , SCREAMING_SNAKE_CASE__ , re.IGNORECASE ) if start_token is None: break lowerCAmelCase__ = start_token.group(1 ) lowerCAmelCase__ = re.search(rf'</s_{key}>' , SCREAMING_SNAKE_CASE__ , re.IGNORECASE ) lowerCAmelCase__ = start_token.group() if end_token is None: lowerCAmelCase__ = tokens.replace(SCREAMING_SNAKE_CASE__ , "" ) else: lowerCAmelCase__ = end_token.group() lowerCAmelCase__ = re.escape(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = re.escape(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = re.search(f'{start_token_escaped}(.*?){end_token_escaped}' , SCREAMING_SNAKE_CASE__ , re.IGNORECASE ) if content is not None: lowerCAmelCase__ = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node lowerCAmelCase__ = self.tokenajson(SCREAMING_SNAKE_CASE__ , is_inner_value=SCREAMING_SNAKE_CASE__ , added_vocab=SCREAMING_SNAKE_CASE__ ) if value: if len(SCREAMING_SNAKE_CASE__ ) == 1: lowerCAmelCase__ = value[0] lowerCAmelCase__ = value else: # leaf nodes lowerCAmelCase__ = [] for leaf in content.split(r"<sep/>" ): lowerCAmelCase__ = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": lowerCAmelCase__ = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__ ) if len(output[key] ) == 1: lowerCAmelCase__ = output[key][0] lowerCAmelCase__ = tokens[tokens.find(SCREAMING_SNAKE_CASE__ ) + len(SCREAMING_SNAKE_CASE__ ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] , is_inner_value=SCREAMING_SNAKE_CASE__ , added_vocab=SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def a ( self : Union[str, Any] ) -> List[Any]: warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , SCREAMING_SNAKE_CASE__ , ) return self.image_processor_class @property def a ( self : Optional[Any] ) -> Tuple: warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , SCREAMING_SNAKE_CASE__ , ) return self.image_processor
61
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) for optional_component in pipe._optional_components: self.assertTrue( getattr(a , a) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
0
import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": snake_case = argparse.ArgumentParser( description=( """Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned""" """ Distillation""" ) ) parser.add_argument("""--model_type""", default="""roberta""", choices=["""roberta""", """gpt2"""]) parser.add_argument("""--model_name""", default="""roberta-large""", type=str) parser.add_argument("""--dump_checkpoint""", default="""serialization_dir/tf_roberta_048131723.pth""", type=str) parser.add_argument("""--vocab_transform""", action="""store_true""") snake_case = parser.parse_args() if args.model_type == "roberta": snake_case = RobertaForMaskedLM.from_pretrained(args.model_name) snake_case = """roberta""" elif args.model_type == "gpt2": snake_case = GPTaLMHeadModel.from_pretrained(args.model_name) snake_case = """transformer""" snake_case = model.state_dict() snake_case = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: snake_case = state_dict[F"""{prefix}.{param_name}"""] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: snake_case = F"""{prefix}.embeddings.{w}.weight""" snake_case = state_dict[param_name] for w in ["weight", "bias"]: snake_case = F"""{prefix}.embeddings.LayerNorm.{w}""" snake_case = state_dict[param_name] # Transformer Blocks # snake_case = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: snake_case = state_dict[ F"""{prefix}.h.{teacher_idx}.{layer}.{w}""" ] snake_case = state_dict[F"""{prefix}.h.{teacher_idx}.attn.bias"""] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: snake_case = state_dict[ F"""{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}""" ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: snake_case = state_dict[F"""{layer}"""] if args.vocab_transform: for w in ["weight", "bias"]: snake_case = state_dict[F"""lm_head.dense.{w}"""] snake_case = state_dict[F"""lm_head.layer_norm.{w}"""] elif args.model_type == "gpt2": for w in ["weight", "bias"]: snake_case = state_dict[F"""{prefix}.ln_f.{w}"""] snake_case = state_dict["""lm_head.weight"""] print(F"""N layers selected for distillation: {std_idx}""") print(F"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(F"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
62
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Any = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _snake_case ( A__ ): _lowercase : Optional[int] = '''unispeech''' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="mean" , a=False , a=False , a=256 , a=80 , a=0 , a=1 , a=2 , a=0.5 , **a , ) -> Optional[int]: super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE = replace_prob @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return functools.reduce(operator.mul , self.conv_stride , 1)
73
0
import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def lowerCamelCase__ ( __lowerCamelCase : Any ): # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def lowerCamelCase__ ( ): with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" __UpperCAmelCase : List[Any] = [1, 2, 3] with pytest.raises(__lowerCamelCase ): with parallel_backend("""unsupported backend""" ): map_nested(__lowerCamelCase , __lowerCamelCase , num_proc=2 ) with pytest.raises(__lowerCamelCase ): with parallel_backend("""unsupported backend""" ): map_nested(__lowerCamelCase , __lowerCamelCase , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" , [2, -1] ) def lowerCamelCase__ ( __lowerCamelCase : Union[str, Any] ): __UpperCAmelCase : int = [1, 2] __UpperCAmelCase : Dict = {"""a""": 1, """b""": 2} __UpperCAmelCase : Optional[int] = {"""a""": [1, 2], """b""": [3, 4]} __UpperCAmelCase : str = {"""a""": {"""1""": 1}, """b""": 2} __UpperCAmelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} __UpperCAmelCase : Tuple = [2, 3] __UpperCAmelCase : List[str] = {"""a""": 2, """b""": 3} __UpperCAmelCase : List[Any] = {"""a""": [2, 3], """b""": [4, 5]} __UpperCAmelCase : str = {"""a""": {"""1""": 2}, """b""": 3} __UpperCAmelCase : Tuple = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(__lowerCamelCase , __lowerCamelCase , num_proc=__lowerCamelCase ) == expected_map_nested_sa assert map_nested(__lowerCamelCase , __lowerCamelCase , num_proc=__lowerCamelCase ) == expected_map_nested_sa assert map_nested(__lowerCamelCase , __lowerCamelCase , num_proc=__lowerCamelCase ) == expected_map_nested_sa assert map_nested(__lowerCamelCase , __lowerCamelCase , num_proc=__lowerCamelCase ) == expected_map_nested_sa assert map_nested(__lowerCamelCase , __lowerCamelCase , num_proc=__lowerCamelCase ) == expected_map_nested_sa
63
import argparse import collections import json import os import re import string import sys import numpy as np a_ : Optional[Any] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a_ : List[str] = None def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.') parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.') parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).') parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.') parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.') parser.add_argument('--verbose' , '-v' , action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa['answers']['text']) return qid_to_has_ans def lowerCamelCase__ (_UpperCAmelCase): def remove_articles(_UpperCAmelCase): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase) def white_space_fix(_UpperCAmelCase): return " ".join(text.split()) def remove_punc(_UpperCAmelCase): SCREAMING_SNAKE_CASE = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(_UpperCAmelCase): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase)))) def lowerCamelCase__ (_UpperCAmelCase): if not s: return [] return normalize_answer(_UpperCAmelCase).split() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int(normalize_answer(_UpperCAmelCase) == normalize_answer(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.Counter(_UpperCAmelCase) & collections.Counter(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(common.values()) if len(_UpperCAmelCase) == 0 or len(_UpperCAmelCase) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa['id'] SCREAMING_SNAKE_CASE = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase)] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [''] if qid not in preds: print(F'''Missing prediction for {qid}''') continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) SCREAMING_SNAKE_CASE = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) return exact_scores, fa_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid]) else: SCREAMING_SNAKE_CASE = s return new_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): if not qid_list: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values()) / total), ('f1', 1_00.0 * sum(fa_scores.values()) / total), ('total', total), ]) else: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list) / total), ('total', total), ]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post') plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(_UpperCAmelCase) plt.savefig(_UpperCAmelCase) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(_UpperCAmelCase): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1) SCREAMING_SNAKE_CASE = true_pos / float(_UpperCAmelCase) if i == len(_UpperCAmelCase) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase) recalls.append(_UpperCAmelCase) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return {"ap": 1_00.0 * avg_prec} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if out_image_dir and not os.path.exists(_UpperCAmelCase): os.makedirs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png') , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png') , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE = {k: float(_UpperCAmelCase) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png') , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(_UpperCAmelCase) / float(len(_UpperCAmelCase)) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title(F'''Histogram of no-answer probability: {name}''') plt.savefig(os.path.join(_UpperCAmelCase , F'''na_prob_hist_{name}.png''')) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) for i, qid in enumerate(_UpperCAmelCase): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 1_00.0 * best_score / len(_UpperCAmelCase), best_thresh def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def lowerCamelCase__ (): with open(OPTS.data_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset_json['data'] with open(OPTS.pred_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(_UpperCAmelCase) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns') if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns') histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns') if OPTS.out_file: with open(OPTS.out_file , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) else: print(json.dumps(_UpperCAmelCase , indent=2)) if __name__ == "__main__": a_ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
73
0
def A__ ( snake_case_ : list ): if len(snake_case_ ) <= 1: return [tuple(snake_case_ )] SCREAMING_SNAKE_CASE__: str= [] def generate(snake_case_ : int , snake_case_ : list ): SCREAMING_SNAKE_CASE__: int= [0] * n res.append(tuple(snake_case_ ) ) SCREAMING_SNAKE_CASE__: Tuple= 0 while i < n: if c[i] < i: if i % 2 == 0: SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: Tuple= arr[i], arr[0] else: SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: List[Any]= arr[i], arr[c[i]] res.append(tuple(snake_case_ ) ) c[i] += 1 SCREAMING_SNAKE_CASE__: Dict= 0 else: SCREAMING_SNAKE_CASE__: Any= 0 i += 1 generate(len(snake_case_ ) , snake_case_ ) return res if __name__ == "__main__": lowercase_ : Any = input('Enter numbers separated by a comma:\n').strip() lowercase_ : Optional[int] = [int(item) for item in user_input.split(',')] print(heaps(arr))
64
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a , ) super().__init__(*a , **a)
73
0
"""simple docstring""" import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class __lowercase ( unittest.TestCase ): def __lowercase ( self : Any ): '''simple docstring''' # A mock response for an HTTP head request to emulate server down UpperCAmelCase__ : Optional[int] = mock.Mock() UpperCAmelCase__ : List[Any] = 500 UpperCAmelCase__ : int = {} UpperCAmelCase__ : List[str] = HTTPError UpperCAmelCase__ : str = {} # Download this model to make sure it's in the cache. UpperCAmelCase__ : int = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("""requests.Session.request""" ,return_value=A ) as mock_head: UpperCAmelCase__ : Any = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def __lowercase ( self : int ): '''simple docstring''' # A mock response for an HTTP head request to emulate server down UpperCAmelCase__ : List[str] = mock.Mock() UpperCAmelCase__ : List[str] = 500 UpperCAmelCase__ : Optional[int] = {} UpperCAmelCase__ : Any = HTTPError UpperCAmelCase__ : Any = {} # Download this model to make sure it's in the cache. UpperCAmelCase__ : List[Any] = GPTaTokenizerFast.from_pretrained("""gpt2""" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("""requests.Session.request""" ,return_value=A ) as mock_head: UpperCAmelCase__ : List[Any] = GPTaTokenizerFast.from_pretrained("""gpt2""" ) # This check we did call the fake head request mock_head.assert_called() def __lowercase ( self : List[str] ): '''simple docstring''' # This test is for deprecated behavior and can be removed in v5 try: UpperCAmelCase__ : List[str] = tempfile.mktemp() with open(A ,"""wb""" ) as f: http_get("""https://huggingface.co/albert-base-v1/resolve/main/spiece.model""" ,A ) UpperCAmelCase__ : Any = AlbertTokenizer.from_pretrained(A ) finally: os.remove(A ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile("""tokenizer.json""" ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open("""tokenizer.json""" ,"""wb""" ) as f: http_get("""https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json""" ,A ) UpperCAmelCase__ : List[str] = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""" ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1_000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove("""tokenizer.json""" ) def __lowercase ( self : List[str] ): '''simple docstring''' # This test is for deprecated behavior and can be removed in v5 UpperCAmelCase__ : Tuple = AlbertTokenizer.from_pretrained("""https://huggingface.co/albert-base-v1/resolve/main/spiece.model""" ) @is_staging_test class __lowercase ( unittest.TestCase ): snake_case_ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""] @classmethod def __lowercase ( cls : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ : int = TOKEN HfFolder.save_token(A ) @classmethod def __lowercase ( cls : List[Any] ): '''simple docstring''' try: delete_repo(token=cls._token ,repo_id="""test-tokenizer""" ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id="""valid_org/test-tokenizer-org""" ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id="""test-dynamic-tokenizer""" ) except HTTPError: pass def __lowercase ( self : int ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase__ : List[Any] = os.path.join(A ,"""vocab.txt""" ) with open(A ,"""w""" ,encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) UpperCAmelCase__ : List[Any] = BertTokenizer(A ) tokenizer.push_to_hub("""test-tokenizer""" ,use_auth_token=self._token ) UpperCAmelCase__ : List[Any] = BertTokenizer.from_pretrained(f"{USER}/test-tokenizer" ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id="""test-tokenizer""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(A ,repo_id="""test-tokenizer""" ,push_to_hub=A ,use_auth_token=self._token ) UpperCAmelCase__ : str = BertTokenizer.from_pretrained(f"{USER}/test-tokenizer" ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def __lowercase ( self : List[str] ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase__ : Dict = os.path.join(A ,"""vocab.txt""" ) with open(A ,"""w""" ,encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) UpperCAmelCase__ : Union[str, Any] = BertTokenizer(A ) tokenizer.push_to_hub("""valid_org/test-tokenizer-org""" ,use_auth_token=self._token ) UpperCAmelCase__ : Dict = BertTokenizer.from_pretrained("""valid_org/test-tokenizer-org""" ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id="""valid_org/test-tokenizer-org""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( A ,repo_id="""valid_org/test-tokenizer-org""" ,push_to_hub=A ,use_auth_token=self._token ) UpperCAmelCase__ : List[str] = BertTokenizer.from_pretrained("""valid_org/test-tokenizer-org""" ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def __lowercase ( self : str ): '''simple docstring''' CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase__ : Optional[Any] = os.path.join(A ,"""vocab.txt""" ) with open(A ,"""w""" ,encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) UpperCAmelCase__ : Tuple = CustomTokenizer(A ) # No fast custom tokenizer tokenizer.push_to_hub("""test-dynamic-tokenizer""" ,use_auth_token=self._token ) UpperCAmelCase__ : Dict = AutoTokenizer.from_pretrained(f"{USER}/test-dynamic-tokenizer" ,trust_remote_code=A ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,"""CustomTokenizer""" ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase__ : List[str] = os.path.join(A ,"""vocab.txt""" ) with open(A ,"""w""" ,encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) UpperCAmelCase__ : Dict = BertTokenizerFast.from_pretrained(A ) bert_tokenizer.save_pretrained(A ) UpperCAmelCase__ : Dict = CustomTokenizerFast.from_pretrained(A ) tokenizer.push_to_hub("""test-dynamic-tokenizer""" ,use_auth_token=self._token ) UpperCAmelCase__ : Any = AutoTokenizer.from_pretrained(f"{USER}/test-dynamic-tokenizer" ,trust_remote_code=A ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,"""CustomTokenizerFast""" ) UpperCAmelCase__ : str = AutoTokenizer.from_pretrained( f"{USER}/test-dynamic-tokenizer" ,use_fast=A ,trust_remote_code=A ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,"""CustomTokenizer""" ) class __lowercase ( unittest.TestCase ): def __lowercase ( self : int ): '''simple docstring''' UpperCAmelCase__ : Tuple = Trie() trie.add("""Hello 友達""" ) self.assertEqual(trie.data ,{"""H""": {"""e""": {"""l""": {"""l""": {"""o""": {""" """: {"""友""": {"""達""": {"""""": 1}}}}}}}}} ) trie.add("""Hello""" ) trie.data self.assertEqual(trie.data ,{"""H""": {"""e""": {"""l""": {"""l""": {"""o""": {"""""": 1, """ """: {"""友""": {"""達""": {"""""": 1}}}}}}}}} ) def __lowercase ( self : Any ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = Trie() self.assertEqual(trie.split("""[CLS] This is a extra_id_100""" ) ,["""[CLS] This is a extra_id_100"""] ) trie.add("""[CLS]""" ) trie.add("""extra_id_1""" ) trie.add("""extra_id_100""" ) self.assertEqual(trie.split("""[CLS] This is a extra_id_100""" ) ,["""[CLS]""", """ This is a """, """extra_id_100"""] ) def __lowercase ( self : List[Any] ): '''simple docstring''' UpperCAmelCase__ : int = Trie() trie.add("""A""" ) self.assertEqual(trie.split("""ABC""" ) ,["""A""", """BC"""] ) self.assertEqual(trie.split("""BCA""" ) ,["""BC""", """A"""] ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ : Tuple = Trie() trie.add("""TOKEN]""" ) trie.add("""[SPECIAL_TOKEN]""" ) self.assertEqual(trie.split("""This is something [SPECIAL_TOKEN]""" ) ,["""This is something """, """[SPECIAL_TOKEN]"""] ) def __lowercase ( self : Dict ): '''simple docstring''' UpperCAmelCase__ : Dict = Trie() trie.add("""A""" ) trie.add("""P""" ) trie.add("""[SPECIAL_TOKEN]""" ) self.assertEqual(trie.split("""This is something [SPECIAL_TOKEN]""" ) ,["""This is something """, """[SPECIAL_TOKEN]"""] ) def __lowercase ( self : Dict ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = Trie() trie.add("""AB""" ) trie.add("""B""" ) trie.add("""C""" ) self.assertEqual(trie.split("""ABC""" ) ,["""AB""", """C"""] ) def __lowercase ( self : str ): '''simple docstring''' UpperCAmelCase__ : int = Trie() trie.add("""ABC""" ) trie.add("""B""" ) trie.add("""CD""" ) self.assertEqual(trie.split("""ABCD""" ) ,["""ABC""", """D"""] ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' # Even if the offsets are wrong, we necessarily output correct string # parts. UpperCAmelCase__ : Dict = Trie() UpperCAmelCase__ : Optional[int] = trie.cut_text("""ABC""" ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(A ,["""AB""", """C"""] )
65
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> List[Any]: _lowercase : int = 384 if "tiny" in model_name: _lowercase : Tuple = [3, 3, 9, 3] _lowercase : List[str] = [96, 192, 384, 768] if "small" in model_name: _lowercase : List[str] = [3, 3, 27, 3] _lowercase : Union[str, Any] = [96, 192, 384, 768] if "base" in model_name: _lowercase : List[Any] = [3, 3, 27, 3] _lowercase : Dict = [128, 256, 512, 1_024] _lowercase : Optional[int] = 512 if "large" in model_name: _lowercase : List[str] = [3, 3, 27, 3] _lowercase : List[Any] = [192, 384, 768, 1_536] _lowercase : Tuple = 768 if "xlarge" in model_name: _lowercase : str = [3, 3, 27, 3] _lowercase : List[str] = [256, 512, 1_024, 2_048] _lowercase : Tuple = 1_024 # set label information _lowercase : Dict = 150 _lowercase : Union[str, Any] = 'huggingface/label-files' _lowercase : str = 'ade20k-id2label.json' _lowercase : List[Any] = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) _lowercase : Dict = {int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} _lowercase : Tuple = {v: k for k, v in idalabel.items()} _lowercase : List[str] = ConvNextConfig( depths=SCREAMING_SNAKE_CASE , hidden_sizes=SCREAMING_SNAKE_CASE , out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) _lowercase : Union[str, Any] = UperNetConfig( backbone_config=SCREAMING_SNAKE_CASE , auxiliary_in_channels=SCREAMING_SNAKE_CASE , num_labels=SCREAMING_SNAKE_CASE , idalabel=SCREAMING_SNAKE_CASE , labelaid=SCREAMING_SNAKE_CASE , ) return config def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> int: _lowercase : Any = [] # fmt: off # stem rename_keys.append(('backbone.downsample_layers.0.0.weight', 'backbone.embeddings.patch_embeddings.weight') ) rename_keys.append(('backbone.downsample_layers.0.0.bias', 'backbone.embeddings.patch_embeddings.bias') ) rename_keys.append(('backbone.downsample_layers.0.1.weight', 'backbone.embeddings.layernorm.weight') ) rename_keys.append(('backbone.downsample_layers.0.1.bias', 'backbone.embeddings.layernorm.bias') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F"""backbone.stages.{i}.{j}.gamma""", F"""backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.depthwise_conv.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.dwconv.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.depthwise_conv.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.dwconv.bias""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.norm.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.layernorm.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.norm.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.layernorm.bias""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv1.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv1.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv2.weight""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight""") ) rename_keys.append((F"""backbone.stages.{i}.{j}.pointwise_conv2.bias""", F"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias""") ) if i > 0: rename_keys.append((F"""backbone.downsample_layers.{i}.0.weight""", F"""backbone.encoder.stages.{i}.downsampling_layer.0.weight""") ) rename_keys.append((F"""backbone.downsample_layers.{i}.0.bias""", F"""backbone.encoder.stages.{i}.downsampling_layer.0.bias""") ) rename_keys.append((F"""backbone.downsample_layers.{i}.1.weight""", F"""backbone.encoder.stages.{i}.downsampling_layer.1.weight""") ) rename_keys.append((F"""backbone.downsample_layers.{i}.1.bias""", F"""backbone.encoder.stages.{i}.downsampling_layer.1.bias""") ) rename_keys.append((F"""backbone.norm{i}.weight""", F"""backbone.hidden_states_norms.stage{i+1}.weight""") ) rename_keys.append((F"""backbone.norm{i}.bias""", F"""backbone.hidden_states_norms.stage{i+1}.bias""") ) # decode head rename_keys.extend( [ ('decode_head.conv_seg.weight', 'decode_head.classifier.weight'), ('decode_head.conv_seg.bias', 'decode_head.classifier.bias'), ('auxiliary_head.conv_seg.weight', 'auxiliary_head.classifier.weight'), ('auxiliary_head.conv_seg.bias', 'auxiliary_head.classifier.bias'), ] ) # fmt: on return rename_keys def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: _lowercase : Any = dct.pop(SCREAMING_SNAKE_CASE ) _lowercase : Any = val def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: _lowercase : List[Any] = { 'upernet-convnext-tiny': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth', 'upernet-convnext-small': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth', 'upernet-convnext-base': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth', 'upernet-convnext-large': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth', 'upernet-convnext-xlarge': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth', } _lowercase : Optional[int] = model_name_to_url[model_name] _lowercase : str = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE , map_location='cpu' )['state_dict'] _lowercase : Optional[int] = get_upernet_config(SCREAMING_SNAKE_CASE ) _lowercase : Tuple = UperNetForSemanticSegmentation(SCREAMING_SNAKE_CASE ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): _lowercase : List[Any] = state_dict.pop(SCREAMING_SNAKE_CASE ) if "bn" in key: _lowercase : Any = key.replace('bn' , 'batch_norm' ) _lowercase : Any = val # rename keys _lowercase : int = create_rename_keys(SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) model.load_state_dict(SCREAMING_SNAKE_CASE ) # verify on image _lowercase : Union[str, Any] = 'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg' _lowercase : Any = Image.open(requests.get(SCREAMING_SNAKE_CASE , stream=SCREAMING_SNAKE_CASE ).raw ).convert('RGB' ) _lowercase : Tuple = SegformerImageProcessor() _lowercase : Tuple = processor(SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values with torch.no_grad(): _lowercase : Dict = model(SCREAMING_SNAKE_CASE ) if model_name == "upernet-convnext-tiny": _lowercase : Dict = torch.tensor( [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] ) elif model_name == "upernet-convnext-small": _lowercase : Union[str, Any] = torch.tensor( [[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]] ) elif model_name == "upernet-convnext-base": _lowercase : Dict = torch.tensor( [[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]] ) elif model_name == "upernet-convnext-large": _lowercase : Optional[int] = torch.tensor( [[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]] ) elif model_name == "upernet-convnext-xlarge": _lowercase : str = torch.tensor( [[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]] ) print('Logits:' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=1E-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(SCREAMING_SNAKE_CASE ) print(F"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(SCREAMING_SNAKE_CASE ) if push_to_hub: print(F"""Pushing model and processor for {model_name} to hub""" ) model.push_to_hub(F"""openmmlab/{model_name}""" ) processor.push_to_hub(F"""openmmlab/{model_name}""" ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="upernet-convnext-tiny", type=str, choices=[f'''upernet-convnext-{size}''' for size in ["tiny", "small", "base", "large", "xlarge"]], help="Name of the ConvNext UperNet model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) UpperCamelCase = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
66
import sys import turtle def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) if depth == 0: return triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) a_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') a_ : str = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
73
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def SCREAMING_SNAKE_CASE__ ( snake_case__ :str ) -> Tuple: _lowercase = 384 _lowercase = 7 if "tiny" in model_name: _lowercase = 96 _lowercase = (2, 2, 6, 2) _lowercase = (3, 6, 12, 24) elif "small" in model_name: _lowercase = 96 _lowercase = (2, 2, 18, 2) _lowercase = (3, 6, 12, 24) elif "base" in model_name: _lowercase = 128 _lowercase = (2, 2, 18, 2) _lowercase = (4, 8, 16, 32) _lowercase = 12 _lowercase = 512 elif "large" in model_name: _lowercase = 192 _lowercase = (2, 2, 18, 2) _lowercase = (6, 12, 24, 48) _lowercase = 12 _lowercase = 768 # set label information _lowercase = 150 _lowercase = 'huggingface/label-files' _lowercase = 'ade20k-id2label.json' _lowercase = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='dataset' ) , 'r' ) ) _lowercase = {int(snake_case__ ): v for k, v in idalabel.items()} _lowercase = {v: k for k, v in idalabel.items()} _lowercase = SwinConfig( embed_dim=snake_case__ , depths=snake_case__ , num_heads=snake_case__ , window_size=snake_case__ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) _lowercase = UperNetConfig( backbone_config=snake_case__ , auxiliary_in_channels=snake_case__ , num_labels=snake_case__ , idalabel=snake_case__ , labelaid=snake_case__ , ) return config def SCREAMING_SNAKE_CASE__ ( snake_case__ :Union[str, Any] ) -> List[Any]: _lowercase = [] # fmt: off # stem rename_keys.append(('backbone.patch_embed.projection.weight', 'backbone.embeddings.patch_embeddings.projection.weight') ) rename_keys.append(('backbone.patch_embed.projection.bias', 'backbone.embeddings.patch_embeddings.projection.bias') ) rename_keys.append(('backbone.patch_embed.norm.weight', 'backbone.embeddings.norm.weight') ) rename_keys.append(('backbone.patch_embed.norm.bias', 'backbone.embeddings.norm.bias') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.norm1.weight""", F"""backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight""") ) rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.norm1.bias""", F"""backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias""") ) rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table""", F"""backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table""") ) rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index""", F"""backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index""") ) rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight""", F"""backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight""") ) rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias""", F"""backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias""") ) rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.norm2.weight""", F"""backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight""") ) rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.norm2.bias""", F"""backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias""") ) rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight""", F"""backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight""") ) rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias""", F"""backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias""") ) rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight""", F"""backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight""") ) rename_keys.append((F"""backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias""", F"""backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias""") ) if i < 3: rename_keys.append((F"""backbone.stages.{i}.downsample.reduction.weight""", F"""backbone.encoder.layers.{i}.downsample.reduction.weight""") ) rename_keys.append((F"""backbone.stages.{i}.downsample.norm.weight""", F"""backbone.encoder.layers.{i}.downsample.norm.weight""") ) rename_keys.append((F"""backbone.stages.{i}.downsample.norm.bias""", F"""backbone.encoder.layers.{i}.downsample.norm.bias""") ) rename_keys.append((F"""backbone.norm{i}.weight""", F"""backbone.hidden_states_norms.stage{i+1}.weight""") ) rename_keys.append((F"""backbone.norm{i}.bias""", F"""backbone.hidden_states_norms.stage{i+1}.bias""") ) # decode head rename_keys.extend( [ ('decode_head.conv_seg.weight', 'decode_head.classifier.weight'), ('decode_head.conv_seg.bias', 'decode_head.classifier.bias'), ('auxiliary_head.conv_seg.weight', 'auxiliary_head.classifier.weight'), ('auxiliary_head.conv_seg.bias', 'auxiliary_head.classifier.bias'), ] ) # fmt: on return rename_keys def SCREAMING_SNAKE_CASE__ ( snake_case__ :Any , snake_case__ :List[Any] , snake_case__ :List[str] ) -> Any: _lowercase = dct.pop(snake_case__ ) _lowercase = val def SCREAMING_SNAKE_CASE__ ( snake_case__ :str , snake_case__ :Tuple ) -> Union[str, Any]: _lowercase = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): _lowercase = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) _lowercase = state_dict.pop(F"""backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight""" ) _lowercase = state_dict.pop(F"""backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict _lowercase = in_proj_weight[:dim, :] _lowercase = in_proj_bias[: dim] _lowercase = in_proj_weight[ dim : dim * 2, : ] _lowercase = in_proj_bias[ dim : dim * 2 ] _lowercase = in_proj_weight[ -dim :, : ] _lowercase = in_proj_bias[-dim :] # fmt: on def SCREAMING_SNAKE_CASE__ ( snake_case__ :str ) -> Optional[Any]: _lowercase , _lowercase = x.shape _lowercase = x.reshape(snake_case__ , 4 , in_channel // 4 ) _lowercase = x[:, [0, 2, 1, 3], :].transpose(1 , 2 ).reshape(snake_case__ , snake_case__ ) return x def SCREAMING_SNAKE_CASE__ ( snake_case__ :int ) -> List[Any]: _lowercase , _lowercase = x.shape _lowercase = x.reshape(snake_case__ , in_channel // 4 , 4 ) _lowercase = x[:, :, [0, 2, 1, 3]].transpose(1 , 2 ).reshape(snake_case__ , snake_case__ ) return x def SCREAMING_SNAKE_CASE__ ( snake_case__ :str ) -> Tuple: _lowercase = x.shape[0] _lowercase = x.reshape(4 , in_channel // 4 ) _lowercase = x[[0, 2, 1, 3], :].transpose(0 , 1 ).reshape(snake_case__ ) return x def SCREAMING_SNAKE_CASE__ ( snake_case__ :List[Any] ) -> Any: _lowercase = x.shape[0] _lowercase = x.reshape(in_channel // 4 , 4 ) _lowercase = x[:, [0, 2, 1, 3]].transpose(0 , 1 ).reshape(snake_case__ ) return x def SCREAMING_SNAKE_CASE__ ( snake_case__ :Optional[int] , snake_case__ :str , snake_case__ :Optional[Any] ) -> Optional[Any]: _lowercase = { 'upernet-swin-tiny': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth', 'upernet-swin-small': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth', 'upernet-swin-base': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth', 'upernet-swin-large': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth', } _lowercase = model_name_to_url[model_name] _lowercase = torch.hub.load_state_dict_from_url(snake_case__ , map_location='cpu' , file_name=snake_case__ )[ 'state_dict' ] for name, param in state_dict.items(): print(snake_case__ , param.shape ) _lowercase = get_upernet_config(snake_case__ ) _lowercase = UperNetForSemanticSegmentation(snake_case__ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): _lowercase = state_dict.pop(snake_case__ ) if "bn" in key: _lowercase = key.replace('bn' , 'batch_norm' ) _lowercase = val # rename keys _lowercase = create_rename_keys(snake_case__ ) for src, dest in rename_keys: rename_key(snake_case__ , snake_case__ , snake_case__ ) read_in_q_k_v(snake_case__ , config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: _lowercase = reverse_correct_unfold_reduction_order(snake_case__ ) if "norm" in key: _lowercase = reverse_correct_unfold_norm_order(snake_case__ ) model.load_state_dict(snake_case__ ) # verify on image _lowercase = 'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg' _lowercase = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ).convert('RGB' ) _lowercase = SegformerImageProcessor() _lowercase = processor(snake_case__ , return_tensors='pt' ).pixel_values with torch.no_grad(): _lowercase = model(snake_case__ ) _lowercase = outputs.logits print(logits.shape ) print('First values of logits:' , logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": _lowercase = torch.tensor( [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]] ) elif model_name == "upernet-swin-small": _lowercase = torch.tensor( [[-7.1921, -7.1921, -6.9532], [-7.1921, -7.1921, -6.9532], [-7.0908, -7.0908, -6.8534]] ) elif model_name == "upernet-swin-base": _lowercase = torch.tensor( [[-6.5851, -6.5851, -6.4330], [-6.5851, -6.5851, -6.4330], [-6.4763, -6.4763, -6.3254]] ) elif model_name == "upernet-swin-large": _lowercase = torch.tensor( [[-7.5297, -7.5297, -7.3802], [-7.5297, -7.5297, -7.3802], [-7.4044, -7.4044, -7.2586]] ) print('Logits:' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , snake_case__ , atol=1E-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case__ ) print(F"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(snake_case__ ) if push_to_hub: print(F"""Pushing model and processor for {model_name} to hub""" ) model.push_to_hub(F"""openmmlab/{model_name}""" ) processor.push_to_hub(F"""openmmlab/{model_name}""" ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""upernet-swin-tiny""", type=str, choices=[F"""upernet-swin-{size}""" for size in ["""tiny""", """small""", """base""", """large"""]], help="""Name of the Swin + UperNet model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) snake_case = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
67
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
0
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __A = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class _A ( unittest.TestCase ): """simple docstring""" def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Path , __SCREAMING_SNAKE_CASE : Union[str, None] = None , __SCREAMING_SNAKE_CASE : Union[List[str], None] = None , __SCREAMING_SNAKE_CASE : Union[str, List[str], None] = None , __SCREAMING_SNAKE_CASE : bool = True , ) -> List[str]: __UpperCAmelCase =[file for file in os.listdir(__SCREAMING_SNAKE_CASE ) if os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) )] if identifier is not None: __UpperCAmelCase =[file for file in files if identifier in file] if n_identifier is not None: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for n_ in n_identifier: __UpperCAmelCase =[file for file in files if n_ not in file] else: __UpperCAmelCase =[file for file in files if n_identifier not in file] __UpperCAmelCase =ignore_files or [] ignore_files.append("""__init__.py""" ) __UpperCAmelCase =[file for file in files if file not in ignore_files] for file in files: # Open all files print("""Testing""" , __SCREAMING_SNAKE_CASE ) if only_modules: __UpperCAmelCase =file.split(""".""" )[0] try: __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCAmelCase =doctest.DocTestSuite(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =unittest.TextTestRunner().run(__SCREAMING_SNAKE_CASE ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(f'''{module_identifier} is not a module.''' ) else: __UpperCAmelCase =doctest.testfile(str("""..""" / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def _a ( self : Optional[Any] ) -> List[str]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""modeling""" __UpperCAmelCase =[ """modeling_ctrl.py""", """modeling_tf_ctrl.py""", ] self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE ) def _a ( self : Tuple ) -> Optional[int]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""tokenization""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Optional[Any] ) -> Optional[Any]: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase ="""configuration""" self.analyze_directory(__SCREAMING_SNAKE_CASE , identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : List[Any] ) -> Tuple: __UpperCAmelCase =Path("""src/transformers""" ) __UpperCAmelCase =["""configuration""", """modeling""", """tokenization"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , n_identifier=__SCREAMING_SNAKE_CASE ) def _a ( self : Any ) -> Tuple: __UpperCAmelCase =Path("""docs/source""" ) __UpperCAmelCase =["""favicon.ico"""] self.analyze_directory(__SCREAMING_SNAKE_CASE , ignore_files=__SCREAMING_SNAKE_CASE , only_modules=__SCREAMING_SNAKE_CASE )
68
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
'''simple docstring''' import enum import shutil import sys a , a : List[str] = shutil.get_terminal_size() a : str = {'''UP''': '''A''', '''DOWN''': '''B''', '''RIGHT''': '''C''', '''LEFT''': '''D'''} class SCREAMING_SNAKE_CASE__ ( enum.Enum ): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1 def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : Tuple="" ) -> List[Any]: sys.stdout.write(str(_UpperCAmelCase ) + end ) sys.stdout.flush() def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : List[str]="" ) -> Optional[int]: forceWrite(F'''\u001b[{color}m{content}\u001b[0m''' , _UpperCAmelCase ) def __UpperCAmelCase ( ) -> Union[str, Any]: forceWrite("\r" ) def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : str ) -> Optional[Any]: forceWrite(F'''\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}''' ) def __UpperCAmelCase ( ) -> int: forceWrite(" " * TERMINAL_WIDTH ) reset_cursor() def __UpperCAmelCase ( ) -> Optional[int]: reset_cursor() forceWrite("-" * TERMINAL_WIDTH )
69
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path a_ : str = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def lowerCamelCase__ (_UpperCAmelCase=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=A__ ) ) class _snake_case ( A__ ): _lowercase : Optional[Any] = None _lowercase : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = dataset_module_factory(a , cache_dir=a) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=a) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=a , config_name=a , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=a).replace(os.sep , '/'), config.DATASET_INFO_FILENAME, ]) SCREAMING_SNAKE_CASE = cached_path(a , cache_dir=a) self.assertTrue(os.path.exists(a)) @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('test_hf_gcp') / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert "train" in ds assert isinstance(ds['train'] , _UpperCAmelCase) assert next(iter(ds['train']))
73
0
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class A( UpperCamelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase = FlaxAutoencoderKL @property def a__ ( self : Optional[int] ) -> List[str]: """simple docstring""" lowerCamelCase_ = 4 lowerCamelCase_ = 3 lowerCamelCase_ = (32, 32) lowerCamelCase_ = jax.random.PRNGKey(0 ) lowerCamelCase_ = jax.random.uniform(A_ , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def a__ ( self : List[str] ) -> List[str]: """simple docstring""" lowerCamelCase_ = { 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 4, } lowerCamelCase_ = self.dummy_input return init_dict, inputs_dict
70
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' def a__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ) -> float: """simple docstring""" UpperCAmelCase_ : Optional[int] = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def a__ ( ) -> Optional[int]: """simple docstring""" print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
71
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append('10000000') else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
0
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class __magic_name__ ( __SCREAMING_SNAKE_CASE ): @staticmethod @abstractmethod def _A( snake_case_ ): raise NotImplementedError() @abstractmethod def _A( self ): raise NotImplementedError()
72
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ (_UpperCAmelCase): return 1.0 / (1.0 + np.exp(-_outputs)) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=_UpperCAmelCase) SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_UpperCAmelCase) class _snake_case ( A__ ): _lowercase : Tuple = '''sigmoid''' _lowercase : List[str] = '''softmax''' _lowercase : Tuple = '''none''' @add_end_docstrings( A__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class _snake_case ( A__ ): _lowercase : Optional[Any] = False _lowercase : Tuple = ClassificationFunction.NONE def __init__( self , **a) -> Optional[Any]: super().__init__(**a) 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 , a=None , a=None , a="" , **a) -> Tuple: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" SCREAMING_SNAKE_CASE = tokenizer_kwargs SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , 'return_all_scores') and return_all_scores is None: SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(a , a) or top_k is None: SCREAMING_SNAKE_CASE = top_k SCREAMING_SNAKE_CASE = 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`.' , a , ) if return_all_scores: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = 1 if isinstance(a , a): SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *a , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = super().__call__(*a , **a) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE = 'top_k' not in kwargs if isinstance(args[0] , a) 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 , a , **a) -> Dict[str, GenericTensor]: SCREAMING_SNAKE_CASE = self.framework if isinstance(a , a): return self.tokenizer(**a , return_tensors=a , **a) elif isinstance(a , a) and len(a) == 1 and isinstance(inputs[0] , a) 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=a , **a) elif isinstance(a , a): # 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(a , return_tensors=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: return self.model(**a) def SCREAMING_SNAKE_CASE__ ( self , a , a=None , a=1 , a=True) -> Any: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply') and function_to_apply is None: SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE = ClassificationFunction.NONE SCREAMING_SNAKE_CASE = model_outputs['logits'][0] SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE = sigmoid(a) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE = softmax(a) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE = 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()} SCREAMING_SNAKE_CASE = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a) ] if not _legacy: dict_scores.sort(key=lambda a: x["score"] , reverse=a) if top_k is not None: SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
73
0
def a__ ( snake_case = 10 , snake_case = 22 ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = range(1 , snake_case ) __SCREAMING_SNAKE_CASE : List[Any] = range(1 , snake_case ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(f'''{solution(10, 22) = }''')
74
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' import os import jsonlines import numpy as np from tqdm import tqdm UpperCamelCase__ = 2_0_4_8 UpperCamelCase__ = 4_0_9_6 UpperCamelCase__ = 4_2 UpperCamelCase__ = os.environ.pop('''PROCESS_TRAIN''', '''false''') UpperCamelCase__ = {'''null''': 0, '''short''': 1, '''long''': 2, '''yes''': 3, '''no''': 4} def a__ ( lowerCAmelCase__ ) -> Optional[int]: def choose_first(lowerCAmelCase__ , lowerCAmelCase__=False ): assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) if len(lowerCAmelCase__ ) == 1: UpperCAmelCase__ : Optional[int] = answer[0] return {k: [answer[k]] for k in answer} if is_long_answer else answer for a in answer: if is_long_answer: UpperCAmelCase__ : Tuple = {k: [a[k]] for k in a} if len(a['''start_token'''] ) > 0: break return a UpperCAmelCase__ : List[Any] = {'''id''': example['''id''']} UpperCAmelCase__ : int = example['''annotations'''] UpperCAmelCase__ : Any = annotation['''yes_no_answer'''] if 0 in yes_no_answer or 1 in yes_no_answer: UpperCAmelCase__ : Union[str, Any] = ['''yes'''] if 1 in yes_no_answer else ['''no'''] UpperCAmelCase__ : int = [] UpperCAmelCase__ : Union[str, Any] = [] UpperCAmelCase__ : Dict = ['''<cls>'''] else: UpperCAmelCase__ : Tuple = ['''short'''] UpperCAmelCase__ : Optional[Any] = choose_first(annotation['''short_answers'''] ) if len(out['''start_token'''] ) == 0: # answer will be long if short is not available UpperCAmelCase__ : Dict = ['''long'''] UpperCAmelCase__ : List[str] = choose_first(annotation['''long_answer'''] , is_long_answer=lowerCAmelCase__ ) UpperCAmelCase__ : str = [] answer.update(lowerCAmelCase__ ) # disregard some samples if len(answer['''start_token'''] ) > 1 or answer["start_token"] == answer["end_token"]: UpperCAmelCase__ : Optional[int] = True else: UpperCAmelCase__ : Any = False UpperCAmelCase__ : str = ['''start_token''', '''end_token''', '''start_byte''', '''end_byte''', '''text'''] if not all(isinstance(answer[k] , lowerCAmelCase__ ) for k in cols ): raise ValueError('''Issue in ID''' , example['''id'''] ) return answer def a__ ( lowerCAmelCase__ , lowerCAmelCase__=False ) -> Optional[Any]: UpperCAmelCase__ : Union[str, Any] = _get_single_answer(lowerCAmelCase__ ) # bytes are of no use del answer["start_byte"] del answer["end_byte"] # handle yes_no answers explicitly if answer["category"][0] in ["yes", "no"]: # category is list with one element UpperCAmelCase__ : int = example['''document''']['''tokens'''] UpperCAmelCase__ : str = [] for i in range(len(doc['''token'''] ) ): if not doc["is_html"][i]: context.append(doc['''token'''][i] ) return { "context": " ".join(lowerCAmelCase__ ), "answer": { "start_token": -1_00, # ignore index in cross-entropy "end_token": -1_00, # ignore index in cross-entropy "category": answer["category"], "span": answer["category"], # extra }, } # later, help in removing all no answers if answer["start_token"] == [-1]: return { "context": "None", "answer": { "start_token": -1, "end_token": -1, "category": "null", "span": "None", # extra }, } # handling normal samples UpperCAmelCase__ : List[Any] = ['''start_token''', '''end_token'''] answer.update({k: answer[k][0] if len(answer[k] ) > 0 else answer[k] for k in cols} ) # e.g. [10] == 10 UpperCAmelCase__ : str = example['''document''']['''tokens'''] UpperCAmelCase__ : List[Any] = answer['''start_token'''] UpperCAmelCase__ : int = answer['''end_token'''] UpperCAmelCase__ : Union[str, Any] = [] for i in range(len(doc['''token'''] ) ): if not doc["is_html"][i]: context.append(doc['''token'''][i] ) else: if answer["start_token"] > i: start_token -= 1 if answer["end_token"] > i: end_token -= 1 UpperCAmelCase__ : Any = ''' '''.join(context[start_token:end_token] ) # checking above code if assertion: UpperCAmelCase__ : Any = doc['''is_html'''][answer['''start_token'''] : answer['''end_token''']] UpperCAmelCase__ : Union[str, Any] = doc['''token'''][answer['''start_token'''] : answer['''end_token''']] UpperCAmelCase__ : str = ''' '''.join([old[i] for i in range(len(lowerCAmelCase__ ) ) if not is_html[i]] ) if new != old: print('''ID:''' , example['''id'''] ) print('''New:''' , lowerCAmelCase__ , end='''\n''' ) print('''Old:''' , lowerCAmelCase__ , end='''\n\n''' ) return { "context": " ".join(lowerCAmelCase__ ), "answer": { "start_token": start_token, "end_token": end_token - 1, # this makes it inclusive "category": answer["category"], # either long or short "span": new, # extra }, } def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=20_48 , lowerCAmelCase__=40_96 , lowerCAmelCase__=True ) -> Dict: # overlap will be of doc_stride - q_len UpperCAmelCase__ : Any = get_context_and_ans(lowerCAmelCase__ , assertion=lowerCAmelCase__ ) UpperCAmelCase__ : Union[str, Any] = out['''answer'''] # later, removing these samples if answer["start_token"] == -1: return { "example_id": example["id"], "input_ids": [[-1]], "labels": { "start_token": [-1], "end_token": [-1], "category": ["null"], }, } UpperCAmelCase__ : str = tokenizer(example['''question''']['''text'''] , out['''context'''] ).input_ids UpperCAmelCase__ : Optional[Any] = input_ids.index(tokenizer.sep_token_id ) + 1 # return yes/no if answer["category"][0] in ["yes", "no"]: # category is list with one element UpperCAmelCase__ : List[Any] = [] UpperCAmelCase__ : Optional[Any] = [] UpperCAmelCase__ : int = input_ids[:q_len] UpperCAmelCase__ : Any = range(lowerCAmelCase__ , len(lowerCAmelCase__ ) , max_length - doc_stride ) for i in doc_start_indices: UpperCAmelCase__ : Tuple = i + max_length - q_len UpperCAmelCase__ : Optional[Any] = input_ids[i:end_index] inputs.append(q_indices + slice ) category.append(answer['''category'''][0] ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": [-1_00] * len(lowerCAmelCase__ ), "end_token": [-1_00] * len(lowerCAmelCase__ ), "category": category, }, } UpperCAmelCase__ : Any = out['''context'''].split() UpperCAmelCase__ : Any = splitted_context[answer['''end_token''']] UpperCAmelCase__ : Dict = len( tokenizer( ''' '''.join(splitted_context[: answer['''start_token''']] ) , add_special_tokens=lowerCAmelCase__ , ).input_ids ) UpperCAmelCase__ : Optional[Any] = len( tokenizer(''' '''.join(splitted_context[: answer['''end_token''']] ) , add_special_tokens=lowerCAmelCase__ ).input_ids ) answer["start_token"] += q_len answer["end_token"] += q_len # fixing end token UpperCAmelCase__ : Union[str, Any] = len(tokenizer(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ).input_ids ) if num_sub_tokens > 1: answer["end_token"] += num_sub_tokens - 1 UpperCAmelCase__ : Dict = input_ids[answer['''start_token'''] : answer['''end_token'''] + 1] # right & left are inclusive UpperCAmelCase__ : List[Any] = answer['''start_token'''] UpperCAmelCase__ : Any = answer['''end_token'''] if assertion: UpperCAmelCase__ : List[Any] = tokenizer.decode(lowerCAmelCase__ ) if answer["span"] != new: print('''ISSUE IN TOKENIZATION''' ) print('''OLD:''' , answer['''span'''] ) print('''NEW:''' , lowerCAmelCase__ , end='''\n\n''' ) if len(lowerCAmelCase__ ) <= max_length: return { "example_id": example["id"], "input_ids": [input_ids], "labels": { "start_token": [answer["start_token"]], "end_token": [answer["end_token"]], "category": answer["category"], }, } UpperCAmelCase__ : Optional[Any] = input_ids[:q_len] UpperCAmelCase__ : Any = range(lowerCAmelCase__ , len(lowerCAmelCase__ ) , max_length - doc_stride ) UpperCAmelCase__ : Any = [] UpperCAmelCase__ : Union[str, Any] = [] UpperCAmelCase__ : List[str] = [] UpperCAmelCase__ : Optional[int] = [] # null, yes, no, long, short for i in doc_start_indices: UpperCAmelCase__ : List[str] = i + max_length - q_len UpperCAmelCase__ : Optional[int] = input_ids[i:end_index] inputs.append(q_indices + slice ) assert len(inputs[-1] ) <= max_length, "Issue in truncating length" if start_token >= i and end_token <= end_index - 1: UpperCAmelCase__ : List[Any] = start_token - i + q_len UpperCAmelCase__ : List[str] = end_token - i + q_len answers_category.append(answer['''category'''][0] ) # ["short"] -> "short" else: UpperCAmelCase__ : Union[str, Any] = -1_00 UpperCAmelCase__ : Tuple = -1_00 answers_category.append('''null''' ) UpperCAmelCase__ : List[Any] = inputs[-1][start_token : end_token + 1] answers_start_token.append(lowerCAmelCase__ ) answers_end_token.append(lowerCAmelCase__ ) if assertion: if new != old and new != [tokenizer.cls_token_id]: print('''ISSUE in strided for ID:''' , example['''id'''] ) print('''New:''' , tokenizer.decode(lowerCAmelCase__ ) ) print('''Old:''' , tokenizer.decode(lowerCAmelCase__ ) , end='''\n\n''' ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": answers_start_token, "end_token": answers_end_token, "category": answers_category, }, } def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=20_48 , lowerCAmelCase__=40_96 , lowerCAmelCase__=False ) -> int: UpperCAmelCase__ : Any = get_strided_contexts_and_ans( lowerCAmelCase__ , lowerCAmelCase__ , doc_stride=lowerCAmelCase__ , max_length=lowerCAmelCase__ , assertion=lowerCAmelCase__ , ) return example def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ) -> str: with jsonlines.open(lowerCAmelCase__ , '''a''' ) as writer: for example in tqdm(lowerCAmelCase__ , total=len(lowerCAmelCase__ ) , desc='''Saving samples ... ''' ): UpperCAmelCase__ : Dict = example['''labels'''] for ids, start, end, cat in zip( example['''input_ids'''] , labels['''start_token'''] , labels['''end_token'''] , labels['''category'''] , ): if start == -1 and end == -1: continue # leave waste samples with no answer if cat == "null" and np.random.rand() < 0.6: continue # removing 50 % samples writer.write( { '''input_ids''': ids, '''start_token''': start, '''end_token''': end, '''category''': CATEGORY_MAPPING[cat], } ) if __name__ == "__main__": from datasets import load_dataset from transformers import BigBirdTokenizer UpperCamelCase__ = load_dataset('''natural_questions''') UpperCamelCase__ = BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''') UpperCamelCase__ = data['''train''' if PROCESS_TRAIN == '''true''' else '''validation'''] UpperCamelCase__ = { '''tokenizer''': tokenizer, '''doc_stride''': DOC_STRIDE, '''max_length''': MAX_LENGTH, '''assertion''': False, } UpperCamelCase__ = data.map(prepare_inputs, fn_kwargs=fn_kwargs) UpperCamelCase__ = data.remove_columns(['''annotations''', '''document''', '''id''', '''question''']) print(data) np.random.seed(SEED) UpperCamelCase__ = '''nq-training.jsonl''' if PROCESS_TRAIN == '''true''' else '''nq-validation.jsonl''' save_to_disk(data, file_name=cache_file_name)
75
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
0
"""simple docstring""" from __future__ import annotations a_ = [True] * 1_0_0_0_0_0_1 a_ = 2 while i * i <= 1_0_0_0_0_0_0: if seive[i]: for j in range(i * i, 1_0_0_0_0_0_1, i): a_ = False i += 1 def __UpperCAmelCase ( __UpperCamelCase ): return seive[n] def __UpperCAmelCase ( __UpperCamelCase ): return any(digit in '''02468''' for digit in str(__UpperCamelCase ) ) def __UpperCAmelCase ( __UpperCamelCase = 1_00_00_00 ): __lowercase : int = [2] # result already includes the number 2. for num in range(3 , limit + 1 , 2 ): if is_prime(__UpperCamelCase ) and not contains_an_even_digit(__UpperCamelCase ): __lowercase : Dict = str(__UpperCamelCase ) __lowercase : Dict = [int(str_num[j:] + str_num[:j] ) for j in range(len(__UpperCamelCase ) )] if all(is_prime(__UpperCamelCase ) for i in list_nums ): result.append(__UpperCamelCase ) return result def __UpperCAmelCase ( ): return len(find_circular_primes() ) if __name__ == "__main__": print(F"{len(find_circular_primes()) = }")
76
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''decision_transformer''' _lowercase : str = ['''past_key_values'''] _lowercase : Union[str, Any] = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=17 , a=4 , a=128 , a=4096 , a=True , a=1 , a=1024 , a=3 , a=1 , a=None , a="relu" , a=0.1 , a=0.1 , a=0.1 , a=1E-5 , a=0.02 , a=True , a=True , a=5_0256 , a=5_0256 , a=False , a=False , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=a , eos_token_id=a , **a)
73
0
"""simple docstring""" import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class a__ ( unittest.TestCase ): def __init__( self : Tuple , UpperCamelCase_ : Optional[Any]): """simple docstring""" __UpperCAmelCase : Tuple = parent def a_ ( self : Dict): """simple docstring""" return {} def _UpperCamelCase ( ) -> Dict: """simple docstring""" __UpperCAmelCase : List[Any] = "<HTML>\n\n <HEAD>\n <TITLE>sample document</TITLE>\n </HEAD>\n\n <BODY BGCOLOR=\"FFFFFF\">\n <HR>\n <a href=\"http://google.com\">Goog</a>\n <H1>This is one header</H1>\n <H2>This is a another Header</H2>\n <P>Travel from\n <P>\n <B>SFO to JFK</B>\n <BR>\n <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>\n <HR>\n <div style=\"color:#0000FF\">\n <h3>Traveler <b> name </b> is\n <p> John Doe </p>\n </div>" __UpperCAmelCase : List[str] = "\n <!DOCTYPE html>\n <html>\n <body>\n\n <h1>My First Heading</h1>\n <p>My first paragraph.</p>\n\n </body>\n </html>\n " return [html_string_a, html_string_a] @require_bsa class a__ ( __magic_name__ , unittest.TestCase ): lowercase_ = MarkupLMFeatureExtractor if is_bsa_available() else None def a_ ( self : Any): """simple docstring""" __UpperCAmelCase : List[str] = MarkupLMFeatureExtractionTester(self) @property def a_ ( self : Tuple): """simple docstring""" return self.feature_extract_tester.prepare_feat_extract_dict() def a_ ( self : Optional[int]): """simple docstring""" __UpperCAmelCase : List[Any] = self.feature_extraction_class() # Test not batched input __UpperCAmelCase : Tuple = get_html_strings()[0] __UpperCAmelCase : Tuple = feature_extractor(UpperCamelCase_) # fmt: off __UpperCAmelCase : Dict = [["sample document", "Goog", "This is one header", "This is a another Header", "Travel from", "SFO to JFK", "on May 2, 2015 at 2:00 pm. For details go to confirm.com", "Traveler", "name", "is", "John Doe"]] __UpperCAmelCase : List[Any] = [["/html/head/title", "/html/body/a", "/html/body/h1", "/html/body/h2", "/html/body/p", "/html/body/p/p/b[1]", "/html/body/p/p/b[2]/i", "/html/body/p/p/div/h3", "/html/body/p/p/div/h3/b", "/html/body/p/p/div/h3", "/html/body/p/p/div/h3/p"]] # fmt: on self.assertEqual(encoding.nodes , UpperCamelCase_) self.assertEqual(encoding.xpaths , UpperCamelCase_) # Test batched __UpperCAmelCase : Optional[int] = get_html_strings() __UpperCAmelCase : str = feature_extractor(UpperCamelCase_) # fmt: off __UpperCAmelCase : Optional[int] = expected_nodes + [["My First Heading", "My first paragraph."]] __UpperCAmelCase : int = expected_xpaths + [["/html/body/h1", "/html/body/p"]] self.assertEqual(len(encoding.nodes) , 2) self.assertEqual(len(encoding.xpaths) , 2) self.assertEqual(encoding.nodes , UpperCamelCase_) self.assertEqual(encoding.xpaths , UpperCamelCase_)
77
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[int] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# SCREAMING_SNAKE_CASE_: Dict =[ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] SCREAMING_SNAKE_CASE_: Union[str, Any] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks SCREAMING_SNAKE_CASE_: Any =f"down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 SCREAMING_SNAKE_CASE_: Optional[Any] =f"down_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: List[str] =f"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks SCREAMING_SNAKE_CASE_: Union[str, Any] =f"up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Any =f"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: Optional[int] =f"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 SCREAMING_SNAKE_CASE_: Union[str, Any] =f"down_blocks.{i}.downsamplers.0.conv." SCREAMING_SNAKE_CASE_: Union[str, Any] =f"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[Any] =f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) SCREAMING_SNAKE_CASE_: int ='mid_block.attentions.0.' SCREAMING_SNAKE_CASE_: List[Any] ='middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"mid_block.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: UpperCAmelCase_ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"encoder.down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: int =f"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: SCREAMING_SNAKE_CASE_: int =f"down_blocks.{i}.downsamplers.0." SCREAMING_SNAKE_CASE_: str =f"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[str] =f"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): SCREAMING_SNAKE_CASE_: List[str] =f"decoder.up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Dict =f"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): SCREAMING_SNAKE_CASE_: Any =f"mid_block.resnets.{i}." SCREAMING_SNAKE_CASE_: Tuple =f"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def lowerCAmelCase_ ( snake_case_ : Tuple ) -> Tuple: '''simple docstring''' return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: vae_state_dict[k] for k, v in mapping.items()} UpperCAmelCase_ = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) UpperCAmelCase_ = reshape_weight_for_sd(snake_case_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] SCREAMING_SNAKE_CASE_: Dict ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} SCREAMING_SNAKE_CASE_: str =re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp SCREAMING_SNAKE_CASE_: List[Any] ={'q': 0, 'k': 1, 'v': 2} def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): UpperCAmelCase_ = k[: -len(".q_proj.weight" )] UpperCAmelCase_ = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): UpperCAmelCase_ = k[: -len(".q_proj.bias" )] UpperCAmelCase_ = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) return new_state_dict def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return text_enc_dict if __name__ == "__main__": SCREAMING_SNAKE_CASE_: str =argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) SCREAMING_SNAKE_CASE_: Dict =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors SCREAMING_SNAKE_CASE_: Any =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Dict =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Union[str, Any] =osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): SCREAMING_SNAKE_CASE_: Union[str, Any] =load_file(unet_path, device='cpu') else: SCREAMING_SNAKE_CASE_: int =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: Dict =torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(vae_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: str =torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(text_enc_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') SCREAMING_SNAKE_CASE_: Any =torch.load(text_enc_path, map_location='cpu') # Convert the UNet model SCREAMING_SNAKE_CASE_: List[Any] =convert_unet_state_dict(unet_state_dict) SCREAMING_SNAKE_CASE_: Any ={'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model SCREAMING_SNAKE_CASE_: List[Any] =convert_vae_state_dict(vae_state_dict) SCREAMING_SNAKE_CASE_: Dict ={'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper SCREAMING_SNAKE_CASE_: Dict ='text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm SCREAMING_SNAKE_CASE_: Any ={'transformer.' + k: v for k, v in text_enc_dict.items()} SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict_vaa(text_enc_dict) SCREAMING_SNAKE_CASE_: int ={'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict(text_enc_dict) SCREAMING_SNAKE_CASE_: Optional[int] ={'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint SCREAMING_SNAKE_CASE_: List[str] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: SCREAMING_SNAKE_CASE_: List[str] ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: SCREAMING_SNAKE_CASE_: str ={'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
78
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
SCREAMING_SNAKE_CASE__ : Union[str, Any] = """0.21.0""" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
79
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): if radian_mode: return [magnitude * cos(_UpperCAmelCase), magnitude * sin(_UpperCAmelCase)] return [magnitude * cos(radians(_UpperCAmelCase)), magnitude * sin(radians(_UpperCAmelCase))] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 10**-1): SCREAMING_SNAKE_CASE = cross(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(_UpperCAmelCase) return abs(_UpperCAmelCase) < eps if __name__ == "__main__": # Test to check if it works a_ : int = array( [ polar_force(718.4, 1_80 - 30), polar_force(879.54, 45), polar_force(1_00, -90), ] ) a_ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg a_ : Dict = array( [ polar_force(30 * 9.81, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) a_ : Any = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg a_ : int = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) a_ : Optional[Any] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
0
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand __UpperCamelCase : Optional[int] = ( """4S 3H 2C 7S 5H""", """9D 8H 2C 6S 7H""", """2D 6D 9D TH 7D""", """TC 8C 2S JH 6C""", """JH 8S TH AH QH""", """TS KS 5S 9S AC""", """KD 6S 9D TH AD""", """KS 8D 4D 9S 4S""", # pair """8C 4S KH JS 4D""", # pair """QH 8H KD JH 8S""", # pair """KC 4H KS 2H 8D""", # pair """KD 4S KC 3H 8S""", # pair """AH 8S AS KC JH""", # pair """3H 4C 4H 3S 2H""", # 2 pairs """5S 5D 2C KH KH""", # 2 pairs """3C KH 5D 5S KH""", # 2 pairs """AS 3C KH AD KH""", # 2 pairs """7C 7S 3S 7H 5S""", # 3 of a kind """7C 7S KH 2H 7H""", # 3 of a kind """AC KH QH AH AS""", # 3 of a kind """2H 4D 3C AS 5S""", # straight (low ace) """3C 5C 4C 2C 6H""", # straight """6S 8S 7S 5H 9H""", # straight """JS QS 9H TS KH""", # straight """QC KH TS JS AH""", # straight (high ace) """8C 9C 5C 3C TC""", # flush """3S 8S 9S 5S KS""", # flush """4C 5C 9C 8C KC""", # flush """JH 8H AH KH QH""", # flush """3D 2H 3H 2C 2D""", # full house """2H 2C 3S 3H 3D""", # full house """KH KC 3S 3H 3D""", # full house """JC 6H JS JD JH""", # 4 of a kind """JC 7H JS JD JH""", # 4 of a kind """JC KH JS JD JH""", # 4 of a kind """2S AS 4S 5S 3S""", # straight flush (low ace) """2D 6D 3D 4D 5D""", # straight flush """5C 6C 3C 7C 4C""", # straight flush """JH 9H TH KH QH""", # straight flush """JH AH TH KH QH""", # royal flush (high ace straight flush) ) __UpperCamelCase : str = ( ("""2H 3H 4H 5H 6H""", """KS AS TS QS JS""", """Loss"""), ("""2H 3H 4H 5H 6H""", """AS AD AC AH JD""", """Win"""), ("""AS AH 2H AD AC""", """JS JD JC JH 3D""", """Win"""), ("""2S AH 2H AS AC""", """JS JD JC JH AD""", """Loss"""), ("""2S AH 2H AS AC""", """2H 3H 5H 6H 7H""", """Win"""), ("""AS 3S 4S 8S 2S""", """2H 3H 5H 6H 7H""", """Win"""), ("""2H 3H 5H 6H 7H""", """2S 3H 4H 5S 6C""", """Win"""), ("""2S 3H 4H 5S 6C""", """3D 4C 5H 6H 2S""", """Tie"""), ("""2S 3H 4H 5S 6C""", """AH AC 5H 6H AS""", """Win"""), ("""2S 2H 4H 5S 4C""", """AH AC 5H 6H AS""", """Loss"""), ("""2S 2H 4H 5S 4C""", """AH AC 5H 6H 7S""", """Win"""), ("""6S AD 7H 4S AS""", """AH AC 5H 6H 7S""", """Loss"""), ("""2S AH 4H 5S KC""", """AH AC 5H 6H 7S""", """Loss"""), ("""2S 3H 6H 7S 9C""", """7H 3C TH 6H 9S""", """Loss"""), ("""4S 5H 6H TS AC""", """3S 5H 6H TS AC""", """Win"""), ("""2S AH 4H 5S 6C""", """AD 4C 5H 6H 2C""", """Tie"""), ("""AS AH 3H AD AC""", """AS AH 2H AD AC""", """Win"""), ("""AH AC 5H 5C QS""", """AH AC 5H 5C KS""", """Loss"""), ("""AH AC 5H 5C QS""", """KH KC 5H 5C QS""", """Win"""), ("""7C 7S KH 2H 7H""", """3C 3S AH 2H 3H""", """Win"""), ("""3C 3S AH 2H 3H""", """7C 7S KH 2H 7H""", """Loss"""), ("""6H 5H 4H 3H 2H""", """5H 4H 3H 2H AH""", """Win"""), ("""5H 4H 3H 2H AH""", """5H 4H 3H 2H AH""", """Tie"""), ("""5H 4H 3H 2H AH""", """6H 5H 4H 3H 2H""", """Loss"""), ("""AH AD KS KC AC""", """AH KD KH AC KC""", """Win"""), ("""2H 4D 3C AS 5S""", """2H 4D 3C 6S 5S""", """Loss"""), ("""2H 3S 3C 3H 2S""", """3S 3C 2S 2H 2D""", """Win"""), ("""4D 6D 5D 2D JH""", """3S 8S 3H TC KH""", """Loss"""), ("""4S 6C 8S 3S 7S""", """AD KS 2D 7D 7C""", """Loss"""), ("""6S 4C 7H 8C 3H""", """5H JC AH 9D 9C""", """Loss"""), ("""9D 9H JH TC QH""", """3C 2S JS 5C 7H""", """Win"""), ("""2H TC 8S AD 9S""", """4H TS 7H 2C 5C""", """Win"""), ("""9D 3S 2C 7S 7C""", """JC TD 3C TC 9H""", """Loss"""), ) __UpperCamelCase : Union[str, Any] = ( ("""2H 3H 4H 5H 6H""", True), ("""AS AH 2H AD AC""", False), ("""2H 3H 5H 6H 7H""", True), ("""KS AS TS QS JS""", True), ("""8H 9H QS JS TH""", False), ("""AS 3S 4S 8S 2S""", True), ) __UpperCamelCase : List[Any] = ( ("""2H 3H 4H 5H 6H""", True), ("""AS AH 2H AD AC""", False), ("""2H 3H 5H 6H 7H""", False), ("""KS AS TS QS JS""", True), ("""8H 9H QS JS TH""", True), ) __UpperCamelCase : List[str] = ( ("""2H 4D 3C AS 5S""", True, [5, 4, 3, 2, 14]), ("""2H 5D 3C AS 5S""", False, [14, 5, 5, 3, 2]), ("""JH QD KC AS TS""", False, [14, 13, 12, 11, 10]), ("""9D 3S 2C 7S 7C""", False, [9, 7, 7, 3, 2]), ) __UpperCamelCase : List[Any] = ( ("""JH AH TH KH QH""", 0), ("""JH 9H TH KH QH""", 0), ("""JC KH JS JD JH""", 7), ("""KH KC 3S 3H 3D""", 6), ("""8C 9C 5C 3C TC""", 0), ("""JS QS 9H TS KH""", 0), ("""7C 7S KH 2H 7H""", 3), ("""3C KH 5D 5S KH""", 2), ("""QH 8H KD JH 8S""", 1), ("""2D 6D 9D TH 7D""", 0), ) __UpperCamelCase : Any = ( ("""JH AH TH KH QH""", 23), ("""JH 9H TH KH QH""", 22), ("""JC KH JS JD JH""", 21), ("""KH KC 3S 3H 3D""", 20), ("""8C 9C 5C 3C TC""", 19), ("""JS QS 9H TS KH""", 18), ("""7C 7S KH 2H 7H""", 17), ("""3C KH 5D 5S KH""", 16), ("""QH 8H KD JH 8S""", 15), ("""2D 6D 9D TH 7D""", 14), ) def snake_case ( ): '''simple docstring''' __lowercase , __lowercase = randrange(len(lowerCamelCase ) ), randrange(len(lowerCamelCase ) ) __lowercase = ["""Loss""", """Tie""", """Win"""][(play >= oppo) + (play > oppo)] __lowercase , __lowercase = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def snake_case ( lowerCamelCase = 100 ): '''simple docstring''' return (generate_random_hand() for _ in range(lowerCamelCase )) @pytest.mark.parametrize("""hand, expected""" , lowerCamelCase ) def snake_case ( lowerCamelCase , lowerCamelCase ): '''simple docstring''' assert PokerHand(lowerCamelCase )._is_flush() == expected @pytest.mark.parametrize("""hand, expected""" , lowerCamelCase ) def snake_case ( lowerCamelCase , lowerCamelCase ): '''simple docstring''' assert PokerHand(lowerCamelCase )._is_straight() == expected @pytest.mark.parametrize("""hand, expected, card_values""" , lowerCamelCase ) def snake_case ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): '''simple docstring''' __lowercase = PokerHand(lowerCamelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("""hand, expected""" , lowerCamelCase ) def snake_case ( lowerCamelCase , lowerCamelCase ): '''simple docstring''' assert PokerHand(lowerCamelCase )._is_same_kind() == expected @pytest.mark.parametrize("""hand, expected""" , lowerCamelCase ) def snake_case ( lowerCamelCase , lowerCamelCase ): '''simple docstring''' assert PokerHand(lowerCamelCase )._hand_type == expected @pytest.mark.parametrize("""hand, other, expected""" , lowerCamelCase ) def snake_case ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): '''simple docstring''' assert PokerHand(lowerCamelCase ).compare_with(PokerHand(lowerCamelCase ) ) == expected @pytest.mark.parametrize("""hand, other, expected""" , generate_random_hands() ) def snake_case ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): '''simple docstring''' assert PokerHand(lowerCamelCase ).compare_with(PokerHand(lowerCamelCase ) ) == expected def snake_case ( ): '''simple docstring''' __lowercase = [PokerHand(lowerCamelCase ) for hand in SORTED_HANDS] __lowercase = poker_hands.copy() shuffle(lowerCamelCase ) __lowercase = chain(sorted(lowerCamelCase ) ) for index, hand in enumerate(lowerCamelCase ): assert hand == poker_hands[index] def snake_case ( ): '''simple docstring''' __lowercase = [PokerHand("""2D AC 3H 4H 5S""" ), PokerHand("""2S 3H 4H 5S 6C""" )] pokerhands.sort(reverse=lowerCamelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def snake_case ( ): '''simple docstring''' __lowercase = PokerHand("""2C 4S AS 3D 5C""" ) __lowercase = True __lowercase = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def snake_case ( ): '''simple docstring''' __lowercase = 0 __lowercase = os.path.abspath(os.path.dirname(lowerCamelCase ) ) __lowercase = os.path.join(lowerCamelCase , """poker_hands.txt""" ) with open(lowerCamelCase ) as file_hand: for line in file_hand: __lowercase = line[:14].strip() __lowercase = line[15:].strip() __lowercase , __lowercase = PokerHand(lowerCamelCase ), PokerHand(lowerCamelCase ) __lowercase = player.compare_with(lowerCamelCase ) if output == "Win": answer += 1 assert answer == 376
80
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : int = { '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 _snake_case ( A__ ): _lowercase : Dict = '''cvt''' def __init__( self , a=3 , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[64, 192, 384] , a=[1, 3, 6] , a=[1, 2, 10] , a=[4.0, 4.0, 4.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.1] , a=[True, True, True] , a=[False, False, True] , a=["dw_bn", "dw_bn", "dw_bn"] , a=[3, 3, 3] , a=[1, 1, 1] , a=[2, 2, 2] , a=[1, 1, 1] , a=[1, 1, 1] , a=0.02 , a=1E-12 , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = drop_rate SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = qkv_projection_method SCREAMING_SNAKE_CASE = kernel_qkv SCREAMING_SNAKE_CASE = padding_kv SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = padding_q SCREAMING_SNAKE_CASE = stride_q SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps
73
0
import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : Optional[int] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __snake_case ( self : Union[str, Any] ) -> Tuple: __snake_case : List[Any] = 1 __snake_case : Any = 3 __snake_case : str = (32, 32) __snake_case : Optional[Any] = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowerCamelCase ) return image @property def __snake_case ( self : List[Any] ) -> Union[str, Any]: torch.manual_seed(0 ) __snake_case : int = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def __snake_case ( self : List[str] ) -> Optional[Any]: torch.manual_seed(0 ) __snake_case : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def __snake_case ( self : int ) -> Any: torch.manual_seed(0 ) __snake_case : Optional[Any] = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5006 , ) return RobertaSeriesModelWithTransformation(lowerCamelCase ) @property def __snake_case ( self : int ) -> Any: def extract(*lowerCamelCase : int , **lowerCamelCase : Any ): class a : """simple docstring""" def __init__( self : Tuple ) -> int: __snake_case : List[Any] = torch.ones([0] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[str] ) -> Dict: self.pixel_values.to(lowerCamelCase ) return self return Out() return extract def __snake_case ( self : Tuple ) -> Tuple: __snake_case : List[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator __snake_case : Optional[Any] = self.dummy_cond_unet __snake_case : Dict = PNDMScheduler(skip_prk_steps=lowerCamelCase ) __snake_case : List[Any] = self.dummy_vae __snake_case : Optional[int] = self.dummy_text_encoder __snake_case : int = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) __snake_case : List[Any] = 77 __snake_case : int = self.dummy_image.to(lowerCamelCase ) __snake_case : str = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk __snake_case : Dict = AltDiffusionImgaImgPipeline( unet=lowerCamelCase , scheduler=lowerCamelCase , vae=lowerCamelCase , text_encoder=lowerCamelCase , tokenizer=lowerCamelCase , safety_checker=lowerCamelCase , feature_extractor=self.dummy_extractor , ) __snake_case : List[str] = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=lowerCamelCase ) __snake_case : Any = alt_pipe.to(lowerCamelCase ) alt_pipe.set_progress_bar_config(disable=lowerCamelCase ) __snake_case : str = "A painting of a squirrel eating a burger" __snake_case : Optional[int] = torch.Generator(device=lowerCamelCase ).manual_seed(0 ) __snake_case : Any = alt_pipe( [prompt] , generator=lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=lowerCamelCase , ) __snake_case : Dict = output.images __snake_case : Tuple = torch.Generator(device=lowerCamelCase ).manual_seed(0 ) __snake_case : Dict = alt_pipe( [prompt] , generator=lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=lowerCamelCase , return_dict=lowerCamelCase , )[0] __snake_case : int = image[0, -3:, -3:, -1] __snake_case : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __snake_case : Tuple = np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5E-3 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def __snake_case ( self : int ) -> Optional[int]: __snake_case : Optional[int] = self.dummy_cond_unet __snake_case : Union[str, Any] = PNDMScheduler(skip_prk_steps=lowerCamelCase ) __snake_case : Optional[int] = self.dummy_vae __snake_case : Optional[int] = self.dummy_text_encoder __snake_case : Union[str, Any] = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) __snake_case : List[str] = 77 __snake_case : Optional[int] = self.dummy_image.to(lowerCamelCase ) # put models in fp16 __snake_case : str = unet.half() __snake_case : Dict = vae.half() __snake_case : int = bert.half() # make sure here that pndm scheduler skips prk __snake_case : int = AltDiffusionImgaImgPipeline( unet=lowerCamelCase , scheduler=lowerCamelCase , vae=lowerCamelCase , text_encoder=lowerCamelCase , tokenizer=lowerCamelCase , safety_checker=lowerCamelCase , feature_extractor=self.dummy_extractor , ) __snake_case : List[str] = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=lowerCamelCase ) __snake_case : Dict = alt_pipe.to(lowerCamelCase ) alt_pipe.set_progress_bar_config(disable=lowerCamelCase ) __snake_case : int = "A painting of a squirrel eating a burger" __snake_case : int = torch.manual_seed(0 ) __snake_case : int = alt_pipe( [prompt] , generator=lowerCamelCase , num_inference_steps=2 , output_type="np" , image=lowerCamelCase , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def __snake_case ( self : Any ) -> List[str]: __snake_case : str = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) # resize to resolution that is divisible by 8 but not 16 or 32 __snake_case : Any = init_image.resize((760, 504) ) __snake_case : Optional[Any] = "BAAI/AltDiffusion" __snake_case : List[str] = AltDiffusionImgaImgPipeline.from_pretrained( lowerCamelCase , safety_checker=lowerCamelCase , ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) pipe.enable_attention_slicing() __snake_case : Dict = "A fantasy landscape, trending on artstation" __snake_case : int = torch.manual_seed(0 ) __snake_case : Dict = pipe( prompt=lowerCamelCase , image=lowerCamelCase , strength=0.75 , guidance_scale=7.5 , generator=lowerCamelCase , output_type="np" , ) __snake_case : Optional[Any] = output.images[0] __snake_case : Dict = image[255:258, 383:386, -1] assert image.shape == (504, 760, 3) __snake_case : Any = np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[Any] ) -> List[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Optional[Any] ) -> int: __snake_case : Optional[int] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) __snake_case : str = init_image.resize((768, 512) ) __snake_case : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy" ) __snake_case : Any = "BAAI/AltDiffusion" __snake_case : Any = AltDiffusionImgaImgPipeline.from_pretrained( lowerCamelCase , safety_checker=lowerCamelCase , ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) pipe.enable_attention_slicing() __snake_case : Optional[Any] = "A fantasy landscape, trending on artstation" __snake_case : Optional[Any] = torch.manual_seed(0 ) __snake_case : Optional[Any] = pipe( prompt=lowerCamelCase , image=lowerCamelCase , strength=0.75 , guidance_scale=7.5 , generator=lowerCamelCase , output_type="np" , ) __snake_case : Union[str, Any] = output.images[0] assert image.shape == (512, 768, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1E-2
81
def lowerCamelCase__ (_UpperCAmelCase = 10 , _UpperCAmelCase = 1000 , _UpperCAmelCase = True): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)') return min_val if option else max_val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int((number_a + number_a) / 2) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)') if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value') def answer(_UpperCAmelCase) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...') SCREAMING_SNAKE_CASE = lower SCREAMING_SNAKE_CASE = higher SCREAMING_SNAKE_CASE = [] while True: SCREAMING_SNAKE_CASE = get_avg(_UpperCAmelCase , _UpperCAmelCase) last_numbers.append(_UpperCAmelCase) if answer(_UpperCAmelCase) == "low": SCREAMING_SNAKE_CASE = number elif answer(_UpperCAmelCase) == "high": SCREAMING_SNAKE_CASE = number else: break print(F'''guess the number : {last_numbers[-1]}''') print(F'''details : {last_numbers!s}''') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Enter lower value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter high value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter value to guess : ').strip()) guess_the_number(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
"""simple docstring""" from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake lowerCamelCase = numpy.array([0, 0]) lowerCamelCase = numpy.array([0.5, 0.8_660_254]) lowerCamelCase = numpy.array([1, 0]) lowerCamelCase = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ): UpperCAmelCase_ = initial_vectors for _ in range(lowerCAmelCase__ ): UpperCAmelCase_ = iteration_step(lowerCAmelCase__ ) return vectors def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = [] for i, start_vector in enumerate(vectors[:-1] ): UpperCAmelCase_ = vectors[i + 1] new_vectors.append(lowerCAmelCase__ ) UpperCAmelCase_ = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3 ) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 60 ) ) new_vectors.append(start_vector + difference_vector * 2 / 3 ) new_vectors.append(vectors[-1] ) return new_vectors def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ): UpperCAmelCase_ = numpy.radians(lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_ = numpy.cos(lowerCAmelCase__ ), numpy.sin(lowerCAmelCase__ ) UpperCAmelCase_ = numpy.array(((c, -s), (s, c)) ) return numpy.dot(lowerCAmelCase__ , lowerCAmelCase__ ) def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = plt.gca() axes.set_aspect("equal" ) # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() UpperCAmelCase_ , UpperCAmelCase_ = zip(*lowerCAmelCase__ ) plt.plot(lowerCAmelCase__ , lowerCAmelCase__ ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase = iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
82
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class _snake_case : def __init__( self , a , a=13 , 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=512 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> Union[str, 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 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: 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 = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , use_stable_embedding=a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Any: SCREAMING_SNAKE_CASE = OpenLlamaModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , ) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , ) SCREAMING_SNAKE_CASE = model(a , attention_mask=a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() # first forward pass SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , use_cache=a , ) SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , output_hidden_states=a , )['hidden_states'][0] SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , past_key_values=a , output_hidden_states=a , )['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1]).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1E-3)) def SCREAMING_SNAKE_CASE__ ( self) -> 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, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) _lowercase : str = (OpenLlamaForCausalLM,) if is_torch_available() else () _lowercase : List[str] = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) _lowercase : List[str] = False _lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = OpenLlamaModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'single_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'multi_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass @parameterized.expand([('linear',), ('dynamic',)]) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ids_tensor([1, 10] , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = OpenLlamaModel(a) original_model.to(a) original_model.eval() SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = {'type': scaling_type, 'factor': 10.0} SCREAMING_SNAKE_CASE = OpenLlamaModel(a) scaled_model.to(a) scaled_model.eval() SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a , a , atol=1E-5)) else: self.assertFalse(torch.allclose(a , a , atol=1E-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(a , a , atol=1E-5))
73
0
"""simple docstring""" import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) def snake_case_ ( A_ : int, A_ : Tuple ): '''simple docstring''' _lowerCamelCase : Optional[Any] = [] for i in range(encoder_config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F'''encoder.deit.blocks.{i}.norm1.weight''', F'''encoder.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''encoder.deit.blocks.{i}.norm1.bias''', F'''encoder.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.attn.proj.weight''', F'''encoder.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.attn.proj.bias''', F'''encoder.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.norm2.weight''', F'''encoder.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''encoder.deit.blocks.{i}.norm2.bias''', F'''encoder.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.mlp.fc1.weight''', F'''encoder.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.mlp.fc1.bias''', F'''encoder.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append( (F'''encoder.deit.blocks.{i}.mlp.fc2.weight''', F'''encoder.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''encoder.deit.blocks.{i}.mlp.fc2.bias''', F'''encoder.encoder.layer.{i}.output.dense.bias''') ) # cls token, position embeddings and patch embeddings of encoder rename_keys.extend( [ ('''encoder.deit.cls_token''', '''encoder.embeddings.cls_token'''), ('''encoder.deit.pos_embed''', '''encoder.embeddings.position_embeddings'''), ('''encoder.deit.patch_embed.proj.weight''', '''encoder.embeddings.patch_embeddings.projection.weight'''), ('''encoder.deit.patch_embed.proj.bias''', '''encoder.embeddings.patch_embeddings.projection.bias'''), ('''encoder.deit.norm.weight''', '''encoder.layernorm.weight'''), ('''encoder.deit.norm.bias''', '''encoder.layernorm.bias'''), ] ) return rename_keys def snake_case_ ( A_ : List[Any], A_ : Tuple ): '''simple docstring''' for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) _lowerCamelCase : Any = state_dict.pop(F'''encoder.deit.blocks.{i}.attn.qkv.weight''' ) _lowerCamelCase : Dict = in_proj_weight[ : encoder_config.hidden_size, : ] _lowerCamelCase : Dict = in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] _lowerCamelCase : str = in_proj_weight[ -encoder_config.hidden_size :, : ] def snake_case_ ( A_ : List[str], A_ : int, A_ : int ): '''simple docstring''' _lowerCamelCase : str = dct.pop(A_ ) _lowerCamelCase : str = val def snake_case_ ( A_ : Dict ): '''simple docstring''' if "handwritten" in checkpoint_url: _lowerCamelCase : int = '''https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg''' # industry # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" # # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg" elif "printed" in checkpoint_url or "stage1" in checkpoint_url: _lowerCamelCase : List[str] = '''https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg''' _lowerCamelCase : Dict = Image.open(requests.get(A_, stream=A_ ).raw ).convert('''RGB''' ) return im @torch.no_grad() def snake_case_ ( A_ : Tuple, A_ : Dict ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = ViTConfig(image_size=3_84, qkv_bias=A_ ) _lowerCamelCase : int = TrOCRConfig() # size of the architecture if "base" in checkpoint_url: _lowerCamelCase : Any = 7_68 elif "large" in checkpoint_url: # use ViT-large encoder _lowerCamelCase : str = 10_24 _lowerCamelCase : List[str] = 40_96 _lowerCamelCase : Any = 24 _lowerCamelCase : Union[str, Any] = 16 _lowerCamelCase : str = 10_24 else: raise ValueError('''Should either find \'base\' or \'large\' in checkpoint URL''' ) # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards if "large-printed" in checkpoint_url or "stage1" in checkpoint_url: _lowerCamelCase : Tuple = False _lowerCamelCase : Any = '''relu''' _lowerCamelCase : Optional[Any] = 10_24 _lowerCamelCase : List[str] = True _lowerCamelCase : Tuple = False _lowerCamelCase : Tuple = False # load HuggingFace model _lowerCamelCase : List[Any] = ViTModel(A_, add_pooling_layer=A_ ) _lowerCamelCase : List[str] = TrOCRForCausalLM(A_ ) _lowerCamelCase : List[Any] = VisionEncoderDecoderModel(encoder=A_, decoder=A_ ) model.eval() # load state_dict of original model, rename some keys _lowerCamelCase : Optional[int] = torch.hub.load_state_dict_from_url(A_, map_location='''cpu''', check_hash=A_ )['''model'''] _lowerCamelCase : Tuple = create_rename_keys(A_, A_ ) for src, dest in rename_keys: rename_key(A_, A_, A_ ) read_in_q_k_v(A_, A_ ) # remove parameters we don't need del state_dict["encoder.deit.head.weight"] del state_dict["encoder.deit.head.bias"] del state_dict["decoder.version"] # add prefix to decoder keys for key, val in state_dict.copy().items(): _lowerCamelCase : Union[str, Any] = state_dict.pop(A_ ) if key.startswith('''decoder''' ) and "output_projection" not in key: _lowerCamelCase : Dict = val else: _lowerCamelCase : Dict = val # load state dict model.load_state_dict(A_ ) # Check outputs on an image _lowerCamelCase : str = ViTImageProcessor(size=encoder_config.image_size ) _lowerCamelCase : List[str] = RobertaTokenizer.from_pretrained('''roberta-large''' ) _lowerCamelCase : List[str] = TrOCRProcessor(A_, A_ ) _lowerCamelCase : Dict = processor(images=prepare_img(A_ ), return_tensors='''pt''' ).pixel_values # verify logits _lowerCamelCase : str = torch.tensor([[model.config.decoder.decoder_start_token_id]] ) _lowerCamelCase : Tuple = model(pixel_values=A_, decoder_input_ids=A_ ) _lowerCamelCase : Optional[Any] = outputs.logits _lowerCamelCase : str = torch.Size([1, 1, 5_02_65] ) if "trocr-base-handwritten" in checkpoint_url: _lowerCamelCase : Dict = torch.tensor( [-1.4502, -4.6683, -0.5347, -2.9291, 9.1435, -3.0571, 8.9764, 1.7560, 8.7358, -1.5311] ) elif "trocr-large-handwritten" in checkpoint_url: _lowerCamelCase : Optional[int] = torch.tensor( [-2.6437, -1.3129, -2.2596, -5.3455, 6.3539, 1.7604, 5.4991, 1.4702, 5.6113, 2.0170] ) elif "trocr-base-printed" in checkpoint_url: _lowerCamelCase : Tuple = torch.tensor( [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210] ) elif "trocr-large-printed" in checkpoint_url: _lowerCamelCase : Tuple = torch.tensor( [-6.0162, -7.0959, 4.4155, -5.1063, 7.0468, -3.1631, 2.6466, -0.3081, -0.8106, -1.7535] ) if "stage1" not in checkpoint_url: assert logits.shape == expected_shape, "Shape of logits not as expected" assert torch.allclose(logits[0, 0, :10], A_, atol=1E-3 ), "First elements of logits not as expected" Path(A_ ).mkdir(exist_ok=A_ ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(A_ ) print(F'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(A_ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_url''', default='''https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt''', type=str, help='''URL 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.''' ) lowerCAmelCase__ = parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
83
from __future__ import annotations a_ : str = [] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for i in range(len(_UpperCAmelCase)): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase)): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , -1 , -1)): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , len(_UpperCAmelCase))): if board[i][j] == 1: return False return True def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if row >= len(_UpperCAmelCase): solution.append(_UpperCAmelCase) printboard(_UpperCAmelCase) print() return True for i in range(len(_UpperCAmelCase)): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 solve(_UpperCAmelCase , row + 1) SCREAMING_SNAKE_CASE = 0 return False def lowerCamelCase__ (_UpperCAmelCase): for i in range(len(_UpperCAmelCase)): for j in range(len(_UpperCAmelCase)): if board[i][j] == 1: print('Q' , end=' ') else: print('.' , end=' ') print() # n=int(input("The no. of queens")) a_ : Tuple = 8 a_ : int = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
73
0
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model UpperCAmelCase = '''0.12''' # assumed parallelism: 8 if is_torch_available(): import torch def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): if rng is None: lowercase = random.Random() lowercase = 1 for dim in shape: total_dims *= dim lowercase = [] for _ in range(__SCREAMING_SNAKE_CASE ): values.append(rng.randint(0 , vocab_size - 1 ) ) lowercase = np.array(__SCREAMING_SNAKE_CASE , dtype=jnp.intaa ).reshape(__SCREAMING_SNAKE_CASE ) return output def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): lowercase = ids_tensor(__SCREAMING_SNAKE_CASE , vocab_size=2 , rng=__SCREAMING_SNAKE_CASE ) # make sure that at least one token is attended to for each batch lowercase = 1 return attn_mask @require_flax class A_ : '''simple docstring''' _UpperCamelCase : int = None _UpperCamelCase : Any = () def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 lowercase = 2 lowercase = inputs['input_ids'].shape[-1] // 2 lowercase = inputs['input_ids'][:max_batch_size, :sequence_length] lowercase = jnp.ones_like(snake_case ) lowercase = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens lowercase = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` lowercase = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase , lowercase , lowercase = self._get_input_ids_and_config() lowercase = False lowercase = max_length lowercase = 0 for model_class in self.all_generative_model_classes: lowercase = model_class(snake_case ) lowercase = model_class.__name__[4:] # Skip the "Flax" at the beginning lowercase = getattr(snake_case , snake_case ) lowercase = pt_model_class(snake_case ).eval() lowercase = load_flax_weights_in_pytorch_model(snake_case , flax_model.params ) lowercase = flax_model.generate(snake_case ).sequences lowercase = pt_model.generate(torch.tensor(snake_case , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: lowercase = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase , lowercase , lowercase = self._get_input_ids_and_config() lowercase = False lowercase = max_length for model_class in self.all_generative_model_classes: lowercase = model_class(snake_case ) lowercase = model.generate(snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case ) lowercase = jit(model.generate ) lowercase = jit_generate(snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase , lowercase , lowercase = self._get_input_ids_and_config() lowercase = True lowercase = max_length for model_class in self.all_generative_model_classes: lowercase = model_class(snake_case ) lowercase = model.generate(snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case ) lowercase = jit(model.generate ) lowercase = jit_generate(snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase , lowercase , lowercase = self._get_input_ids_and_config() lowercase = False lowercase = max_length lowercase = 2 for model_class in self.all_generative_model_classes: lowercase = model_class(snake_case ) lowercase = model.generate(snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case ) lowercase = jit(model.generate ) lowercase = jit_generate(snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase , lowercase , lowercase = self._get_input_ids_and_config() lowercase = False lowercase = max_length lowercase = 2 lowercase = 2 for model_class in self.all_generative_model_classes: lowercase = model_class(snake_case ) lowercase = model.generate(snake_case ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase , lowercase , lowercase = self._get_input_ids_and_config() lowercase = True lowercase = max_length lowercase = 0.8 lowercase = 10 lowercase = 0.3 lowercase = 1 lowercase = 8 lowercase = 9 for model_class in self.all_generative_model_classes: lowercase = model_class(snake_case ) lowercase = model.generate(snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case ) lowercase = jit(model.generate ) lowercase = jit_generate(snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase , lowercase , lowercase = self._get_input_ids_and_config() lowercase = max_length lowercase = 1 lowercase = 8 lowercase = 9 for model_class in self.all_generative_model_classes: lowercase = model_class(snake_case ) lowercase = model.generate(snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case ) lowercase = jit(model.generate ) lowercase = jit_generate(snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase , lowercase , lowercase = self._get_input_ids_and_config() lowercase = max_length lowercase = 2 lowercase = 1 lowercase = 8 lowercase = 9 for model_class in self.all_generative_model_classes: lowercase = model_class(snake_case ) lowercase = model.generate(snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case ) lowercase = jit(model.generate ) lowercase = jit_generate(snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase , lowercase , lowercase = self._get_input_ids_and_config() # pad attention mask on the left lowercase = attention_mask.at[(0, 0)].set(0 ) lowercase = False lowercase = max_length for model_class in self.all_generative_model_classes: lowercase = model_class(snake_case ) lowercase = model.generate(snake_case , attention_mask=snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case ) lowercase = jit(model.generate ) lowercase = jit_generate(snake_case , attention_mask=snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase , lowercase , lowercase = self._get_input_ids_and_config() # pad attention mask on the left lowercase = attention_mask.at[(0, 0)].set(0 ) lowercase = True lowercase = max_length for model_class in self.all_generative_model_classes: lowercase = model_class(snake_case ) lowercase = model.generate(snake_case , attention_mask=snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case ) lowercase = jit(model.generate ) lowercase = jit_generate(snake_case , attention_mask=snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase , lowercase , lowercase , lowercase = self._get_input_ids_and_config() # pad attention mask on the left lowercase = attention_mask.at[(0, 0)].set(0 ) lowercase = 2 lowercase = max_length for model_class in self.all_generative_model_classes: lowercase = model_class(snake_case ) lowercase = model.generate(snake_case , attention_mask=snake_case ).sequences self.assertEqual(generation_outputs.shape[-1] , snake_case ) lowercase = jit(model.generate ) lowercase = jit_generate(snake_case , attention_mask=snake_case ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class A_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self ): lowercase = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-bert' ) lowercase = FlaxAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-bert-flax-only' ) lowercase = 'Hello world' lowercase = tokenizer(snake_case , return_tensors='np' ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(snake_case , 'do_samples' ): model.generate(snake_case , do_samples=snake_case ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(snake_case , 'foo' ): lowercase = {'foo': 'bar'} model.generate(snake_case , **snake_case )
84
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) for optional_component in pipe._optional_components: self.assertTrue( getattr(a , a) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
0
from __future__ import annotations import bisect def _a ( lowercase__ : list[int] , lowercase__ : int , lowercase__ : int = 0 , lowercase__ : int = -1 ): '''simple docstring''' if hi < 0: SCREAMING_SNAKE_CASE__ : str = len(lowercase__ ) while lo < hi: SCREAMING_SNAKE_CASE__ : Optional[Any] = lo + (hi - lo) // 2 if sorted_collection[mid] < item: SCREAMING_SNAKE_CASE__ : Tuple = mid + 1 else: SCREAMING_SNAKE_CASE__ : str = mid return lo def _a ( lowercase__ : list[int] , lowercase__ : int , lowercase__ : int = 0 , lowercase__ : int = -1 ): '''simple docstring''' if hi < 0: SCREAMING_SNAKE_CASE__ : str = len(lowercase__ ) while lo < hi: SCREAMING_SNAKE_CASE__ : Any = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: SCREAMING_SNAKE_CASE__ : int = mid + 1 else: SCREAMING_SNAKE_CASE__ : List[str] = mid return lo def _a ( lowercase__ : list[int] , lowercase__ : int , lowercase__ : int = 0 , lowercase__ : int = -1 ): '''simple docstring''' sorted_collection.insert(bisect_left(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) , lowercase__ ) def _a ( lowercase__ : list[int] , lowercase__ : int , lowercase__ : int = 0 , lowercase__ : int = -1 ): '''simple docstring''' sorted_collection.insert(bisect_right(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) , lowercase__ ) def _a ( lowercase__ : list[int] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : str = len(lowercase__ ) - 1 while left <= right: SCREAMING_SNAKE_CASE__ : Tuple = left + (right - left) // 2 SCREAMING_SNAKE_CASE__ : List[str] = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: SCREAMING_SNAKE_CASE__ : List[str] = midpoint - 1 else: SCREAMING_SNAKE_CASE__ : Tuple = midpoint + 1 return None def _a ( lowercase__ : list[int] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = bisect.bisect_left(lowercase__ , lowercase__ ) if index != len(lowercase__ ) and sorted_collection[index] == item: return index return None def _a ( lowercase__ : list[int] , lowercase__ : int , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if right < left: return None SCREAMING_SNAKE_CASE__ : Dict = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(lowercase__ , lowercase__ , lowercase__ , midpoint - 1 ) else: return binary_search_by_recursion(lowercase__ , lowercase__ , midpoint + 1 , lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = input("Enter numbers separated by comma:\n").strip() SCREAMING_SNAKE_CASE__ : Union[str, Any] = sorted(int(item) for item in user_input.split(",")) SCREAMING_SNAKE_CASE__ : Optional[Any] = int(input("Enter a single number to be found in the list:\n")) SCREAMING_SNAKE_CASE__ : Optional[Any] = binary_search(collection, target) if result is None: print(F"""{target} was not found in {collection}.""") else: print(F"""{target} was found at position {result} in {collection}.""")
85
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Any = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _snake_case ( A__ ): _lowercase : Optional[int] = '''unispeech''' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="mean" , a=False , a=False , a=256 , a=80 , a=0 , a=1 , a=2 , a=0.5 , **a , ) -> Optional[int]: super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE = replace_prob @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return functools.reduce(operator.mul , self.conv_stride , 1)
73
0
from ..utils import DummyObject, requires_backends class _a ( metaclass=snake_case_ ): """simple docstring""" _lowerCamelCase : List[Any] = ['torch', 'torchsde'] def __init__( self : Any , *UpperCAmelCase : int , **UpperCAmelCase : int ): requires_backends(self , ["torch", "torchsde"] ) @classmethod def __A ( cls : Optional[int] , *UpperCAmelCase : Any , **UpperCAmelCase : int ): requires_backends(cls , ["torch", "torchsde"] ) @classmethod def __A ( cls : int , *UpperCAmelCase : Tuple , **UpperCAmelCase : List[Any] ): requires_backends(cls , ["torch", "torchsde"] )
86
import argparse import collections import json import os import re import string import sys import numpy as np a_ : Optional[Any] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a_ : List[str] = None def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.') parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.') parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).') parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.') parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.') parser.add_argument('--verbose' , '-v' , action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa['answers']['text']) return qid_to_has_ans def lowerCamelCase__ (_UpperCAmelCase): def remove_articles(_UpperCAmelCase): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase) def white_space_fix(_UpperCAmelCase): return " ".join(text.split()) def remove_punc(_UpperCAmelCase): SCREAMING_SNAKE_CASE = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(_UpperCAmelCase): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase)))) def lowerCamelCase__ (_UpperCAmelCase): if not s: return [] return normalize_answer(_UpperCAmelCase).split() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int(normalize_answer(_UpperCAmelCase) == normalize_answer(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.Counter(_UpperCAmelCase) & collections.Counter(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(common.values()) if len(_UpperCAmelCase) == 0 or len(_UpperCAmelCase) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa['id'] SCREAMING_SNAKE_CASE = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase)] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [''] if qid not in preds: print(F'''Missing prediction for {qid}''') continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) SCREAMING_SNAKE_CASE = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) return exact_scores, fa_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid]) else: SCREAMING_SNAKE_CASE = s return new_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): if not qid_list: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values()) / total), ('f1', 1_00.0 * sum(fa_scores.values()) / total), ('total', total), ]) else: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list) / total), ('total', total), ]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post') plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(_UpperCAmelCase) plt.savefig(_UpperCAmelCase) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(_UpperCAmelCase): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1) SCREAMING_SNAKE_CASE = true_pos / float(_UpperCAmelCase) if i == len(_UpperCAmelCase) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase) recalls.append(_UpperCAmelCase) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return {"ap": 1_00.0 * avg_prec} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if out_image_dir and not os.path.exists(_UpperCAmelCase): os.makedirs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png') , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png') , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE = {k: float(_UpperCAmelCase) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png') , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(_UpperCAmelCase) / float(len(_UpperCAmelCase)) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title(F'''Histogram of no-answer probability: {name}''') plt.savefig(os.path.join(_UpperCAmelCase , F'''na_prob_hist_{name}.png''')) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) for i, qid in enumerate(_UpperCAmelCase): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 1_00.0 * best_score / len(_UpperCAmelCase), best_thresh def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def lowerCamelCase__ (): with open(OPTS.data_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset_json['data'] with open(OPTS.pred_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(_UpperCAmelCase) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns') if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns') histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns') if OPTS.out_file: with open(OPTS.out_file , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) else: print(json.dumps(_UpperCAmelCase , indent=2)) if __name__ == "__main__": a_ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
73
0
import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() _lowerCamelCase : List[str] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Union[str, Any]: """simple docstring""" A__ = WavaVecaForSequenceClassification.from_pretrained(lowercase_ , config=lowercase_ ) A__ = downstream_dict['''projector.weight'''] A__ = downstream_dict['''projector.bias'''] A__ = downstream_dict['''model.post_net.linear.weight'''] A__ = downstream_dict['''model.post_net.linear.bias'''] return model def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> List[str]: """simple docstring""" A__ = WavaVecaForAudioFrameClassification.from_pretrained(lowercase_ , config=lowercase_ ) A__ = downstream_dict['''model.linear.weight'''] A__ = downstream_dict['''model.linear.bias'''] return model def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Tuple: """simple docstring""" A__ = WavaVecaForXVector.from_pretrained(lowercase_ , config=lowercase_ ) A__ = downstream_dict['''connector.weight'''] A__ = downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): A__ = downstream_dict[ f"""model.framelevel_feature_extractor.module.{i}.kernel.weight""" ] A__ = downstream_dict[f"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""] A__ = downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] A__ = downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] A__ = downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] A__ = downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] A__ = downstream_dict['''objective.W'''] return model @torch.no_grad() def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> Union[str, Any]: """simple docstring""" A__ = torch.load(lowercase_ , map_location='''cpu''' ) A__ = checkpoint['''Downstream'''] A__ = WavaVecaConfig.from_pretrained(lowercase_ ) A__ = WavaVecaFeatureExtractor.from_pretrained( lowercase_ , return_attention_mask=lowercase_ , do_normalize=lowercase_ ) A__ = hf_config.architectures[0] if arch.endswith('''ForSequenceClassification''' ): A__ = convert_classification(lowercase_ , lowercase_ , lowercase_ ) elif arch.endswith('''ForAudioFrameClassification''' ): A__ = convert_diarization(lowercase_ , lowercase_ , lowercase_ ) elif arch.endswith('''ForXVector''' ): A__ = convert_xvector(lowercase_ , lowercase_ , lowercase_ ) else: raise NotImplementedError(f"""S3PRL weights conversion is not supported for {arch}""" ) if hf_config.use_weighted_layer_sum: A__ = checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(lowercase_ ) hf_model.save_pretrained(lowercase_ ) if __name__ == "__main__": _lowerCamelCase : 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.""") _lowerCamelCase : List[str] = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
87
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a , ) super().__init__(*a , **a)
73
0
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def _snake_case ( __snake_case : Optional[Any] , __snake_case : Any , __snake_case : List[Any] ): """simple docstring""" _lowerCamelCase : Dict = 1.5 _lowerCamelCase : List[Any] = int(factor * num_class_images ) _lowerCamelCase : List[str] = ClipClient( url="""https://knn.laion.ai/knn-service""" , indice_name="""laion_400m""" , num_images=__snake_case , aesthetic_weight=0.1 ) os.makedirs(F'{class_data_dir}/images' , exist_ok=__snake_case ) if len(list(Path(F'{class_data_dir}/images' ).iterdir() ) ) >= num_class_images: return while True: _lowerCamelCase : Optional[int] = client.query(text=__snake_case ) if len(__snake_case ) >= factor * num_class_images or num_images > 1E4: break else: _lowerCamelCase : Any = int(factor * num_images ) _lowerCamelCase : str = ClipClient( url="""https://knn.laion.ai/knn-service""" , indice_name="""laion_400m""" , num_images=__snake_case , aesthetic_weight=0.1 , ) _lowerCamelCase : Dict = 0 _lowerCamelCase : List[Any] = 0 _lowerCamelCase : Tuple = tqdm(desc="""downloading real regularization images""" , total=__snake_case ) with open(F'{class_data_dir}/caption.txt' , """w""" ) as fa, open(F'{class_data_dir}/urls.txt' , """w""" ) as fa, open( F'{class_data_dir}/images.txt' , """w""" ) as fa: while total < num_class_images: _lowerCamelCase : Dict = class_images[count] count += 1 try: _lowerCamelCase : Optional[Any] = requests.get(images["""url"""] ) if img.status_code == 200: _lowerCamelCase : Optional[int] = Image.open(BytesIO(img.content ) ) with open(F'{class_data_dir}/images/{total}.jpg' , """wb""" ) as f: f.write(img.content ) fa.write(images["""caption"""] + """\n""" ) fa.write(images["""url"""] + """\n""" ) fa.write(F'{class_data_dir}/images/{total}.jpg' + """\n""" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[str] = argparse.ArgumentParser("""""" , add_help=__snake_case ) parser.add_argument("""--class_prompt""" , help="""text prompt to retrieve images""" , required=__snake_case , type=__snake_case ) parser.add_argument("""--class_data_dir""" , help="""path to save images""" , required=__snake_case , type=__snake_case ) parser.add_argument("""--num_class_images""" , help="""number of images to download""" , default=200 , type=__snake_case ) return parser.parse_args() if __name__ == "__main__": UpperCAmelCase = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
88
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
0
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class _lowerCamelCase( _a ): lowercase_ : Dict = """""" lowercase_ : str = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) lowercase_ : str = None # compression type in fsspec. ex: "gzip" lowercase_ : str = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self, lowerCamelCase = "", lowerCamelCase = None, lowerCamelCase = None, **lowerCamelCase) -> List[str]: """simple docstring""" super().__init__(self, **lowerCamelCase) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode _lowercase : str = fsspec.open( lowerCamelCase, mode='rb', protocol=lowerCamelCase, compression=self.compression, client_kwargs={ 'requote_redirect_url': False, # see https://github.com/huggingface/datasets/pull/5459 'trust_env': True, # Enable reading proxy env variables. **(target_options or {}).pop('client_kwargs', {}), # To avoid issues if it was already passed. }, **(target_options or {}), ) _lowercase : Dict = os.path.basename(self.file.path.split('::')[0]) _lowercase : int = ( self.compressed_name[: self.compressed_name.rindex('.')] if '.' in self.compressed_name else self.compressed_name ) _lowercase : int = None @classmethod def UpperCamelCase ( cls, lowerCamelCase) -> Any: """simple docstring""" return super()._strip_protocol(lowerCamelCase).lstrip('/') def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" if self.dir_cache is None: _lowercase : List[str] = {**self.file.fs.info(self.file.path), 'name': self.uncompressed_name} _lowercase : Optional[int] = {f['name']: f} def UpperCamelCase ( self, lowerCamelCase) -> Union[str, Any]: """simple docstring""" return self.file.open().read() def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = "rb", lowerCamelCase=None, lowerCamelCase=True, lowerCamelCase=None, **lowerCamelCase, ) -> str: """simple docstring""" _lowercase : Optional[int] = self._strip_protocol(lowerCamelCase) if mode != "rb": raise ValueError(F'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''') return self.file.open() class _lowerCamelCase( _a ): lowercase_ : Tuple = """bz2""" lowercase_ : Dict = """bz2""" lowercase_ : List[Any] = """.bz2""" class _lowerCamelCase( _a ): lowercase_ : Optional[Any] = """gzip""" lowercase_ : int = """gzip""" lowercase_ : Optional[Any] = """.gz""" class _lowerCamelCase( _a ): lowercase_ : Any = """lz4""" lowercase_ : List[str] = """lz4""" lowercase_ : str = """.lz4""" class _lowerCamelCase( _a ): lowercase_ : List[Any] = """xz""" lowercase_ : str = """xz""" lowercase_ : int = """.xz""" class _lowerCamelCase( _a ): lowercase_ : List[str] = """zstd""" lowercase_ : List[Any] = """zstd""" lowercase_ : Tuple = """.zst""" def __init__( self, lowerCamelCase, lowerCamelCase = "rb", lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = DEFAULT_BLOCK_SIZE, **lowerCamelCase, ) -> Dict: """simple docstring""" super().__init__( fo=lowerCamelCase, mode=lowerCamelCase, target_protocol=lowerCamelCase, target_options=lowerCamelCase, block_size=lowerCamelCase, **lowerCamelCase, ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 _lowercase : List[Any] = self.file.__enter__ class _lowerCamelCase: def __init__( self, lowerCamelCase) -> Tuple: """simple docstring""" _lowercase : Tuple = file_ def __enter__( self) -> Any: """simple docstring""" self._file.__enter__() return self def __exit__( self, *lowerCamelCase, **lowerCamelCase) -> Any: """simple docstring""" self._file.__exit__(*lowerCamelCase, **lowerCamelCase) def __iter__( self) -> Optional[int]: """simple docstring""" return iter(self._file) def UpperCamelCase ( self) -> Any: """simple docstring""" return next(self._file) def __getattr__( self, lowerCamelCase) -> Tuple: """simple docstring""" return getattr(self._file, lowerCamelCase) def fixed_enter(*lowerCamelCase, **lowerCamelCase): return WrappedFile(_enter(*lowerCamelCase, **lowerCamelCase)) _lowercase : Optional[int] = fixed_enter
89
import sys import turtle def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) if depth == 0: return triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) a_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') a_ : str = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
73
0
'''simple docstring''' import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) __UpperCAmelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class a__ ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = None , lowerCamelCase_ = None ) -> Any: lowerCAmelCase__ = None lowerCAmelCase__ = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) lowerCAmelCase__ = os.path.abspath('''examples''' ) for item in os.listdir(lowerCamelCase_ ): if item not in EXCLUDE_EXAMPLES: lowerCAmelCase__ = os.path.join(lowerCamelCase_ , lowerCamelCase_ ) if os.path.isfile(lowerCamelCase_ ) and ".py" in item_path: with self.subTest( tested_script=lowerCamelCase_ , feature_script=lowerCamelCase_ , tested_section='''main()''' if parser_only else '''training_function()''' , ): lowerCAmelCase__ = compare_against_test( os.path.join(lowerCamelCase_ , lowerCamelCase_ ) , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) lowerCAmelCase__ = '''\n'''.join(lowerCamelCase_ ) if special_strings is not None: for string in special_strings: lowerCAmelCase__ = diff.replace(lowerCamelCase_ , '''''' ) self.assertEqual(lowerCamelCase_ , '''''' ) def __SCREAMING_SNAKE_CASE ( self ) -> Any: self.one_complete_example('''complete_nlp_example.py''' , lowerCamelCase_ ) self.one_complete_example('''complete_nlp_example.py''' , lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]: lowerCAmelCase__ = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) lowerCAmelCase__ = [ ''' ''' * 16 + '''{\n\n''', ''' ''' * 20 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 20 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 20 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 20 + '''"epoch": epoch,\n\n''', ''' ''' * 16 + '''},\n\n''', ''' ''' * 16 + '''step=epoch,\n''', ''' ''' * 12, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) self.one_complete_example('''complete_cv_example.py''' , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) @mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "1"} ) class a__ ( a__ ): '''simple docstring''' lowercase__ : Optional[Any] = False @classmethod def __SCREAMING_SNAKE_CASE ( cls ) -> Optional[Any]: super().setUpClass() lowerCAmelCase__ = tempfile.mkdtemp() lowerCAmelCase__ = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) lowerCAmelCase__ = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def __SCREAMING_SNAKE_CASE ( cls ) -> str: super().tearDownClass() shutil.rmtree(cls._tmpdir ) def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]: lowerCAmelCase__ = F""" examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: lowerCAmelCase__ = F""" examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} """.split() lowerCAmelCase__ = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def __SCREAMING_SNAKE_CASE ( self ) -> str: lowerCAmelCase__ = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "epoch_0" )} """.split() lowerCAmelCase__ = run_command(self._launch_args + testargs , return_stdout=lowerCamelCase_ ) self.assertNotIn('''epoch 0:''' , lowerCamelCase_ ) self.assertIn('''epoch 1:''' , lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: lowerCAmelCase__ = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "step_2" )} """.split() lowerCAmelCase__ = run_command(self._launch_args + testargs , return_stdout=lowerCamelCase_ ) if torch.cuda.is_available(): lowerCAmelCase__ = torch.cuda.device_count() else: lowerCAmelCase__ = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , lowerCamelCase_ ) self.assertIn('''epoch 1:''' , lowerCamelCase_ ) else: self.assertIn('''epoch 0:''' , lowerCamelCase_ ) self.assertIn('''epoch 1:''' , lowerCamelCase_ ) @slow def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: lowerCAmelCase__ = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): lowerCAmelCase__ = run_command(self._launch_args + testargs , return_stdout=lowerCamelCase_ ) lowerCAmelCase__ = re.findall('''({.+})''' , lowerCamelCase_ ) lowerCAmelCase__ = [r for r in results if '''accuracy''' in r][-1] lowerCAmelCase__ = ast.literal_eval(lowerCamelCase_ ) self.assertGreaterEqual(results['''accuracy'''] , 0.75 ) def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: lowerCAmelCase__ = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __SCREAMING_SNAKE_CASE ( self ) -> List[str]: with tempfile.TemporaryDirectory() as tmpdir: lowerCAmelCase__ = F""" examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(lowerCamelCase_ , '''tracking''' ) ) ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: lowerCAmelCase__ = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: lowerCAmelCase__ = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
90
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
0
"""simple docstring""" import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def _snake_case ( snake_case__ : List[Any] , snake_case__ : str , snake_case__ : str , snake_case__ : Path , snake_case__ : str = None , snake_case__ : str = None , snake_case__ : str = None , ): if config_name_or_path is None: A = 'facebook/rag-token-base' if model_type == 'rag_token' else 'facebook/rag-sequence-base' if generator_tokenizer_name_or_path is None: A = generator_name_or_path if question_encoder_tokenizer_name_or_path is None: A = question_encoder_name_or_path A = RagTokenForGeneration if model_type == 'rag_token' else RagSequenceForGeneration # Save model. A = RagConfig.from_pretrained(snake_case__ ) A = AutoConfig.from_pretrained(snake_case__ ) A = AutoConfig.from_pretrained(snake_case__ ) A = gen_config A = question_encoder_config A = model_class.from_pretrained_question_encoder_generator( snake_case__ , snake_case__ , config=snake_case__ ) rag_model.save_pretrained(snake_case__ ) # Sanity check. model_class.from_pretrained(snake_case__ ) # Save tokenizers. A = AutoTokenizer.from_pretrained(snake_case__ ) gen_tokenizer.save_pretrained(dest_dir / 'generator_tokenizer/' ) A = AutoTokenizer.from_pretrained(snake_case__ ) question_encoder_tokenizer.save_pretrained(dest_dir / 'question_encoder_tokenizer/' ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() parser.add_argument( '''--model_type''', choices=['''rag_sequence''', '''rag_token'''], required=True, type=str, help='''RAG model type: rag_sequence, rag_token''', ) parser.add_argument('''--dest''', type=str, required=True, help='''Path to the output checkpoint directory.''') parser.add_argument('''--generator_name_or_path''', type=str, required=True, help='''Generator model identifier''') parser.add_argument( '''--question_encoder_name_or_path''', type=str, required=True, help='''Question encoder model identifier''' ) parser.add_argument( '''--generator_tokenizer_name_or_path''', type=str, help='''Generator tokenizer identifier, if not specified, resolves to ``generator_name_or_path``''', ) parser.add_argument( '''--question_encoder_tokenizer_name_or_path''', type=str, help='''Question encoder tokenizer identifier, if not specified, resolves to ``question_encoder_name_or_path``''', ) parser.add_argument( '''--config_name_or_path''', type=str, help=( '''Identifier of the model config to use, if not provided, resolves to a base config for a given''' ''' ``model_type``''' ), ) _lowercase = parser.parse_args() _lowercase = Path(args.dest) dest_dir.mkdir(exist_ok=True) consolidate( args.model_type, args.generator_name_or_path, args.question_encoder_name_or_path, dest_dir, args.config_name_or_path, args.generator_tokenizer_name_or_path, args.question_encoder_tokenizer_name_or_path, )
91
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def _lowerCAmelCase ( __magic_name__ : int , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int ) -> np.ndarray: # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: lowercase : int =ksize + 1 lowercase : str =np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(__magic_name__ ): for x in range(__magic_name__ ): # distance from center lowercase : Optional[Any] =x - ksize // 2 lowercase : List[str] =y - ksize // 2 # degree to radiant lowercase : Optional[int] =theta / 180 * np.pi lowercase : Union[str, Any] =np.cos(_theta ) lowercase : Optional[int] =np.sin(_theta ) # get kernel x lowercase : Tuple =cos_theta * px + sin_theta * py # get kernel y lowercase : Dict =-sin_theta * px + cos_theta * py # fill kernel lowercase : str =np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image UpperCamelCase_ = imread("""../image_data/lena.jpg""") # turn image in gray scale value UpperCamelCase_ = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges UpperCamelCase_ = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: UpperCamelCase_ = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) UpperCamelCase_ = out / out.max() * 255 UpperCamelCase_ = out.astype(np.uinta) imshow("""Original""", gray) imshow("""Gabor filter with 20x20 mask and 6 directions""", out) waitKey(0)
92
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path a_ : str = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def lowerCamelCase__ (_UpperCAmelCase=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=A__ ) ) class _snake_case ( A__ ): _lowercase : Optional[Any] = None _lowercase : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = dataset_module_factory(a , cache_dir=a) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=a) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=a , config_name=a , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=a).replace(os.sep , '/'), config.DATASET_INFO_FILENAME, ]) SCREAMING_SNAKE_CASE = cached_path(a , cache_dir=a) self.assertTrue(os.path.exists(a)) @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('test_hf_gcp') / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert "train" in ds assert isinstance(ds['train'] , _UpperCAmelCase) assert next(iter(ds['train']))
73
0
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE = 1000 ) ->int: """simple docstring""" lowerCAmelCase__ :List[str] = 3 lowerCAmelCase__ :str = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(F'''{solution() = }''')
93
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json' ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class UpperCAmelCase_ ( __A ): """simple docstring""" UpperCamelCase_ = '''speech_to_text_2''' UpperCamelCase_ = ['''past_key_values'''] UpperCamelCase_ = {'''num_attention_heads''': '''decoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self : Tuple , UpperCAmelCase : Dict=1_0000 , UpperCAmelCase : Dict=6 , UpperCAmelCase : Dict=2048 , UpperCAmelCase : int=4 , UpperCAmelCase : Union[str, Any]=0.0 , UpperCAmelCase : Union[str, Any]=True , UpperCAmelCase : Dict="relu" , UpperCAmelCase : List[str]=256 , UpperCAmelCase : List[Any]=0.1 , UpperCAmelCase : Any=0.0 , UpperCAmelCase : int=0.0 , UpperCAmelCase : int=0.0_2 , UpperCAmelCase : Dict=2 , UpperCAmelCase : Tuple=True , UpperCAmelCase : List[Any]=1 , UpperCAmelCase : Any=0 , UpperCAmelCase : Dict=2 , UpperCAmelCase : str=1024 , **UpperCAmelCase : Optional[Any] , ) -> Dict: '''simple docstring''' lowercase : Dict =vocab_size lowercase : Optional[Any] =d_model lowercase : List[str] =decoder_ffn_dim lowercase : Union[str, Any] =decoder_layers lowercase : Any =decoder_attention_heads lowercase : Optional[Any] =dropout lowercase : Optional[int] =attention_dropout lowercase : int =activation_dropout lowercase : List[str] =activation_function lowercase : List[str] =init_std lowercase : str =decoder_layerdrop lowercase : List[Any] =use_cache lowercase : List[str] =decoder_layers lowercase : List[str] =scale_embedding # scale factor will be sqrt(d_model) if True lowercase : Any =max_target_positions super().__init__( pad_token_id=UpperCAmelCase , bos_token_id=UpperCAmelCase , eos_token_id=UpperCAmelCase , decoder_start_token_id=UpperCAmelCase , **UpperCAmelCase , )
94
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append('10000000') else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowerCamelCase_ = random.Random() def snake_case ( A__ ,A__=1.0 ,A__=None ,A__=None ): if rng is None: UpperCAmelCase_ : str = global_rng UpperCAmelCase_ : str = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase_ (unittest.TestCase ): def __init__( self : List[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Any=7 , lowerCAmelCase_ : Dict=400 , lowerCAmelCase_ : int=2_000 , lowerCAmelCase_ : int=1 , lowerCAmelCase_ : str=0.0 , lowerCAmelCase_ : Optional[Any]=16_000 , lowerCAmelCase_ : Dict=True , lowerCAmelCase_ : Tuple=True , ) -> Any: UpperCAmelCase_ : str = parent UpperCAmelCase_ : Tuple = batch_size UpperCAmelCase_ : Tuple = min_seq_length UpperCAmelCase_ : Any = max_seq_length UpperCAmelCase_ : Optional[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCAmelCase_ : List[Any] = feature_size UpperCAmelCase_ : List[Any] = padding_value UpperCAmelCase_ : Union[str, Any] = sampling_rate UpperCAmelCase_ : Union[str, Any] = return_attention_mask UpperCAmelCase_ : List[Any] = do_normalize def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : List[Any]=False , lowerCAmelCase_ : Optional[int]=False ) -> Union[str, Any]: def _flatten(lowerCAmelCase_ : List[str] ): return list(itertools.chain(*lowerCAmelCase_ ) ) if equal_length: UpperCAmelCase_ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size UpperCAmelCase_ : List[Any] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCAmelCase_ : str = [np.asarray(lowerCAmelCase_ ) for x in speech_inputs] return speech_inputs class UpperCamelCase_ (__A , unittest.TestCase ): __magic_name__ = WavaVecaFeatureExtractor def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: UpperCAmelCase_ : List[str] = WavaVecaFeatureExtractionTester(self ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : int ) -> List[str]: self.assertTrue(np.all(np.mean(lowerCAmelCase_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(lowerCAmelCase_ , axis=0 ) - 1 ) < 1e-3 ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: # Tests that all call wrap to encode_plus and batch_encode_plus UpperCAmelCase_ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCAmelCase_ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] UpperCAmelCase_ : Dict = [np.asarray(lowerCAmelCase_ ) for speech_input in speech_inputs] # Test not batched input UpperCAmelCase_ : List[Any] = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values UpperCAmelCase_ : int = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) # Test batched UpperCAmelCase_ : Optional[int] = feat_extract(lowerCAmelCase_ , return_tensors="np" ).input_values UpperCAmelCase_ : List[str] = feat_extract(lowerCAmelCase_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCAmelCase_ : Tuple = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCAmelCase_ : str = np.asarray(lowerCAmelCase_ ) UpperCAmelCase_ : Optional[Any] = feat_extract(lowerCAmelCase_ , return_tensors="np" ).input_values UpperCAmelCase_ : Optional[int] = feat_extract(lowerCAmelCase_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: UpperCAmelCase_ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase_ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] UpperCAmelCase_ : Optional[int] = ["longest", "max_length", "do_not_pad"] UpperCAmelCase_ : Union[str, Any] = [None, 1_600, None] for max_length, padding in zip(lowerCAmelCase_ , lowerCAmelCase_ ): UpperCAmelCase_ : str = feat_extract(lowerCAmelCase_ , padding=lowerCAmelCase_ , max_length=lowerCAmelCase_ , return_tensors="np" ) UpperCAmelCase_ : Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_000] ) self.assertTrue(input_values[0][1_000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_200] ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: UpperCAmelCase_ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase_ : Dict = range(800 , 1_400 , 200 ) UpperCAmelCase_ : Any = [floats_list((1, x) )[0] for x in lengths] UpperCAmelCase_ : Tuple = ["longest", "max_length", "do_not_pad"] UpperCAmelCase_ : Optional[Any] = [None, 1_600, None] for max_length, padding in zip(lowerCAmelCase_ , lowerCAmelCase_ ): UpperCAmelCase_ : List[Any] = feat_extract(lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding=lowerCAmelCase_ ) UpperCAmelCase_ : Dict = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1_000] ) self._check_zero_mean_unit_variance(input_values[2][:1_200] ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: UpperCAmelCase_ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase_ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] UpperCAmelCase_ : Optional[Any] = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=1_000 , padding="max_length" , return_tensors="np" ) UpperCAmelCase_ : Any = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: UpperCAmelCase_ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase_ : int = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] UpperCAmelCase_ : Optional[int] = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=1_000 , padding="longest" , return_tensors="np" ) UpperCAmelCase_ : List[str] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1_000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_000) ) UpperCAmelCase_ : str = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] UpperCAmelCase_ : List[str] = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=2_000 , padding="longest" , return_tensors="np" ) UpperCAmelCase_ : Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1_000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_200) ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: import torch UpperCAmelCase_ : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase_ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) UpperCAmelCase_ : Union[str, Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCAmelCase_ : List[Any] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) UpperCAmelCase_ : int = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: # this test makes sure that models that are using # group norm don't have their feature extractor return the # attention_mask for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: UpperCAmelCase_ : Optional[int] = WavaVecaConfig.from_pretrained(lowerCAmelCase_ ) UpperCAmelCase_ : Optional[Any] = WavaVecaFeatureExtractor.from_pretrained(lowerCAmelCase_ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == "layer" )
95
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ (_UpperCAmelCase): return 1.0 / (1.0 + np.exp(-_outputs)) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=_UpperCAmelCase) SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_UpperCAmelCase) class _snake_case ( A__ ): _lowercase : Tuple = '''sigmoid''' _lowercase : List[str] = '''softmax''' _lowercase : Tuple = '''none''' @add_end_docstrings( A__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class _snake_case ( A__ ): _lowercase : Optional[Any] = False _lowercase : Tuple = ClassificationFunction.NONE def __init__( self , **a) -> Optional[Any]: super().__init__(**a) 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 , a=None , a=None , a="" , **a) -> Tuple: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" SCREAMING_SNAKE_CASE = tokenizer_kwargs SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , 'return_all_scores') and return_all_scores is None: SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(a , a) or top_k is None: SCREAMING_SNAKE_CASE = top_k SCREAMING_SNAKE_CASE = 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`.' , a , ) if return_all_scores: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = 1 if isinstance(a , a): SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *a , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = super().__call__(*a , **a) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE = 'top_k' not in kwargs if isinstance(args[0] , a) 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 , a , **a) -> Dict[str, GenericTensor]: SCREAMING_SNAKE_CASE = self.framework if isinstance(a , a): return self.tokenizer(**a , return_tensors=a , **a) elif isinstance(a , a) and len(a) == 1 and isinstance(inputs[0] , a) 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=a , **a) elif isinstance(a , a): # 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(a , return_tensors=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: return self.model(**a) def SCREAMING_SNAKE_CASE__ ( self , a , a=None , a=1 , a=True) -> Any: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply') and function_to_apply is None: SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE = ClassificationFunction.NONE SCREAMING_SNAKE_CASE = model_outputs['logits'][0] SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE = sigmoid(a) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE = softmax(a) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE = 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()} SCREAMING_SNAKE_CASE = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a) ] if not _legacy: dict_scores.sort(key=lambda a: x["score"] , reverse=a) if top_k is not None: SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
73
0
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __A ( unittest.TestCase ): def lowerCamelCase__ ( self : str ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCamelCase__ ( self : List[Any] ) -> Optional[int]: torch.manual_seed(0 ) __magic_name__: Dict = UNetaDModel( sample_size=(3_2, 6_4) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""AttnDownBlock2D""", """DownBlock2D""") , up_block_types=("""UpBlock2D""", """AttnUpBlock2D""") , ) return model @property def lowerCamelCase__ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) __magic_name__: Tuple = UNetaDConditionModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""") , up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""") , cross_attention_dim=1_0 , ) return model @property def lowerCamelCase__ ( self : Union[str, Any] ) -> Optional[Any]: torch.manual_seed(0 ) __magic_name__: Any = AutoencoderKL( sample_size=(1_2_8, 6_4) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""") , up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""") , ) __magic_name__: Union[str, Any] = UNetaDModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""AttnDownBlock2D""", """DownBlock2D""") , up_block_types=("""UpBlock2D""", """AttnUpBlock2D""") , ) return vqvae, unet @slow def lowerCamelCase__ ( self : int ) -> Union[str, Any]: __magic_name__: Tuple = """cpu""" # ensure determinism for the device-dependent torch.Generator __magic_name__: Dict = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) __magic_name__: Optional[int] = DDPMScheduler() __magic_name__: str = AudioDiffusionPipeline(vqvae=__snake_case , unet=self.dummy_unet , mel=__snake_case , scheduler=__snake_case ) __magic_name__: Any = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) __magic_name__: Optional[Any] = torch.Generator(device=__snake_case ).manual_seed(4_2 ) __magic_name__: Any = pipe(generator=__snake_case , steps=4 ) __magic_name__: Any = output.audios[0] __magic_name__: List[str] = output.images[0] __magic_name__: int = torch.Generator(device=__snake_case ).manual_seed(4_2 ) __magic_name__: List[str] = pipe(generator=__snake_case , steps=4 , return_dict=__snake_case ) __magic_name__: Optional[int] = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) __magic_name__: Tuple = np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] __magic_name__: List[str] = np.frombuffer(image_from_tuple.tobytes() , dtype="""uint8""" )[:1_0] __magic_name__: str = np.array([6_9, 2_5_5, 2_5_5, 2_5_5, 0, 0, 7_7, 1_8_1, 1_2, 1_2_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 __magic_name__: Optional[Any] = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) __magic_name__: Optional[Any] = DDIMScheduler() __magic_name__: Optional[Any] = self.dummy_vqvae_and_unet __magic_name__: int = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=__snake_case , scheduler=__snake_case ) __magic_name__: str = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) np.random.seed(0 ) __magic_name__: Any = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) __magic_name__: Any = torch.Generator(device=__snake_case ).manual_seed(4_2 ) __magic_name__: Optional[Any] = pipe(raw_audio=__snake_case , generator=__snake_case , start_step=5 , steps=1_0 ) __magic_name__: List[str] = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) __magic_name__: str = np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] __magic_name__: Optional[Any] = np.array([1_2_0, 1_1_7, 1_1_0, 1_0_9, 1_3_8, 1_6_7, 1_3_8, 1_4_8, 1_3_2, 1_2_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 __magic_name__: int = self.dummy_unet_condition __magic_name__: List[Any] = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=__snake_case , mel=__snake_case , scheduler=__snake_case ) __magic_name__: List[Any] = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) np.random.seed(0 ) __magic_name__: Tuple = torch.rand((1, 1, 1_0) ) __magic_name__: Tuple = pipe(generator=__snake_case , encoding=__snake_case ) __magic_name__: int = output.images[0] __magic_name__: List[Any] = np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] __magic_name__: Optional[int] = np.array([1_0_7, 1_0_3, 1_2_0, 1_2_7, 1_4_2, 1_2_2, 1_1_3, 1_2_2, 9_7, 1_1_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class __A ( unittest.TestCase ): def lowerCamelCase__ ( self : Any ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self : Union[str, Any] ) -> List[str]: __magic_name__: Dict = torch_device __magic_name__: Dict = DiffusionPipeline.from_pretrained("""teticio/audio-diffusion-ddim-256""" ) __magic_name__: List[Any] = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) __magic_name__: Dict = torch.Generator(device=__snake_case ).manual_seed(4_2 ) __magic_name__: str = pipe(generator=__snake_case ) __magic_name__: str = output.audios[0] __magic_name__: Any = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] __magic_name__: List[str] = np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] __magic_name__: Any = np.array([1_5_1, 1_6_7, 1_5_4, 1_4_4, 1_2_2, 1_3_4, 1_2_1, 1_0_5, 7_0, 2_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
96
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { 'microsoft/unispeech-sat-base-100h-libri-ft': ( 'https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json' ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class lowercase__( UpperCAmelCase ): """simple docstring""" a :Any = 'unispeech-sat' def __init__( self : Any , SCREAMING_SNAKE_CASE_ : Any=3_2 , SCREAMING_SNAKE_CASE_ : Any=7_6_8 , SCREAMING_SNAKE_CASE_ : Optional[Any]=1_2 , SCREAMING_SNAKE_CASE_ : int=1_2 , SCREAMING_SNAKE_CASE_ : str=3_0_7_2 , SCREAMING_SNAKE_CASE_ : Dict="gelu" , SCREAMING_SNAKE_CASE_ : int=0.1 , SCREAMING_SNAKE_CASE_ : Any=0.1 , SCREAMING_SNAKE_CASE_ : Tuple=0.1 , SCREAMING_SNAKE_CASE_ : Tuple=0.0 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE_ : Tuple=0.1 , SCREAMING_SNAKE_CASE_ : Dict=0.1 , SCREAMING_SNAKE_CASE_ : List[str]=0.02 , SCREAMING_SNAKE_CASE_ : Optional[Any]=1e-5 , SCREAMING_SNAKE_CASE_ : Union[str, Any]="group" , SCREAMING_SNAKE_CASE_ : Optional[Any]="gelu" , SCREAMING_SNAKE_CASE_ : List[str]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , SCREAMING_SNAKE_CASE_ : Tuple=(5, 2, 2, 2, 2, 2, 2) , SCREAMING_SNAKE_CASE_ : List[str]=(1_0, 3, 3, 3, 3, 2, 2) , SCREAMING_SNAKE_CASE_ : Optional[Any]=False , SCREAMING_SNAKE_CASE_ : Any=1_2_8 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1_6 , SCREAMING_SNAKE_CASE_ : Dict=False , SCREAMING_SNAKE_CASE_ : List[Any]=True , SCREAMING_SNAKE_CASE_ : Tuple=0.05 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE_ : List[Any]=2 , SCREAMING_SNAKE_CASE_ : Tuple=0.0 , SCREAMING_SNAKE_CASE_ : Optional[Any]=1_0 , SCREAMING_SNAKE_CASE_ : int=0 , SCREAMING_SNAKE_CASE_ : Tuple=3_2_0 , SCREAMING_SNAKE_CASE_ : Dict=2 , SCREAMING_SNAKE_CASE_ : Dict=0.1 , SCREAMING_SNAKE_CASE_ : List[str]=1_0_0 , SCREAMING_SNAKE_CASE_ : str=2_5_6 , SCREAMING_SNAKE_CASE_ : List[str]=2_5_6 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE_ : Dict="mean" , SCREAMING_SNAKE_CASE_ : Dict=False , SCREAMING_SNAKE_CASE_ : Dict=False , SCREAMING_SNAKE_CASE_ : Tuple=2_5_6 , SCREAMING_SNAKE_CASE_ : Optional[int]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0) , SCREAMING_SNAKE_CASE_ : List[Any]=(5, 3, 3, 1, 1) , SCREAMING_SNAKE_CASE_ : Dict=(1, 2, 3, 1, 1) , SCREAMING_SNAKE_CASE_ : Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE_ : List[Any]=0 , SCREAMING_SNAKE_CASE_ : List[Any]=1 , SCREAMING_SNAKE_CASE_ : Optional[Any]=2 , SCREAMING_SNAKE_CASE_ : List[str]=5_0_4 , **SCREAMING_SNAKE_CASE_ : Dict , ) -> Any: super().__init__(**SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ ) lowercase_ = hidden_size lowercase_ = feat_extract_norm lowercase_ = feat_extract_activation lowercase_ = list(SCREAMING_SNAKE_CASE_ ) lowercase_ = list(SCREAMING_SNAKE_CASE_ ) lowercase_ = list(SCREAMING_SNAKE_CASE_ ) lowercase_ = conv_bias lowercase_ = num_conv_pos_embeddings lowercase_ = num_conv_pos_embedding_groups lowercase_ = len(self.conv_dim ) lowercase_ = num_hidden_layers lowercase_ = intermediate_size lowercase_ = hidden_act lowercase_ = num_attention_heads lowercase_ = hidden_dropout lowercase_ = attention_dropout lowercase_ = activation_dropout lowercase_ = feat_proj_dropout lowercase_ = final_dropout lowercase_ = layerdrop lowercase_ = layer_norm_eps lowercase_ = initializer_range lowercase_ = vocab_size lowercase_ = num_clusters lowercase_ = do_stable_layer_norm lowercase_ = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowercase_ = apply_spec_augment lowercase_ = mask_time_prob lowercase_ = mask_time_length lowercase_ = mask_time_min_masks lowercase_ = mask_feature_prob lowercase_ = mask_feature_length lowercase_ = mask_feature_min_masks # parameters for pretraining with codevector quantized representations lowercase_ = num_codevectors_per_group lowercase_ = num_codevector_groups lowercase_ = contrastive_logits_temperature lowercase_ = feat_quantizer_dropout lowercase_ = num_negatives lowercase_ = codevector_dim lowercase_ = proj_codevector_dim lowercase_ = diversity_loss_weight # ctc loss lowercase_ = ctc_loss_reduction lowercase_ = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. lowercase_ = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. lowercase_ = list(SCREAMING_SNAKE_CASE_ ) lowercase_ = list(SCREAMING_SNAKE_CASE_ ) lowercase_ = list(SCREAMING_SNAKE_CASE_ ) lowercase_ = xvector_output_dim @property def _lowercase ( self : Optional[Any] ) -> Any: return functools.reduce(operator.mul , self.conv_stride , 1 )
97
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
0
'''simple docstring''' import argparse import intel_extension_for_pytorch as ipex import torch from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline lowercase__ : int = argparse.ArgumentParser('Stable Diffusion script with intel optimization', add_help=False) parser.add_argument('--dpm', action='store_true', help='Enable DPMSolver or not') parser.add_argument('--steps', default=None, type=int, help='Num inference steps') lowercase__ : Union[str, Any] = parser.parse_args() lowercase__ : Union[str, Any] = 'cpu' lowercase__ : Tuple = 'a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings' lowercase__ : List[Any] = 'path-to-your-trained-model' lowercase__ : Optional[Any] = StableDiffusionPipeline.from_pretrained(model_id) if args.dpm: lowercase__ : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) lowercase__ : Dict = pipe.to(device) # to channels last lowercase__ : Any = pipe.unet.to(memory_format=torch.channels_last) lowercase__ : Dict = pipe.vae.to(memory_format=torch.channels_last) lowercase__ : Any = pipe.text_encoder.to(memory_format=torch.channels_last) if pipe.requires_safety_checker: lowercase__ : Union[str, Any] = pipe.safety_checker.to(memory_format=torch.channels_last) # optimize with ipex lowercase__ : List[str] = torch.randn(2, 4, 64, 64) lowercase__ : int = torch.rand(1) * 9_99 lowercase__ : Optional[int] = torch.randn(2, 77, 7_68) lowercase__ : List[str] = (sample, timestep, encoder_hidden_status) try: lowercase__ : Optional[Any] = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example) except Exception: lowercase__ : Any = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True) lowercase__ : Tuple = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True) lowercase__ : Any = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True) if pipe.requires_safety_checker: lowercase__ : Union[str, Any] = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True) # compute lowercase__ : Optional[Any] = 6_66 lowercase__ : Tuple = torch.Generator(device).manual_seed(seed) lowercase__ : Dict = {'generator': generator} if args.steps is not None: lowercase__ : int = args.steps with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa): lowercase__ : Dict = pipe(prompt, **generate_kwargs).images[0] # save image image.save('generated.png')
98
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''decision_transformer''' _lowercase : str = ['''past_key_values'''] _lowercase : Union[str, Any] = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=17 , a=4 , a=128 , a=4096 , a=True , a=1 , a=1024 , a=3 , a=1 , a=None , a="relu" , a=0.1 , a=0.1 , a=0.1 , a=1E-5 , a=0.02 , a=True , a=True , a=5_0256 , a=5_0256 , a=False , a=False , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=a , eos_token_id=a , **a)
73
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE = 1_6 SCREAMING_SNAKE_CASE = 3_2 def a (lowerCAmelCase__ , lowerCAmelCase__ = 16 ): __a = AutoTokenizer.from_pretrained("""bert-base-cased""" ) __a = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(lowerCAmelCase__ ): # max_length=None => use the model max length (it's actually the default) __a = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __a = datasets.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(lowerCAmelCase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. __a = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __a = 16 elif accelerator.mixed_precision != "no": __a = 8 else: __a = None return tokenizer.pad( lowerCAmelCase__ , padding="""longest""" , max_length=lowerCAmelCase__ , pad_to_multiple_of=lowerCAmelCase__ , return_tensors="""pt""" , ) # Instantiate dataloaders. __a = DataLoader( tokenized_datasets["""train"""] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) __a = DataLoader( tokenized_datasets["""validation"""] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders SCREAMING_SNAKE_CASE = mocked_dataloaders # noqa: F811 def a (lowerCAmelCase__ , lowerCAmelCase__ ): # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , lowerCAmelCase__ ) == "1": __a = 2 # New Code # __a = int(args.gradient_accumulation_steps ) __a = int(args.local_sgd_steps ) # Initialize accelerator __a = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=lowerCAmelCase__ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a = config["""lr"""] __a = int(config["""num_epochs"""] ) __a = int(config["""seed"""] ) __a = int(config["""batch_size"""] ) __a = evaluate.load("""glue""" , """mrpc""" ) set_seed(lowerCAmelCase__ ) __a , __a = get_dataloaders(lowerCAmelCase__ , lowerCAmelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=lowerCAmelCase__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __a = model.to(accelerator.device ) # Instantiate optimizer __a = AdamW(params=model.parameters() , lr=lowerCAmelCase__ ) # Instantiate scheduler __a = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase__ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a , __a , __a , __a , __a = accelerator.prepare( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Now we train the model for epoch in range(lowerCAmelCase__ ): model.train() with LocalSGD( accelerator=lowerCAmelCase__ , model=lowerCAmelCase__ , local_sgd_steps=lowerCAmelCase__ , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(lowerCAmelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(lowerCAmelCase__ ): __a = model(**lowerCAmelCase__ ) __a = output.loss accelerator.backward(lowerCAmelCase__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(lowerCAmelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __a = model(**lowerCAmelCase__ ) __a = outputs.logits.argmax(dim=-1 ) __a , __a = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=lowerCAmelCase__ , references=lowerCAmelCase__ , ) __a = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , lowerCAmelCase__ ) def a (): __a = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=lowerCAmelCase__ , default=lowerCAmelCase__ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=lowerCAmelCase__ , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument( """--local_sgd_steps""" , type=lowerCAmelCase__ , default=8 , help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) __a = parser.parse_args() __a = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": main()
99
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[int] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _A : str = { """configuration_albert""": ["""ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """AlbertConfig""", """AlbertOnnxConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : List[Any] = ["""AlbertTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Dict = ["""AlbertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : int = [ """ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """AlbertForMaskedLM""", """AlbertForMultipleChoice""", """AlbertForPreTraining""", """AlbertForQuestionAnswering""", """AlbertForSequenceClassification""", """AlbertForTokenClassification""", """AlbertModel""", """AlbertPreTrainedModel""", """load_tf_weights_in_albert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Optional[Any] = [ """TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFAlbertForMaskedLM""", """TFAlbertForMultipleChoice""", """TFAlbertForPreTraining""", """TFAlbertForQuestionAnswering""", """TFAlbertForSequenceClassification""", """TFAlbertForTokenClassification""", """TFAlbertMainLayer""", """TFAlbertModel""", """TFAlbertPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Union[str, Any] = [ """FlaxAlbertForMaskedLM""", """FlaxAlbertForMultipleChoice""", """FlaxAlbertForPreTraining""", """FlaxAlbertForQuestionAnswering""", """FlaxAlbertForSequenceClassification""", """FlaxAlbertForTokenClassification""", """FlaxAlbertModel""", """FlaxAlbertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert import AlbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert_fast import AlbertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_albert import ( ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, AlbertPreTrainedModel, load_tf_weights_in_albert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_albert import ( TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFAlbertForMaskedLM, TFAlbertForMultipleChoice, TFAlbertForPreTraining, TFAlbertForQuestionAnswering, TFAlbertForSequenceClassification, TFAlbertForTokenClassification, TFAlbertMainLayer, TFAlbertModel, TFAlbertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, FlaxAlbertPreTrainedModel, ) else: import sys _A : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
100
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class __lowercase (__SCREAMING_SNAKE_CASE ): """simple docstring""" _UpperCAmelCase = """Speech2TextFeatureExtractor""" _UpperCAmelCase = """Speech2TextTokenizer""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" super().__init__(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = self.feature_extractor SCREAMING_SNAKE_CASE_ : Union[str, Any] = False def __call__( self , *lowerCAmelCase__ , **lowerCAmelCase__ ): """simple docstring""" if self._in_target_context_manager: return self.current_processor(*lowerCAmelCase__ , **lowerCAmelCase__ ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('raw_speech' ) else: SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.pop('audio' , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Tuple = kwargs.pop('sampling_rate' , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('text' , lowerCAmelCase__ ) if len(lowerCAmelCase__ ) > 0: SCREAMING_SNAKE_CASE_ : Dict = args[0] SCREAMING_SNAKE_CASE_ : str = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: SCREAMING_SNAKE_CASE_ : List[str] = self.feature_extractor(lowerCAmelCase__ , *lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , **lowerCAmelCase__ ) if text is not None: SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(lowerCAmelCase__ , **lowerCAmelCase__ ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE_ : int = encodings['input_ids'] return inputs def UpperCamelCase__ ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ): """simple docstring""" return self.tokenizer.batch_decode(*lowerCAmelCase__ , **lowerCAmelCase__ ) def UpperCamelCase__ ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ): """simple docstring""" return self.tokenizer.decode(*lowerCAmelCase__ , **lowerCAmelCase__ ) @contextmanager def UpperCamelCase__ ( self ): """simple docstring""" warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) SCREAMING_SNAKE_CASE_ : str = True SCREAMING_SNAKE_CASE_ : List[str] = self.tokenizer yield SCREAMING_SNAKE_CASE_ : List[str] = self.feature_extractor SCREAMING_SNAKE_CASE_ : Optional[Any] = False
101
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): if radian_mode: return [magnitude * cos(_UpperCAmelCase), magnitude * sin(_UpperCAmelCase)] return [magnitude * cos(radians(_UpperCAmelCase)), magnitude * sin(radians(_UpperCAmelCase))] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 10**-1): SCREAMING_SNAKE_CASE = cross(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(_UpperCAmelCase) return abs(_UpperCAmelCase) < eps if __name__ == "__main__": # Test to check if it works a_ : int = array( [ polar_force(718.4, 1_80 - 30), polar_force(879.54, 45), polar_force(1_00, -90), ] ) a_ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg a_ : Dict = array( [ polar_force(30 * 9.81, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) a_ : Any = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg a_ : int = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) a_ : Optional[Any] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
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 __magic_name__ : List[Any] = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class lowercase__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *_A , **_A ): '''simple docstring''' super().__init__(*_A , **_A ) requires_backends(self , """decord""" ) self.check_model_type(_A ) def _a ( self , _A=None , _A=None , _A=None ): '''simple docstring''' UpperCamelCase : Any = {} if frame_sampling_rate is not None: UpperCamelCase : int = frame_sampling_rate if num_frames is not None: UpperCamelCase : List[Any] = num_frames UpperCamelCase : int = {} if top_k is not None: UpperCamelCase : List[Any] = top_k return preprocess_params, {}, postprocess_params def __call__( self , _A , **_A ): '''simple docstring''' return super().__call__(_A , **_A ) def _a ( self , _A , _A=None , _A=1 ): '''simple docstring''' if num_frames is None: UpperCamelCase : Optional[int] = self.model.config.num_frames if video.startswith("""http://""" ) or video.startswith("""https://""" ): UpperCamelCase : Optional[int] = BytesIO(requests.get(_A ).content ) UpperCamelCase : Any = VideoReader(_A ) videoreader.seek(0 ) UpperCamelCase : Optional[int] = 0 UpperCamelCase : int = num_frames * frame_sampling_rate - 1 UpperCamelCase : List[Any] = np.linspace(_A , _A , num=_A , dtype=np.intaa ) UpperCamelCase : List[Any] = videoreader.get_batch(_A ).asnumpy() UpperCamelCase : Any = list(_A ) UpperCamelCase : Dict = self.image_processor(_A , return_tensors=self.framework ) return model_inputs def _a ( self , _A ): '''simple docstring''' UpperCamelCase : str = self.model(**_A ) return model_outputs def _a ( self , _A , _A=5 ): '''simple docstring''' if top_k > self.model.config.num_labels: UpperCamelCase : Optional[Any] = self.model.config.num_labels if self.framework == "pt": UpperCamelCase : List[str] = model_outputs.logits.softmax(-1 )[0] UpperCamelCase , UpperCamelCase : Union[str, Any] = probs.topk(_A ) else: raise ValueError(f"""Unsupported framework: {self.framework}""" ) UpperCamelCase : int = scores.tolist() UpperCamelCase : str = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_A , _A )]
102
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : int = { '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 _snake_case ( A__ ): _lowercase : Dict = '''cvt''' def __init__( self , a=3 , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[64, 192, 384] , a=[1, 3, 6] , a=[1, 2, 10] , a=[4.0, 4.0, 4.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.1] , a=[True, True, True] , a=[False, False, True] , a=["dw_bn", "dw_bn", "dw_bn"] , a=[3, 3, 3] , a=[1, 1, 1] , a=[2, 2, 2] , a=[1, 1, 1] , a=[1, 1, 1] , a=0.02 , a=1E-12 , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = drop_rate SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = qkv_projection_method SCREAMING_SNAKE_CASE = kernel_qkv SCREAMING_SNAKE_CASE = padding_kv SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = padding_q SCREAMING_SNAKE_CASE = stride_q SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps
73
0
"""simple docstring""" import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class UpperCAmelCase ( __SCREAMING_SNAKE_CASE,unittest.TestCase ): A__ : Optional[int] = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def __UpperCAmelCase ( self : Tuple , __lowerCamelCase : Dict=0 ): """simple docstring""" _snake_case = floats_tensor((1, 3, 1_2_8, 1_2_8) , rng=random.Random(__lowerCamelCase ) ) _snake_case = np.random.RandomState(__lowerCamelCase ) _snake_case = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 3, '''strength''': 0.7_5, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def __UpperCAmelCase ( self : str ): """simple docstring""" _snake_case = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) _snake_case = self.get_dummy_inputs() _snake_case = pipe(**__lowerCamelCase ).images _snake_case = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 1_2_8, 1_2_8, 3) _snake_case = np.array([0.6_9_6_4_3, 0.5_8_4_8_4, 0.5_0_3_1_4, 0.5_8_7_6_0, 0.5_5_3_6_8, 0.5_9_6_4_3, 0.5_1_5_2_9, 0.4_1_2_1_7, 0.4_9_0_8_7] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def __UpperCAmelCase ( self : Tuple ): """simple docstring""" _snake_case = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) _snake_case = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) _snake_case = self.get_dummy_inputs() _snake_case = pipe(**__lowerCamelCase ).images _snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) _snake_case = np.array([0.6_1_7_3_7, 0.5_4_6_4_2, 0.5_3_1_8_3, 0.5_4_4_6_5, 0.5_2_7_4_2, 0.6_0_5_2_5, 0.4_9_9_6_9, 0.4_0_6_5_5, 0.4_8_1_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def __UpperCAmelCase ( self : Optional[int] ): """simple docstring""" _snake_case = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) _snake_case = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) # warmup pass to apply optimizations _snake_case = pipe(**self.get_dummy_inputs() ) _snake_case = self.get_dummy_inputs() _snake_case = pipe(**__lowerCamelCase ).images _snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) _snake_case = np.array([0.5_2_7_6_1, 0.5_9_9_7_7, 0.4_9_0_3_3, 0.4_9_6_1_9, 0.5_4_2_8_2, 0.5_0_3_1_1, 0.4_7_6_0_0, 0.4_0_9_1_8, 0.4_5_2_0_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def __UpperCAmelCase ( self : int ): """simple docstring""" _snake_case = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) _snake_case = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) _snake_case = self.get_dummy_inputs() _snake_case = pipe(**__lowerCamelCase ).images _snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) _snake_case = np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def __UpperCAmelCase ( self : Optional[int] ): """simple docstring""" _snake_case = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) _snake_case = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) _snake_case = self.get_dummy_inputs() _snake_case = pipe(**__lowerCamelCase ).images _snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) _snake_case = np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" _snake_case = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) _snake_case = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) _snake_case = self.get_dummy_inputs() _snake_case = pipe(**__lowerCamelCase ).images _snake_case = image[0, -3:, -3:, -1] assert image.shape == (1, 1_2_8, 1_2_8, 3) _snake_case = np.array([0.6_5_3_3_1, 0.5_8_2_7_7, 0.4_8_2_0_4, 0.5_6_0_5_9, 0.5_3_6_6_5, 0.5_6_2_3_5, 0.5_0_9_6_9, 0.4_0_0_0_9, 0.4_6_5_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): @property def __UpperCAmelCase ( self : Optional[int] ): """simple docstring""" return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __UpperCAmelCase ( self : List[str] ): """simple docstring""" _snake_case = ort.SessionOptions() _snake_case = False return options def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" _snake_case = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) _snake_case = init_image.resize((7_6_8, 5_1_2) ) # using the PNDM scheduler by default _snake_case = OnnxStableDiffusionImgaImgPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''onnx''' , safety_checker=__lowerCamelCase , feature_extractor=__lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) _snake_case = '''A fantasy landscape, trending on artstation''' _snake_case = np.random.RandomState(0 ) _snake_case = pipe( prompt=__lowerCamelCase , image=__lowerCamelCase , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=1_0 , generator=__lowerCamelCase , output_type='''np''' , ) _snake_case = output.images _snake_case = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 7_6_8, 3) _snake_case = np.array([0.4_9_0_9, 0.5_0_5_9, 0.5_3_7_2, 0.4_6_2_3, 0.4_8_7_6, 0.5_0_4_9, 0.4_8_2_0, 0.4_9_5_6, 0.5_0_1_9] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def __UpperCAmelCase ( self : Dict ): """simple docstring""" _snake_case = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) _snake_case = init_image.resize((7_6_8, 5_1_2) ) _snake_case = LMSDiscreteScheduler.from_pretrained( '''runwayml/stable-diffusion-v1-5''' , subfolder='''scheduler''' , revision='''onnx''' ) _snake_case = OnnxStableDiffusionImgaImgPipeline.from_pretrained( '''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , scheduler=__lowerCamelCase , safety_checker=__lowerCamelCase , feature_extractor=__lowerCamelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) _snake_case = '''A fantasy landscape, trending on artstation''' _snake_case = np.random.RandomState(0 ) _snake_case = pipe( prompt=__lowerCamelCase , image=__lowerCamelCase , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=2_0 , generator=__lowerCamelCase , output_type='''np''' , ) _snake_case = output.images _snake_case = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 7_6_8, 3) _snake_case = np.array([0.8_0_4_3, 0.9_2_6, 0.9_5_8_1, 0.8_1_1_9, 0.8_9_5_4, 0.9_1_3, 0.7_2_0_9, 0.7_4_6_3, 0.7_4_3_1] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
103
def lowerCamelCase__ (_UpperCAmelCase = 10 , _UpperCAmelCase = 1000 , _UpperCAmelCase = True): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)') return min_val if option else max_val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int((number_a + number_a) / 2) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)') if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value') def answer(_UpperCAmelCase) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...') SCREAMING_SNAKE_CASE = lower SCREAMING_SNAKE_CASE = higher SCREAMING_SNAKE_CASE = [] while True: SCREAMING_SNAKE_CASE = get_avg(_UpperCAmelCase , _UpperCAmelCase) last_numbers.append(_UpperCAmelCase) if answer(_UpperCAmelCase) == "low": SCREAMING_SNAKE_CASE = number elif answer(_UpperCAmelCase) == "high": SCREAMING_SNAKE_CASE = number else: break print(F'''guess the number : {last_numbers[-1]}''') print(F'''details : {last_numbers!s}''') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Enter lower value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter high value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter value to guess : ').strip()) guess_the_number(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
"""simple docstring""" def _lowerCamelCase ( UpperCAmelCase_ : int ) -> int: """simple docstring""" assert ( isinstance(UpperCAmelCase_, UpperCAmelCase_ ) and number_of_steps > 0 ), F"""number_of_steps needs to be positive integer, your input {number_of_steps}""" if number_of_steps == 1: return 1 A__ , A__ = 1, 1 for _ in range(number_of_steps - 1 ): A__ , A__ = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
104
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class _snake_case : def __init__( self , a , a=13 , 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=512 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> Union[str, 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 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: 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 = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , use_stable_embedding=a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Any: SCREAMING_SNAKE_CASE = OpenLlamaModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , ) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , ) SCREAMING_SNAKE_CASE = model(a , attention_mask=a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() # first forward pass SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , use_cache=a , ) SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , output_hidden_states=a , )['hidden_states'][0] SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , past_key_values=a , output_hidden_states=a , )['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1]).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1E-3)) def SCREAMING_SNAKE_CASE__ ( self) -> 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, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) _lowercase : str = (OpenLlamaForCausalLM,) if is_torch_available() else () _lowercase : List[str] = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) _lowercase : List[str] = False _lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = OpenLlamaModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'single_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'multi_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass @parameterized.expand([('linear',), ('dynamic',)]) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ids_tensor([1, 10] , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = OpenLlamaModel(a) original_model.to(a) original_model.eval() SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = {'type': scaling_type, 'factor': 10.0} SCREAMING_SNAKE_CASE = OpenLlamaModel(a) scaled_model.to(a) scaled_model.eval() SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a , a , atol=1E-5)) else: self.assertFalse(torch.allclose(a , a , atol=1E-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(a , a , atol=1E-5))
73
0
import json import os import unittest from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase_ ( lowerCamelCase_ , unittest.TestCase ): __a : List[Any] = XLMTokenizer __a : int = False def snake_case ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE_ : Any = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] SCREAMING_SNAKE_CASE_ : str = dict(zip(snake_case__ ,range(len(snake_case__ ) ) ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] SCREAMING_SNAKE_CASE_ : int = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE_ : str = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file ,'w' ) as fp: fp.write(json.dumps(snake_case__ ) ) with open(self.merges_file ,'w' ) as fp: fp.write('\n'.join(snake_case__ ) ) def snake_case ( self ,snake_case__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = 'lower newer' SCREAMING_SNAKE_CASE_ : Dict = 'lower newer' return input_text, output_text def snake_case ( self ): SCREAMING_SNAKE_CASE_ : List[Any] = XLMTokenizer(self.vocab_file ,self.merges_file ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 'lower' SCREAMING_SNAKE_CASE_ : Optional[Any] = ['low', 'er</w>'] SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.tokenize(snake_case__ ) self.assertListEqual(snake_case__ ,snake_case__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = tokens + ['<unk>'] SCREAMING_SNAKE_CASE_ : List[Any] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case__ ) ,snake_case__ ) @slow def snake_case ( self ): SCREAMING_SNAKE_CASE_ : int = XLMTokenizer.from_pretrained('xlm-mlm-en-2048' ) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer.encode('sequence builders' ,add_special_tokens=snake_case__ ) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer.encode('multi-sequence build' ,add_special_tokens=snake_case__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.build_inputs_with_special_tokens(snake_case__ ) SCREAMING_SNAKE_CASE_ : List[str] = tokenizer.build_inputs_with_special_tokens(snake_case__ ,snake_case__ ) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
105
from __future__ import annotations a_ : str = [] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for i in range(len(_UpperCAmelCase)): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase)): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , -1 , -1)): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , len(_UpperCAmelCase))): if board[i][j] == 1: return False return True def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if row >= len(_UpperCAmelCase): solution.append(_UpperCAmelCase) printboard(_UpperCAmelCase) print() return True for i in range(len(_UpperCAmelCase)): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 solve(_UpperCAmelCase , row + 1) SCREAMING_SNAKE_CASE = 0 return False def lowerCamelCase__ (_UpperCAmelCase): for i in range(len(_UpperCAmelCase)): for j in range(len(_UpperCAmelCase)): if board[i][j] == 1: print('Q' , end=' ') else: print('.' , end=' ') print() # n=int(input("The no. of queens")) a_ : Tuple = 8 a_ : int = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
73
0
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class lowerCAmelCase__ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , unittest.TestCase ): A_ : Union[str, Any] = StableUnCLIPPipeline A_ : Union[str, Any] = TEXT_TO_IMAGE_PARAMS A_ : Union[str, Any] = TEXT_TO_IMAGE_BATCH_PARAMS A_ : Optional[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS A_ : str = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false A_ : Optional[Any] = False def __UpperCamelCase ( self : Tuple ) -> str: A = 32 A = embedder_hidden_size # prior components torch.manual_seed(0 ) A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) A = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__UpperCamelCase , projection_dim=__UpperCamelCase , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) ) torch.manual_seed(0 ) A = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=__UpperCamelCase , num_layers=1 , ) torch.manual_seed(0 ) A = DDPMScheduler( variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1_000 , clip_sample=__UpperCamelCase , clip_sample_range=5.0 , beta_schedule='squaredcos_cap_v2' , ) # regular denoising components torch.manual_seed(0 ) A = StableUnCLIPImageNormalizer(embedding_dim=__UpperCamelCase ) A = DDPMScheduler(beta_schedule='squaredcos_cap_v2' ) torch.manual_seed(0 ) A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) A = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__UpperCamelCase , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) ) torch.manual_seed(0 ) A = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__UpperCamelCase , layers_per_block=1 , upcast_attention=__UpperCamelCase , use_linear_projection=__UpperCamelCase , ) torch.manual_seed(0 ) A = DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , prediction_type='v_prediction' , set_alpha_to_one=__UpperCamelCase , steps_offset=1 , ) torch.manual_seed(0 ) A = AutoencoderKL() A = { # prior components 'prior_tokenizer': prior_tokenizer, 'prior_text_encoder': prior_text_encoder, 'prior': prior, 'prior_scheduler': prior_scheduler, # image noising components 'image_normalizer': image_normalizer, 'image_noising_scheduler': image_noising_scheduler, # regular denoising components 'tokenizer': tokenizer, 'text_encoder': text_encoder, 'unet': unet, 'scheduler': scheduler, 'vae': vae, } return components def __UpperCamelCase ( self : Optional[int] , __UpperCamelCase : Optional[int] , __UpperCamelCase : str=0 ) -> Optional[int]: if str(__UpperCamelCase ).startswith('mps' ): A = torch.manual_seed(__UpperCamelCase ) else: A = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase ) A = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'prior_num_inference_steps': 2, 'output_type': 'numpy', } return inputs def __UpperCamelCase ( self : Union[str, Any] ) -> Union[str, Any]: A = torch_device == 'cpu' self._test_attention_slicing_forward_pass(test_max_difference=__UpperCamelCase ) def __UpperCamelCase ( self : Optional[int] ) -> Tuple: A = torch_device in ['cpu', 'mps'] self._test_inference_batch_single_identical(test_max_difference=__UpperCamelCase ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def __UpperCamelCase ( self : Any ) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self : List[Any] ) -> Tuple: A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy' ) A = StableUnCLIPPipeline.from_pretrained('fusing/stable-unclip-2-1-l' , torch_dtype=torch.floataa ) pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() A = torch.Generator(device='cpu' ).manual_seed(0 ) A = pipe('anime turle' , generator=__UpperCamelCase , output_type='np' ) A = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__UpperCamelCase , __UpperCamelCase ) def __UpperCamelCase ( self : List[str] ) -> Dict: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() A = StableUnCLIPPipeline.from_pretrained('fusing/stable-unclip-2-1-l' , torch_dtype=torch.floataa ) A = pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() A = pipe( 'anime turtle' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='np' , ) A = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
106
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) for optional_component in pipe._optional_components: self.assertTrue( getattr(a , a) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
0
'''simple docstring''' from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def _SCREAMING_SNAKE_CASE ( ): _A , _A = 9, 1_4 # noqa: F841 _A = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 1_4], [3, 4, 9], [5, 4, 1_0], [1, 7, 1_1], ] _A = defaultdict(__snake_case ) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost] ) adjancency[nodea].append([nodea, cost] ) _A = mst(__snake_case ) _A = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: _A = tuple(answer[:2] ) _A = tuple(edge[::-1] ) assert edge in result or reverse in result
107
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Any = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _snake_case ( A__ ): _lowercase : Optional[int] = '''unispeech''' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="mean" , a=False , a=False , a=256 , a=80 , a=0 , a=1 , a=2 , a=0.5 , **a , ) -> Optional[int]: super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE = replace_prob @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return functools.reduce(operator.mul , self.conv_stride , 1)
73
0
from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class SCREAMING_SNAKE_CASE__ : '''simple docstring''' _lowerCamelCase = 42 _lowerCamelCase = None _lowerCamelCase = None __a: Optional[int] = namedtuple('''CoinsDistribResult''', '''moves excess''') def _SCREAMING_SNAKE_CASE ( __snake_case ) -> int: if root is None: return 0 # Validation def count_nodes(__snake_case ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(__snake_case ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(__snake_case ) != count_coins(__snake_case ): raise ValueError("""The nodes number should be same as the number of coins""" ) # Main calculation def get_distrib(__snake_case ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) _UpperCAmelCase , _UpperCAmelCase = get_distrib(node.left ) _UpperCAmelCase , _UpperCAmelCase = get_distrib(node.right ) _UpperCAmelCase = 1 - left_distrib_excess _UpperCAmelCase = 1 - right_distrib_excess _UpperCAmelCase = ( left_distrib_moves + right_distrib_moves + abs(__snake_case ) + abs(__snake_case ) ) _UpperCAmelCase = node.data - coins_to_left - coins_to_right return CoinsDistribResult(__snake_case , __snake_case ) return get_distrib(__snake_case )[0] if __name__ == "__main__": import doctest doctest.testmod()
108
import argparse import collections import json import os import re import string import sys import numpy as np a_ : Optional[Any] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a_ : List[str] = None def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.') parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.') parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).') parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.') parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.') parser.add_argument('--verbose' , '-v' , action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa['answers']['text']) return qid_to_has_ans def lowerCamelCase__ (_UpperCAmelCase): def remove_articles(_UpperCAmelCase): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase) def white_space_fix(_UpperCAmelCase): return " ".join(text.split()) def remove_punc(_UpperCAmelCase): SCREAMING_SNAKE_CASE = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(_UpperCAmelCase): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase)))) def lowerCamelCase__ (_UpperCAmelCase): if not s: return [] return normalize_answer(_UpperCAmelCase).split() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int(normalize_answer(_UpperCAmelCase) == normalize_answer(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.Counter(_UpperCAmelCase) & collections.Counter(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(common.values()) if len(_UpperCAmelCase) == 0 or len(_UpperCAmelCase) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa['id'] SCREAMING_SNAKE_CASE = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase)] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [''] if qid not in preds: print(F'''Missing prediction for {qid}''') continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) SCREAMING_SNAKE_CASE = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) return exact_scores, fa_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid]) else: SCREAMING_SNAKE_CASE = s return new_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): if not qid_list: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values()) / total), ('f1', 1_00.0 * sum(fa_scores.values()) / total), ('total', total), ]) else: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list) / total), ('total', total), ]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post') plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(_UpperCAmelCase) plt.savefig(_UpperCAmelCase) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(_UpperCAmelCase): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1) SCREAMING_SNAKE_CASE = true_pos / float(_UpperCAmelCase) if i == len(_UpperCAmelCase) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase) recalls.append(_UpperCAmelCase) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return {"ap": 1_00.0 * avg_prec} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if out_image_dir and not os.path.exists(_UpperCAmelCase): os.makedirs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png') , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png') , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE = {k: float(_UpperCAmelCase) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png') , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(_UpperCAmelCase) / float(len(_UpperCAmelCase)) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title(F'''Histogram of no-answer probability: {name}''') plt.savefig(os.path.join(_UpperCAmelCase , F'''na_prob_hist_{name}.png''')) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) for i, qid in enumerate(_UpperCAmelCase): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 1_00.0 * best_score / len(_UpperCAmelCase), best_thresh def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def lowerCamelCase__ (): with open(OPTS.data_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset_json['data'] with open(OPTS.pred_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(_UpperCAmelCase) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns') if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns') histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns') if OPTS.out_file: with open(OPTS.out_file , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) else: print(json.dumps(_UpperCAmelCase , indent=2)) if __name__ == "__main__": a_ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
73
0
'''simple docstring''' import csv import tweepy # Twitter API credentials a = "" a = "" a = "" a = "" def __magic_name__ ( __UpperCAmelCase ) -> None: '''simple docstring''' __SCREAMING_SNAKE_CASE = tweepy.OAuthHandler(__UpperCAmelCase , __UpperCAmelCase ) auth.set_access_token(__UpperCAmelCase , __UpperCAmelCase ) __SCREAMING_SNAKE_CASE = tweepy.API(__UpperCAmelCase ) # initialize a list to hold all the tweepy Tweets __SCREAMING_SNAKE_CASE = [] # make initial request for most recent tweets (200 is the maximum allowed count) __SCREAMING_SNAKE_CASE = api.user_timeline(screen_name=__UpperCAmelCase , count=200 ) # save most recent tweets alltweets.extend(__UpperCAmelCase ) # save the id of the oldest tweet less one __SCREAMING_SNAKE_CASE = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(__UpperCAmelCase ) > 0: print(f"""getting tweets before {oldest}""" ) # all subsequent requests use the max_id param to prevent duplicates __SCREAMING_SNAKE_CASE = api.user_timeline( screen_name=__UpperCAmelCase , count=200 , max_id=__UpperCAmelCase ) # save most recent tweets alltweets.extend(__UpperCAmelCase ) # update the id of the oldest tweet less one __SCREAMING_SNAKE_CASE = alltweets[-1].id - 1 print(f"""...{len(__UpperCAmelCase )} tweets downloaded so far""" ) # transform the tweepy tweets into a 2D array that will populate the csv __SCREAMING_SNAKE_CASE = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(f"""new_{screen_name}_tweets.csv""" , """w""" ) as f: __SCREAMING_SNAKE_CASE = csv.writer(__UpperCAmelCase ) writer.writerow(["""id""", """created_at""", """text"""] ) writer.writerows(__UpperCAmelCase ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("FirePing32")
109
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a , ) super().__init__(*a , **a)
73
0
"""simple docstring""" import os from pathlib import Path def lowerCamelCase ( ): from torch.utils.cpp_extension import load UpperCAmelCase__ : str = Path(_snake_case ).resolve().parent.parent.parent / 'kernels' / 'deformable_detr' UpperCAmelCase__ : List[Any] = [ root / filename for filename in [ 'vision.cpp', os.path.join('cpu' ,'ms_deform_attn_cpu.cpp' ), os.path.join('cuda' ,'ms_deform_attn_cuda.cu' ), ] ] load( 'MultiScaleDeformableAttention' ,_snake_case ,with_cuda=_snake_case ,extra_include_paths=[str(_snake_case )] ,extra_cflags=['-DWITH_CUDA=1'] ,extra_cuda_cflags=[ '-DCUDA_HAS_FP16=1', '-D__CUDA_NO_HALF_OPERATORS__', '-D__CUDA_NO_HALF_CONVERSIONS__', '-D__CUDA_NO_HALF2_OPERATORS__', ] ,) import MultiScaleDeformableAttention as MSDA return MSDA
110
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
0
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class __lowercase ( A__): """simple docstring""" _A : Tuple = '''EncodecFeatureExtractor''' _A : Union[str, Any] = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__(self , lowercase__ , lowercase__ ): super().__init__(lowercase__ , lowercase__ ) snake_case_ : Tuple = self.feature_extractor snake_case_ : List[Any] = False def __UpperCamelCase (self , lowercase__=None , lowercase__=None , lowercase__=True ): return self.tokenizer.get_decoder_prompt_ids(task=lowercase__ , language=lowercase__ , no_timestamps=lowercase__ ) def __call__(self , *lowercase__ , **lowercase__ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*lowercase__ , **lowercase__ ) snake_case_ : Dict = kwargs.pop("""audio""" , lowercase__ ) snake_case_ : Union[str, Any] = kwargs.pop("""sampling_rate""" , lowercase__ ) snake_case_ : Tuple = kwargs.pop("""text""" , lowercase__ ) if len(lowercase__ ) > 0: snake_case_ : Tuple = args[0] snake_case_ : Optional[int] = 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: snake_case_ : Union[str, Any] = self.tokenizer(lowercase__ , **lowercase__ ) if audio is not None: snake_case_ : int = self.feature_extractor(lowercase__ , *lowercase__ , sampling_rate=lowercase__ , **lowercase__ ) if audio is None: return inputs elif text is None: return audio_inputs else: snake_case_ : str = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: snake_case_ : Tuple = audio_inputs["""padding_mask"""] return inputs def __UpperCamelCase (self , *lowercase__ , **lowercase__ ): snake_case_ : int = kwargs.pop("""audio""" , lowercase__ ) snake_case_ : List[str] = kwargs.pop("""padding_mask""" , lowercase__ ) if len(lowercase__ ) > 0: snake_case_ : Dict = args[0] snake_case_ : str = args[1:] if audio_values is not None: return self._decode_audio(lowercase__ , padding_mask=lowercase__ ) else: return self.tokenizer.batch_decode(*lowercase__ , **lowercase__ ) def __UpperCamelCase (self , *lowercase__ , **lowercase__ ): return self.tokenizer.decode(*lowercase__ , **lowercase__ ) def __UpperCamelCase (self , lowercase__ , lowercase__ = None ): snake_case_ : Tuple = to_numpy(lowercase__ ) snake_case_ , snake_case_ , snake_case_ : Any = audio_values.shape if padding_mask is None: return list(lowercase__ ) snake_case_ : int = to_numpy(lowercase__ ) # 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) snake_case_ : Tuple = seq_len - padding_mask.shape[-1] snake_case_ : List[Any] = 1 - self.feature_extractor.padding_value snake_case_ : List[str] = np.pad(lowercase__ , ((0, 0), (0, difference)) , """constant""" , constant_values=lowercase__ ) snake_case_ : List[Any] = audio_values.tolist() for i in range(lowercase__ ): snake_case_ : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] snake_case_ : Union[str, Any] = sliced_audio.reshape(lowercase__ , -1 ) return audio_values
480
import sys import turtle def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) if depth == 0: return triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) a_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') a_ : str = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
73
0
def _lowercase ( SCREAMING_SNAKE_CASE_ : List[Any] ): """simple docstring""" UpperCamelCase = [0] * len(_UpperCAmelCase ) UpperCamelCase = [] UpperCamelCase = [1] * len(_UpperCAmelCase ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(_UpperCAmelCase ) ): if indegree[i] == 0: queue.append(_UpperCAmelCase ) while queue: UpperCamelCase = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: UpperCamelCase = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(_UpperCAmelCase ) print(max(_UpperCAmelCase ) ) # Adjacency list of Graph __snake_case = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
386
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase _lowerCamelCase : Tuple = logging.get_logger(__name__) _lowerCamelCase : List[Any] = { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json', 'allenai/longformer-large-4096': 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json', 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json' ), } class UpperCamelCase_ ( A__ ): '''simple docstring''' UpperCAmelCase__ = '''longformer''' def __init__( self : Any , UpperCAmelCase__ : Tuple = 512 , UpperCAmelCase__ : str = 2 , UpperCAmelCase__ : Tuple = 1 , UpperCAmelCase__ : int = 0 , UpperCAmelCase__ : Optional[Any] = 2 , UpperCAmelCase__ : Optional[Any] = 30_522 , UpperCAmelCase__ : List[Any] = 768 , UpperCAmelCase__ : List[str] = 12 , UpperCAmelCase__ : Optional[Any] = 12 , UpperCAmelCase__ : int = 3_072 , UpperCAmelCase__ : int = "gelu" , UpperCAmelCase__ : Optional[Any] = 0.1 , UpperCAmelCase__ : List[Any] = 0.1 , UpperCAmelCase__ : Any = 512 , UpperCAmelCase__ : Union[str, Any] = 2 , UpperCAmelCase__ : Union[str, Any] = 0.02 , UpperCAmelCase__ : Union[str, Any] = 1e-12 , UpperCAmelCase__ : List[str] = False , **UpperCAmelCase__ : Optional[Any] , ) ->Dict: '''simple docstring''' super().__init__(pad_token_id=UpperCAmelCase__ , **UpperCAmelCase__) A__ = attention_window A__ = sep_token_id A__ = bos_token_id A__ = eos_token_id A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = hidden_act A__ = intermediate_size A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = type_vocab_size A__ = initializer_range A__ = layer_norm_eps A__ = onnx_export class UpperCamelCase_ ( A__ ): '''simple docstring''' def __init__( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str = "default" , UpperCAmelCase__ : Dict = None) ->Dict: '''simple docstring''' super().__init__(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) A__ = True @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": A__ = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: A__ = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''global_attention_mask''', dynamic_axis), ]) @property def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' A__ = super().outputs if self.task == "default": A__ = {0: '''batch'''} return outputs @property def SCREAMING_SNAKE_CASE ( self : List[Any]) ->float: '''simple docstring''' return 1e-4 @property def SCREAMING_SNAKE_CASE ( self : List[str]) ->int: '''simple docstring''' return max(super().default_onnx_opset , 14) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Union[str, Any] = -1 , UpperCAmelCase__ : Tuple = -1 , UpperCAmelCase__ : Tuple = False , UpperCAmelCase__ : List[Any] = None , ) ->Mapping[str, Any]: '''simple docstring''' A__ = super().generate_dummy_inputs( preprocessor=UpperCAmelCase__ , batch_size=UpperCAmelCase__ , seq_length=UpperCAmelCase__ , is_pair=UpperCAmelCase__ , framework=UpperCAmelCase__) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly A__ = torch.zeros_like(inputs['''input_ids''']) # make every second token global A__ = 1 return inputs
87
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'EleutherAI/gpt-neo-1.3B': 'https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class __snake_case ( A__ ): """simple docstring""" lowerCAmelCase_ : Any = '''gpt_neo''' lowerCAmelCase_ : int = ['''past_key_values'''] lowerCAmelCase_ : Tuple = {'''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self :str , UpperCamelCase__ :int=50_257 , UpperCamelCase__ :str=2_048 , UpperCamelCase__ :List[Any]=2_048 , UpperCamelCase__ :List[str]=24 , UpperCamelCase__ :Tuple=[[["global", "local"], 12]] , UpperCamelCase__ :Tuple=16 , UpperCamelCase__ :Any=None , UpperCamelCase__ :int=256 , UpperCamelCase__ :Dict="gelu_new" , UpperCamelCase__ :str=0.0 , UpperCamelCase__ :Optional[Any]=0.0 , UpperCamelCase__ :List[Any]=0.0 , UpperCamelCase__ :Optional[int]=0.1 , UpperCamelCase__ :Optional[int]=1E-5 , UpperCamelCase__ :Dict=0.02 , UpperCamelCase__ :List[str]=True , UpperCamelCase__ :Any=50_256 , UpperCamelCase__ :Any=50_256 , **UpperCamelCase__ :Dict , ): _a = vocab_size _a = max_position_embeddings _a = hidden_size _a = num_layers _a = num_heads _a = intermediate_size _a = window_size _a = activation_function _a = resid_dropout _a = embed_dropout _a = attention_dropout _a = classifier_dropout _a = layer_norm_epsilon _a = initializer_range _a = use_cache _a = bos_token_id _a = eos_token_id _a = attention_types _a = self.expand_attention_types_params(UpperCamelCase__ ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " f'but is `len(config.attention_layers) = {len(self.attention_layers )}`, ' f'`config.num_layers = {self.num_layers}`. ' "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( UpperCamelCase__ :List[Any] ): _a = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def __a ( a, a, a, a ): """simple docstring""" import torch _a = input.size() _a = len(_UpperCAmelCase ) _a = shape[dimension] _a = torch.arange(0, _UpperCAmelCase, _UpperCAmelCase ) _a = torch.div(sizedim - size, _UpperCAmelCase, rounding_mode="floor" ) + 1 _a = torch.arange(_UpperCAmelCase ) + low_indices[:min_length][:, None] _a = [slice(_UpperCAmelCase )] * rank _a = indices _a = input[s] _a = list(range(0, rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(_UpperCAmelCase ) def __a ( a, a ): """simple docstring""" import torch _a = torch.arange(1, _UpperCAmelCase ) _a = torch.remainder(_UpperCAmelCase, _UpperCAmelCase ) _a = remainders == 0 _a = candidates[divisor_indices] _a = torch.max(_UpperCAmelCase ) return largest_divisor, torch.div(_UpperCAmelCase, _UpperCAmelCase, rounding_mode="floor" ) class __snake_case ( A__ ): """simple docstring""" @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): _a = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(UpperCamelCase__ , direction="inputs" ) _a = {0: "batch", 1: "past_sequence + sequence"} else: _a = {0: "batch", 1: "sequence"} return common_inputs @property def SCREAMING_SNAKE_CASE_ ( self :str ): return self._config.num_heads def SCREAMING_SNAKE_CASE_ ( self :Dict , UpperCamelCase__ :Dict , UpperCamelCase__ :int = -1 , UpperCamelCase__ :Tuple = -1 , UpperCamelCase__ :int = False , UpperCamelCase__ :int = None , ): _a = 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() _a = 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 _a , _a = common_inputs["input_ids"].shape # Not using the same length for past_key_values _a = seqlen + 2 _a = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) _a = [ (torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ )) for _ in range(self.num_layers ) ] _a = common_inputs["attention_mask"] if self.use_past: _a = ordered_inputs["attention_mask"].dtype _a = torch.cat( [ordered_inputs["attention_mask"], torch.ones(UpperCamelCase__ , UpperCamelCase__ , dtype=UpperCamelCase__ )] , dim=1 ) return ordered_inputs @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return 13
388
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path a_ : str = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def lowerCamelCase__ (_UpperCAmelCase=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=A__ ) ) class _snake_case ( A__ ): _lowercase : Optional[Any] = None _lowercase : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = dataset_module_factory(a , cache_dir=a) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=a) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=a , config_name=a , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=a).replace(os.sep , '/'), config.DATASET_INFO_FILENAME, ]) SCREAMING_SNAKE_CASE = cached_path(a , cache_dir=a) self.assertTrue(os.path.exists(a)) @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('test_hf_gcp') / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert "train" in ds assert isinstance(ds['train'] , _UpperCAmelCase) assert next(iter(ds['train']))
73
0
'''simple docstring''' import re def _lowerCAmelCase (_lowercase ): """simple docstring""" return [char.split() for char in re.split(R"[^ a-z A-Z 0-9 \s]" , str_ )] def _lowerCAmelCase (_lowercase ): """simple docstring""" a__ = split_input(str_ ) return "".join( ["".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def _lowerCAmelCase (_lowercase , _lowercase , _lowercase ): """simple docstring""" try: a__ = split_input(_UpperCAmelCase ) if upper: a__ = "".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: a__ = "".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def _lowerCAmelCase (_lowercase ): """simple docstring""" return to_simple_case(_UpperCAmelCase ) def _lowerCAmelCase (_lowercase ): """simple docstring""" try: a__ = to_simple_case(_UpperCAmelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def _lowerCAmelCase (_lowercase , _lowercase ): """simple docstring""" return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "_" ) def _lowerCAmelCase (_lowercase , _lowercase ): """simple docstring""" return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "-" ) if __name__ == "__main__": __import__("""doctest""").testmod()
331
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
0
"""simple docstring""" def _lowercase ( __snake_case = "The quick brown fox jumps over the lazy dog" ,) -> Optional[Any]: __lowerCAmelCase : Dict = set() # Replace all the whitespace in our sentence __lowerCAmelCase : Union[str, Any] = input_str.replace(" " ,"" ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(_UpperCAmelCase ) == 26 def _lowercase ( __snake_case = "The quick brown fox jumps over the lazy dog" ,) -> Tuple: __lowerCAmelCase : Dict = [False] * 26 for char in input_str: if char.islower(): __lowerCAmelCase : List[Any] = True elif char.isupper(): __lowerCAmelCase : str = True return all(_UpperCAmelCase ) def _lowercase ( __snake_case = "The quick brown fox jumps over the lazy dog" ,) -> int: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _lowercase ( ) -> Optional[int]: from timeit import timeit __lowerCAmelCase : Tuple = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()" ,setup=_UpperCAmelCase ) ) print(timeit("is_pangram_faster()" ,setup=_UpperCAmelCase ) ) print(timeit("is_pangram_fastest()" ,setup=_UpperCAmelCase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
293
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append('10000000') else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig _lowerCAmelCase :Optional[Any] = logging.get_logger(__name__) _lowerCAmelCase :Tuple = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class UpperCAmelCase ( A__ ): '''simple docstring''' snake_case__ : Optional[int] = '''dpt''' def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3_072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.0_2 , lowercase__=1E-12 , lowercase__=384 , lowercase__=16 , lowercase__=3 , lowercase__=False , lowercase__=True , lowercase__=[2, 5, 8, 11] , lowercase__="project" , lowercase__=[4, 2, 1, 0.5] , lowercase__=[96, 192, 384, 768] , lowercase__=256 , lowercase__=-1 , lowercase__=False , lowercase__=True , lowercase__=0.4 , lowercase__=255 , lowercase__=0.1 , lowercase__=[1, 1_024, 24, 24] , lowercase__=[0, 1] , lowercase__=None , **lowercase__ , ) -> List[str]: super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE : Tuple = hidden_size SCREAMING_SNAKE_CASE : int = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) SCREAMING_SNAKE_CASE : List[Any] = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } SCREAMING_SNAKE_CASE : Tuple = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): logger.info('Initializing the config with a `BiT` backbone.' ) SCREAMING_SNAKE_CASE : str = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE : List[Any] = backbone_config else: raise ValueError( F"""backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.""" ) SCREAMING_SNAKE_CASE : List[Any] = backbone_featmap_shape SCREAMING_SNAKE_CASE : Tuple = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = num_attention_heads SCREAMING_SNAKE_CASE : List[Any] = intermediate_size SCREAMING_SNAKE_CASE : Dict = hidden_act SCREAMING_SNAKE_CASE : int = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[int] = initializer_range SCREAMING_SNAKE_CASE : int = layer_norm_eps SCREAMING_SNAKE_CASE : Optional[Any] = image_size SCREAMING_SNAKE_CASE : Tuple = patch_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : List[str] = qkv_bias SCREAMING_SNAKE_CASE : Dict = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) SCREAMING_SNAKE_CASE : Dict = readout_type SCREAMING_SNAKE_CASE : Optional[int] = reassemble_factors SCREAMING_SNAKE_CASE : Union[str, Any] = neck_hidden_sizes SCREAMING_SNAKE_CASE : List[Any] = fusion_hidden_size SCREAMING_SNAKE_CASE : Union[str, Any] = head_in_index SCREAMING_SNAKE_CASE : int = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE : Tuple = use_auxiliary_head SCREAMING_SNAKE_CASE : Optional[Any] = auxiliary_loss_weight SCREAMING_SNAKE_CASE : Dict = semantic_loss_ignore_index SCREAMING_SNAKE_CASE : List[str] = semantic_classifier_dropout def _UpperCamelCase ( self ) -> str: SCREAMING_SNAKE_CASE : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE : List[str] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE : str = self.__class__.model_type return output
251
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ (_UpperCAmelCase): return 1.0 / (1.0 + np.exp(-_outputs)) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=_UpperCAmelCase) SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_UpperCAmelCase) class _snake_case ( A__ ): _lowercase : Tuple = '''sigmoid''' _lowercase : List[str] = '''softmax''' _lowercase : Tuple = '''none''' @add_end_docstrings( A__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class _snake_case ( A__ ): _lowercase : Optional[Any] = False _lowercase : Tuple = ClassificationFunction.NONE def __init__( self , **a) -> Optional[Any]: super().__init__(**a) 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 , a=None , a=None , a="" , **a) -> Tuple: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" SCREAMING_SNAKE_CASE = tokenizer_kwargs SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , 'return_all_scores') and return_all_scores is None: SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(a , a) or top_k is None: SCREAMING_SNAKE_CASE = top_k SCREAMING_SNAKE_CASE = 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`.' , a , ) if return_all_scores: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = 1 if isinstance(a , a): SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *a , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = super().__call__(*a , **a) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE = 'top_k' not in kwargs if isinstance(args[0] , a) 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 , a , **a) -> Dict[str, GenericTensor]: SCREAMING_SNAKE_CASE = self.framework if isinstance(a , a): return self.tokenizer(**a , return_tensors=a , **a) elif isinstance(a , a) and len(a) == 1 and isinstance(inputs[0] , a) 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=a , **a) elif isinstance(a , a): # 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(a , return_tensors=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: return self.model(**a) def SCREAMING_SNAKE_CASE__ ( self , a , a=None , a=1 , a=True) -> Any: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply') and function_to_apply is None: SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE = ClassificationFunction.NONE SCREAMING_SNAKE_CASE = model_outputs['logits'][0] SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE = sigmoid(a) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE = softmax(a) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE = 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()} SCREAMING_SNAKE_CASE = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a) ] if not _legacy: dict_scores.sort(key=lambda a: x["score"] , reverse=a) if top_k is not None: SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
73
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __lowerCamelCase = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys __lowerCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
204
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __UpperCAmelCase : Any = { 'configuration_owlvit': [ 'OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'OwlViTConfig', 'OwlViTOnnxConfig', 'OwlViTTextConfig', 'OwlViTVisionConfig', ], 'processing_owlvit': ['OwlViTProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase : Union[str, Any] = ['OwlViTFeatureExtractor'] __UpperCAmelCase : List[str] = ['OwlViTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase : Any = [ 'OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'OwlViTModel', 'OwlViTPreTrainedModel', 'OwlViTTextModel', 'OwlViTVisionModel', 'OwlViTForObjectDetection', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __UpperCAmelCase : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
241
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
0
"""simple docstring""" class a : def __init__( self , UpperCamelCase_ ): UpperCAmelCase__ : Dict = n UpperCAmelCase__ : str = [None] * self.n UpperCAmelCase__ : str = 0 # index of the first element UpperCAmelCase__ : Dict = 0 UpperCAmelCase__ : List[str] = 0 def __len__( self ): return self.size def __snake_case ( self ): return self.size == 0 def __snake_case ( self ): return False if self.is_empty() else self.array[self.front] def __snake_case ( self , UpperCamelCase_ ): if self.size >= self.n: raise Exception('QUEUE IS FULL' ) UpperCAmelCase__ : Union[str, Any] = data UpperCAmelCase__ : int = (self.rear + 1) % self.n self.size += 1 return self def __snake_case ( self ): if self.size == 0: raise Exception('UNDERFLOW' ) UpperCAmelCase__ : List[Any] = self.array[self.front] UpperCAmelCase__ : List[str] = None UpperCAmelCase__ : Tuple = (self.front + 1) % self.n self.size -= 1 return temp
110
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''decision_transformer''' _lowercase : str = ['''past_key_values'''] _lowercase : Union[str, Any] = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=17 , a=4 , a=128 , a=4096 , a=True , a=1 , a=1024 , a=3 , a=1 , a=None , a="relu" , a=0.1 , a=0.1 , a=0.1 , a=1E-5 , a=0.02 , a=True , a=True , a=5_0256 , a=5_0256 , a=False , a=False , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=a , eos_token_id=a , **a)
73
0
def __UpperCAmelCase ( a_ , a_): print('\nThe shortest path matrix using Floyd Warshall algorithm\n') for i in range(_UpperCAmelCase): for j in range(_UpperCAmelCase): if dist[i][j] != float('inf'): print(int(dist[i][j]) , end='\t') else: print('INF' , end='\t') print() def __UpperCAmelCase ( a_ , a_): snake_case_ = [[float('inf') for _ in range(_UpperCAmelCase)] for _ in range(_UpperCAmelCase)] for i in range(_UpperCAmelCase): for j in range(_UpperCAmelCase): snake_case_ = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(_UpperCAmelCase): # looping through rows of graph array for i in range(_UpperCAmelCase): # looping through columns of graph array for j in range(_UpperCAmelCase): if ( dist[i][k] != float('inf') and dist[k][j] != float('inf') and dist[i][k] + dist[k][j] < dist[i][j] ): snake_case_ = dist[i][k] + dist[k][j] _print_dist(_UpperCAmelCase , _UpperCAmelCase) return dist, v if __name__ == "__main__": lowercase = int(input("Enter number of vertices: ")) lowercase = int(input("Enter number of edges: ")) lowercase = [[float("inf") for i in range(v)] for j in range(v)] for i in range(v): lowercase = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print("\nEdge ", i + 1) lowercase = int(input("Enter source:")) lowercase = int(input("Enter destination:")) lowercase = float(input("Enter weight:")) lowercase = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
198
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[int] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
"""simple docstring""" from math import sqrt def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : Dict ): """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(sqrt(_UpperCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : Dict = 1_0_0_0_1 ): """simple docstring""" snake_case_ : List[str] = 0 snake_case_ : str = 1 while count != nth and number < 3: number += 1 if is_prime(_UpperCAmelCase ): count += 1 while count != nth: number += 2 if is_prime(_UpperCAmelCase ): count += 1 return number if __name__ == "__main__": print(F'''{solution() = }''')
480
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class UpperCAmelCase ( yaml.SafeLoader ): def lowerCamelCase_ ( self : Dict , __magic_name__ : List[str] ): """simple docstring""" UpperCamelCase = [self.constructed_objects[key_node] for key_node, _ in node.value] UpperCamelCase = [tuple(__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else key for key in keys] UpperCamelCase = Counter(__magic_name__ ) UpperCamelCase = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F'Got duplicate yaml keys: {duplicate_keys}' ) def lowerCamelCase_ ( self : Any , __magic_name__ : Optional[int] , __magic_name__ : int=False ): """simple docstring""" UpperCamelCase = super().construct_mapping(__magic_name__ , deep=__magic_name__ ) self._check_no_duplicates_on_constructed_node(__magic_name__ ) return mapping def _lowercase ( SCREAMING_SNAKE_CASE_ : Dict ): """simple docstring""" UpperCamelCase = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: UpperCamelCase = full_content[1:].index("""---""" ) + 1 UpperCamelCase = """\n""".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_UpperCAmelCase ) class UpperCAmelCase ( A__ ): # class attributes lowercase = {'''train_eval_index'''} # train-eval-index in the YAML metadata @classmethod def lowerCamelCase_ ( cls : List[Any] , __magic_name__ : Any ): """simple docstring""" with open(__magic_name__ , encoding="""utf-8""" ) as readme_file: UpperCamelCase , UpperCamelCase = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__magic_name__ ) else: return cls() def lowerCamelCase_ ( self : Optional[Any] , __magic_name__ : List[Any] ): """simple docstring""" if path.exists(): with open(__magic_name__ , encoding="""utf-8""" ) as readme_file: UpperCamelCase = readme_file.read() else: UpperCamelCase = None UpperCamelCase = self._to_readme(__magic_name__ ) with open(__magic_name__ , """w""" , encoding="""utf-8""" ) as readme_file: readme_file.write(__magic_name__ ) def lowerCamelCase_ ( self : str , __magic_name__ : Any = None ): """simple docstring""" if readme_content is not None: UpperCamelCase , UpperCamelCase = _split_yaml_from_readme(__magic_name__ ) UpperCamelCase = """---\n""" + self.to_yaml_string() + """---\n""" + content else: UpperCamelCase = """---\n""" + self.to_yaml_string() + """---\n""" return full_content @classmethod def lowerCamelCase_ ( cls : Tuple , __magic_name__ : Optional[int] ): """simple docstring""" UpperCamelCase = yaml.load(__magic_name__ , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields UpperCamelCase = { (key.replace("""-""" , """_""" ) if key.replace("""-""" , """_""" ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__magic_name__ ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" return yaml.safe_dump( { (key.replace("""_""" , """-""" ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__magic_name__ , allow_unicode=__magic_name__ , encoding="""utf-8""" , ).decode("""utf-8""" ) __snake_case = { 'image-classification': [], 'translation': [], 'image-segmentation': [], 'fill-mask': [], 'automatic-speech-recognition': [], 'token-classification': [], 'sentence-similarity': [], 'audio-classification': [], 'question-answering': [], 'summarization': [], 'zero-shot-classification': [], 'table-to-text': [], 'feature-extraction': [], 'other': [], 'multiple-choice': [], 'text-classification': [], 'text-to-image': [], 'text2text-generation': [], 'zero-shot-image-classification': [], 'tabular-classification': [], 'tabular-regression': [], 'image-to-image': [], 'tabular-to-text': [], 'unconditional-image-generation': [], 'text-retrieval': [], 'text-to-speech': [], 'object-detection': [], 'audio-to-audio': [], 'text-generation': [], 'conversational': [], 'table-question-answering': [], 'visual-question-answering': [], 'image-to-text': [], 'reinforcement-learning': [], 'voice-activity-detection': [], 'time-series-forecasting': [], 'document-question-answering': [], } if __name__ == "__main__": from argparse import ArgumentParser __snake_case = ArgumentParser(usage="Validate the yaml metadata block of a README.md file.") ap.add_argument("readme_filepath") __snake_case = ap.parse_args() __snake_case = Path(args.readme_filepath) __snake_case = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
386
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): if radian_mode: return [magnitude * cos(_UpperCAmelCase), magnitude * sin(_UpperCAmelCase)] return [magnitude * cos(radians(_UpperCAmelCase)), magnitude * sin(radians(_UpperCAmelCase))] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 10**-1): SCREAMING_SNAKE_CASE = cross(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(_UpperCAmelCase) return abs(_UpperCAmelCase) < eps if __name__ == "__main__": # Test to check if it works a_ : int = array( [ polar_force(718.4, 1_80 - 30), polar_force(879.54, 45), polar_force(1_00, -90), ] ) a_ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg a_ : Dict = array( [ polar_force(30 * 9.81, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) a_ : Any = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg a_ : int = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) a_ : Optional[Any] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
0
import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> List[Any]: """simple docstring""" A__ = 1.5 A__ = int(factor * num_class_images ) A__ = ClipClient( url='''https://knn.laion.ai/knn-service''' , indice_name='''laion_400m''' , num_images=_UpperCAmelCase , aesthetic_weight=0.1 ) os.makedirs(f"""{class_data_dir}/images""" , exist_ok=_UpperCAmelCase ) if len(list(Path(f"""{class_data_dir}/images""" ).iterdir() ) ) >= num_class_images: return while True: A__ = client.query(text=_UpperCAmelCase ) if len(_UpperCAmelCase ) >= factor * num_class_images or num_images > 1E4: break else: A__ = int(factor * num_images ) A__ = ClipClient( url='''https://knn.laion.ai/knn-service''' , indice_name='''laion_400m''' , num_images=_UpperCAmelCase , aesthetic_weight=0.1 , ) A__ = 0 A__ = 0 A__ = tqdm(desc='''downloading real regularization images''' , total=_UpperCAmelCase ) with open(f"""{class_data_dir}/caption.txt""" , '''w''' ) as fa, open(f"""{class_data_dir}/urls.txt""" , '''w''' ) as fa, open( f"""{class_data_dir}/images.txt""" , '''w''' ) as fa: while total < num_class_images: A__ = class_images[count] count += 1 try: A__ = requests.get(images['''url'''] ) if img.status_code == 200: A__ = Image.open(BytesIO(img.content ) ) with open(f"""{class_data_dir}/images/{total}.jpg""" , '''wb''' ) as f: f.write(img.content ) fa.write(images['''caption'''] + '''\n''' ) fa.write(images['''url'''] + '''\n''' ) fa.write(f"""{class_data_dir}/images/{total}.jpg""" + '''\n''' ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def SCREAMING_SNAKE_CASE ( ) -> List[Any]: """simple docstring""" A__ = argparse.ArgumentParser('''''' , add_help=_UpperCAmelCase ) parser.add_argument('''--class_prompt''' , help='''text prompt to retrieve images''' , required=_UpperCAmelCase , type=_UpperCAmelCase ) parser.add_argument('''--class_data_dir''' , help='''path to save images''' , required=_UpperCAmelCase , type=_UpperCAmelCase ) parser.add_argument('''--num_class_images''' , help='''number of images to download''' , default=200 , type=_UpperCAmelCase ) return parser.parse_args() if __name__ == "__main__": _lowerCamelCase : int = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
87
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : int = { '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 _snake_case ( A__ ): _lowercase : Dict = '''cvt''' def __init__( self , a=3 , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[64, 192, 384] , a=[1, 3, 6] , a=[1, 2, 10] , a=[4.0, 4.0, 4.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.1] , a=[True, True, True] , a=[False, False, True] , a=["dw_bn", "dw_bn", "dw_bn"] , a=[3, 3, 3] , a=[1, 1, 1] , a=[2, 2, 2] , a=[1, 1, 1] , a=[1, 1, 1] , a=0.02 , a=1E-12 , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = drop_rate SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = qkv_projection_method SCREAMING_SNAKE_CASE = kernel_qkv SCREAMING_SNAKE_CASE = padding_kv SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = padding_q SCREAMING_SNAKE_CASE = stride_q SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps
73
0
"""simple docstring""" def __a ( a, a ): """simple docstring""" if digit_amount > 0: return round(number - int(_UpperCAmelCase ), _UpperCAmelCase ) return number - int(_UpperCAmelCase ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
388
def lowerCamelCase__ (_UpperCAmelCase = 10 , _UpperCAmelCase = 1000 , _UpperCAmelCase = True): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)') return min_val if option else max_val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int((number_a + number_a) / 2) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)') if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value') def answer(_UpperCAmelCase) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...') SCREAMING_SNAKE_CASE = lower SCREAMING_SNAKE_CASE = higher SCREAMING_SNAKE_CASE = [] while True: SCREAMING_SNAKE_CASE = get_avg(_UpperCAmelCase , _UpperCAmelCase) last_numbers.append(_UpperCAmelCase) if answer(_UpperCAmelCase) == "low": SCREAMING_SNAKE_CASE = number elif answer(_UpperCAmelCase) == "high": SCREAMING_SNAKE_CASE = number else: break print(F'''guess the number : {last_numbers[-1]}''') print(F'''details : {last_numbers!s}''') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Enter lower value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter high value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter value to guess : ').strip()) guess_the_number(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
'''simple docstring''' from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def _lowerCAmelCase (_lowercase , _lowercase , _lowercase=1e-12 ): """simple docstring""" a__ = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(_UpperCAmelCase , axis=1 ) , a_min=_UpperCAmelCase ) ).T a__ = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(_UpperCAmelCase , axis=1 ) , a_min=_UpperCAmelCase ) ).T return jnp.matmul(_UpperCAmelCase , norm_emb_a.T ) class lowerCamelCase__ ( nn.Module ): """simple docstring""" UpperCamelCase__ = 42 UpperCamelCase__ = jnp.floataa def lowerCAmelCase_ ( self : List[str] ): a__ = FlaxCLIPVisionModule(self.config.vision_config ) a__ = nn.Dense(self.config.projection_dim ,use_bias=a__ ,dtype=self.dtype ) a__ = self.param("concept_embeds" ,jax.nn.initializers.ones ,(17, self.config.projection_dim) ) a__ = self.param( "special_care_embeds" ,jax.nn.initializers.ones ,(3, self.config.projection_dim) ) a__ = self.param("concept_embeds_weights" ,jax.nn.initializers.ones ,(17,) ) a__ = self.param("special_care_embeds_weights" ,jax.nn.initializers.ones ,(3,) ) def __call__( self : int ,a__ : List[str] ): a__ = self.vision_model(a__ )[1] a__ = self.visual_projection(a__ ) a__ = jax_cosine_distance(a__ ,self.special_care_embeds ) a__ = jax_cosine_distance(a__ ,self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs a__ = 0.0 a__ = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment a__ = jnp.round(a__ ,3 ) a__ = jnp.any(special_scores > 0 ,axis=1 ,keepdims=a__ ) # Use a lower threshold if an image has any special care concept a__ = is_special_care * 0.01 a__ = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment a__ = jnp.round(a__ ,3 ) a__ = jnp.any(concept_scores > 0 ,axis=1 ) return has_nsfw_concepts class lowerCamelCase__ ( A__ ): """simple docstring""" UpperCamelCase__ = CLIPConfig UpperCamelCase__ = '''clip_input''' UpperCamelCase__ = FlaxStableDiffusionSafetyCheckerModule def __init__( self : Optional[int] ,a__ : Dict ,a__ : str = None ,a__ : Any = 0 ,a__ : Union[str, Any] = jnp.floataa ,a__ : Union[str, Any] = True ,**a__ : int ,): if input_shape is None: a__ = (1, 2_24, 2_24, 3) a__ = self.module_class(config=a__ ,dtype=a__ ,**a__ ) super().__init__(a__ ,a__ ,input_shape=a__ ,seed=a__ ,dtype=a__ ,_do_init=_do_init ) def lowerCAmelCase_ ( self : Any ,a__ : int ,a__ : Tuple ,a__ : int = None ): # init input tensor a__ = jax.random.normal(a__ ,a__ ) a__ , a__ = jax.random.split(a__ ) a__ = {"params": params_rng, "dropout": dropout_rng} a__ = self.module.init(a__ ,a__ )["params"] return random_params def __call__( self : List[str] ,a__ : Dict ,a__ : Any = None ,): a__ = jnp.transpose(a__ ,(0, 2, 3, 1) ) return self.module.apply( {"params": params or self.params} ,jnp.array(a__ ,dtype=jnp.floataa ) ,rngs={} ,)
331
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class _snake_case : def __init__( self , a , a=13 , 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=512 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> Union[str, 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 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: 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 = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , use_stable_embedding=a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Any: SCREAMING_SNAKE_CASE = OpenLlamaModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , ) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , ) SCREAMING_SNAKE_CASE = model(a , attention_mask=a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() # first forward pass SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , use_cache=a , ) SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , output_hidden_states=a , )['hidden_states'][0] SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , past_key_values=a , output_hidden_states=a , )['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1]).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1E-3)) def SCREAMING_SNAKE_CASE__ ( self) -> 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, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) _lowercase : str = (OpenLlamaForCausalLM,) if is_torch_available() else () _lowercase : List[str] = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) _lowercase : List[str] = False _lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = OpenLlamaModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'single_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'multi_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass @parameterized.expand([('linear',), ('dynamic',)]) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ids_tensor([1, 10] , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = OpenLlamaModel(a) original_model.to(a) original_model.eval() SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = {'type': scaling_type, 'factor': 10.0} SCREAMING_SNAKE_CASE = OpenLlamaModel(a) scaled_model.to(a) scaled_model.eval() SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a , a , atol=1E-5)) else: self.assertFalse(torch.allclose(a , a , atol=1E-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(a , a , atol=1E-5))
73
0
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def _lowercase ( ) -> Optional[Any]: __lowerCAmelCase : Union[str, Any] = ArgumentParser("Accelerate CLI tool" ,usage="accelerate <command> [<args>]" ,allow_abbrev=_UpperCAmelCase ) __lowerCAmelCase : Optional[Any] = parser.add_subparsers(help="accelerate command helpers" ) # Register commands get_config_parser(subparsers=_UpperCAmelCase ) env_command_parser(subparsers=_UpperCAmelCase ) launch_command_parser(subparsers=_UpperCAmelCase ) tpu_command_parser(subparsers=_UpperCAmelCase ) test_command_parser(subparsers=_UpperCAmelCase ) # Let's go __lowerCAmelCase : Optional[int] = parser.parse_args() if not hasattr(_UpperCAmelCase ,"func" ): parser.print_help() exit(1 ) # Run args.func(_UpperCAmelCase ) if __name__ == "__main__": main()
293
from __future__ import annotations a_ : str = [] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for i in range(len(_UpperCAmelCase)): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase)): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , -1 , -1)): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , len(_UpperCAmelCase))): if board[i][j] == 1: return False return True def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if row >= len(_UpperCAmelCase): solution.append(_UpperCAmelCase) printboard(_UpperCAmelCase) print() return True for i in range(len(_UpperCAmelCase)): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 solve(_UpperCAmelCase , row + 1) SCREAMING_SNAKE_CASE = 0 return False def lowerCamelCase__ (_UpperCAmelCase): for i in range(len(_UpperCAmelCase)): for j in range(len(_UpperCAmelCase)): if board[i][j] == 1: print('Q' , end=' ') else: print('.' , end=' ') print() # n=int(input("The no. of queens")) a_ : Tuple = 8 a_ : int = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
73
0
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class UpperCAmelCase ( datasets.BeamBasedBuilder ): '''simple docstring''' def _UpperCamelCase ( self ) -> int: return datasets.DatasetInfo( features=datasets.Features({'content': datasets.Value('string' )} ) , supervised_keys=lowercase__ , ) def _UpperCamelCase ( self , lowercase__ , lowercase__ ) -> Any: return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'examples': get_test_dummy_examples()} )] def _UpperCamelCase ( self , lowercase__ , lowercase__ ) -> Union[str, Any]: import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(lowercase__ ) class UpperCAmelCase ( datasets.BeamBasedBuilder ): '''simple docstring''' def _UpperCamelCase ( self ) -> str: return datasets.DatasetInfo( features=datasets.Features({'a': datasets.Sequence({'b': datasets.Value('string' )} )} ) , supervised_keys=lowercase__ , ) def _UpperCamelCase ( self , lowercase__ , lowercase__ ) -> Union[str, Any]: return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'examples': get_test_nested_examples()} ) ] def _UpperCamelCase ( self , lowercase__ , lowercase__ ) -> int: import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(lowercase__ ) def __lowerCAmelCase ( ) -> Dict: '''simple docstring''' return [(i, {"content": content}) for i, content in enumerate(['foo', 'bar', 'foobar'] )] def __lowerCAmelCase ( ) -> Union[str, Any]: '''simple docstring''' return [(i, {"a": {"b": [content]}}) for i, content in enumerate(['foo', 'bar', 'foobar'] )] class UpperCAmelCase ( A__ ): '''simple docstring''' @require_beam def _UpperCamelCase ( self ) -> Dict: SCREAMING_SNAKE_CASE : Dict = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: SCREAMING_SNAKE_CASE : List[Any] = DummyBeamDataset(cache_dir=lowercase__ , beam_runner='DirectRunner' ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(lowercase__ , builder.name , 'default' , '0.0.0' , F"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({'content': datasets.Value('string' )} ) ) SCREAMING_SNAKE_CASE : str = builder.as_dataset() self.assertEqual(dset['train'].num_rows , lowercase__ ) self.assertEqual(dset['train'].info.splits['train'].num_examples , lowercase__ ) self.assertDictEqual(dset['train'][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset['train'][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(lowercase__ , builder.name , 'default' , '0.0.0' , 'dataset_info.json' ) ) ) del dset @require_beam def _UpperCamelCase ( self ) -> Union[str, Any]: import apache_beam as beam SCREAMING_SNAKE_CASE : Dict = beam.io.parquetio.WriteToParquet SCREAMING_SNAKE_CASE : List[str] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: SCREAMING_SNAKE_CASE : str = DummyBeamDataset(cache_dir=lowercase__ , beam_runner='DirectRunner' ) with patch('apache_beam.io.parquetio.WriteToParquet' ) as write_parquet_mock: SCREAMING_SNAKE_CASE : Union[str, Any] = partial(lowercase__ , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( lowercase__ , builder.name , 'default' , '0.0.0' , F"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertTrue( os.path.exists( os.path.join( lowercase__ , builder.name , 'default' , '0.0.0' , F"""{builder.name}-train-00000-of-00002.arrow""" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({'content': datasets.Value('string' )} ) ) SCREAMING_SNAKE_CASE : Any = builder.as_dataset() self.assertEqual(dset['train'].num_rows , lowercase__ ) self.assertEqual(dset['train'].info.splits['train'].num_examples , lowercase__ ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset['train']['content'] ) , sorted(['foo', 'bar', 'foobar'] ) ) self.assertTrue( os.path.exists(os.path.join(lowercase__ , builder.name , 'default' , '0.0.0' , 'dataset_info.json' ) ) ) del dset @require_beam def _UpperCamelCase ( self ) -> List[str]: with tempfile.TemporaryDirectory() as tmp_cache_dir: SCREAMING_SNAKE_CASE : List[str] = DummyBeamDataset(cache_dir=lowercase__ ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def _UpperCamelCase ( self ) -> Dict: SCREAMING_SNAKE_CASE : Optional[int] = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: SCREAMING_SNAKE_CASE : Union[str, Any] = NestedBeamDataset(cache_dir=lowercase__ , beam_runner='DirectRunner' ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(lowercase__ , builder.name , 'default' , '0.0.0' , F"""{builder.name}-train.arrow""" ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({'a': datasets.Sequence({'b': datasets.Value('string' )} )} ) ) SCREAMING_SNAKE_CASE : List[str] = builder.as_dataset() self.assertEqual(dset['train'].num_rows , lowercase__ ) self.assertEqual(dset['train'].info.splits['train'].num_examples , lowercase__ ) self.assertDictEqual(dset['train'][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset['train'][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(lowercase__ , builder.name , 'default' , '0.0.0' , 'dataset_info.json' ) ) ) del dset
251
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) for optional_component in pipe._optional_components: self.assertTrue( getattr(a , a) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
0
import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification __lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co __lowerCamelCase = 'main' # Default branch name __lowerCamelCase = 'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2' # One particular commit (not the top of `main`) __lowerCamelCase = 'aaaaaaa' # This commit does not exist, so we should 404. __lowerCamelCase = 'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684' # Sha-1 of config.json on the top of `main`, for checking purposes __lowerCamelCase = '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3' @contextlib.contextmanager def UpperCamelCase ( ): print("Welcome!" ) yield print("Bye!" ) @contextlib.contextmanager def UpperCamelCase ( ): print("Bonjour!" ) yield print("Au revoir!" ) class UpperCAmelCase ( unittest.TestCase ): def _SCREAMING_SNAKE_CASE (self : Tuple ) -> Any: '''simple docstring''' assert transformers.__spec__ is not None assert importlib.util.find_spec("transformers" ) is not None class UpperCAmelCase ( unittest.TestCase ): @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def _SCREAMING_SNAKE_CASE (self : str , snake_case__ : List[Any] ) -> List[str]: '''simple docstring''' with ContextManagers([] ): print("Transformers are awesome!" ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , "Transformers are awesome!\n" ) @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def _SCREAMING_SNAKE_CASE (self : Any , snake_case__ : Tuple ) -> List[str]: '''simple docstring''' with ContextManagers([context_en()] ): print("Transformers are awesome!" ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , "Welcome!\nTransformers are awesome!\nBye!\n" ) @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def _SCREAMING_SNAKE_CASE (self : Union[str, Any] , snake_case__ : int ) -> Optional[int]: '''simple docstring''' with ContextManagers([context_fr(), context_en()] ): print("Transformers are awesome!" ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n" ) @require_torch def _SCREAMING_SNAKE_CASE (self : Optional[int] ) -> List[Any]: '''simple docstring''' self.assertEqual(find_labels(snake_case__ ) , ["labels"] ) self.assertEqual(find_labels(snake_case__ ) , ["labels", "next_sentence_label"] ) self.assertEqual(find_labels(snake_case__ ) , ["start_positions", "end_positions"] ) class UpperCAmelCase ( A__ ): pass self.assertEqual(find_labels(snake_case__ ) , ["labels"] ) @require_tf def _SCREAMING_SNAKE_CASE (self : Tuple ) -> List[str]: '''simple docstring''' self.assertEqual(find_labels(snake_case__ ) , ["labels"] ) self.assertEqual(find_labels(snake_case__ ) , ["labels", "next_sentence_label"] ) self.assertEqual(find_labels(snake_case__ ) , ["start_positions", "end_positions"] ) class UpperCAmelCase ( A__ ): pass self.assertEqual(find_labels(snake_case__ ) , ["labels"] ) @require_flax def _SCREAMING_SNAKE_CASE (self : Dict ) -> str: '''simple docstring''' self.assertEqual(find_labels(snake_case__ ) , [] ) self.assertEqual(find_labels(snake_case__ ) , [] ) self.assertEqual(find_labels(snake_case__ ) , [] ) class UpperCAmelCase ( A__ ): pass self.assertEqual(find_labels(snake_case__ ) , [] )
204
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Any = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _snake_case ( A__ ): _lowercase : Optional[int] = '''unispeech''' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="mean" , a=False , a=False , a=256 , a=80 , a=0 , a=1 , a=2 , a=0.5 , **a , ) -> Optional[int]: super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE = replace_prob @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return functools.reduce(operator.mul , self.conv_stride , 1)
73
0
from __future__ import annotations from collections.abc import Sequence from typing import Literal def lowercase_ ( __snake_case : List[str] , __snake_case : Optional[Any] ) -> Optional[int]: '''simple docstring''' snake_case__ :List[Any] = list(_UpperCAmelCase ) snake_case__ :Dict = list(_UpperCAmelCase ) snake_case__ :List[Any] = 0 for i in range(len(_UpperCAmelCase ) ): if lista[i] != lista[i]: count += 1 snake_case__ :str = "_" if count > 1: return False else: return "".join(_UpperCAmelCase ) def lowercase_ ( __snake_case : Tuple ) -> Tuple: '''simple docstring''' snake_case__ :List[Any] = [] while True: snake_case__ :List[Any] = ["$"] * len(_UpperCAmelCase ) snake_case__ :int = [] for i in range(len(_UpperCAmelCase ) ): for j in range(i + 1 , len(_UpperCAmelCase ) ): snake_case__ :List[Any] = compare_string(binary[i] , binary[j] ) if k is False: snake_case__ :Any = "*" snake_case__ :Optional[int] = "*" temp.append("X" ) for i in range(len(_UpperCAmelCase ) ): if checka[i] == "$": pi.append(binary[i] ) if len(_UpperCAmelCase ) == 0: return pi snake_case__ :Union[str, Any] = list(set(_UpperCAmelCase ) ) def lowercase_ ( __snake_case : Any , __snake_case : Tuple ) -> int: '''simple docstring''' snake_case__ :List[str] = [] for minterm in minterms: snake_case__ :int = "" for _ in range(_UpperCAmelCase ): snake_case__ :str = str(minterm % 2 ) + string minterm //= 2 temp.append(_UpperCAmelCase ) return temp def lowercase_ ( __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : List[Any] ) -> Optional[int]: '''simple docstring''' snake_case__ :Optional[int] = list(_UpperCAmelCase ) snake_case__ :Optional[Any] = list(_UpperCAmelCase ) snake_case__ :Optional[Any] = 0 for i in range(len(_UpperCAmelCase ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def lowercase_ ( __snake_case : Optional[Any] , __snake_case : int ) -> Dict: '''simple docstring''' snake_case__ :Optional[Any] = [] snake_case__ :Dict = [0] * len(_UpperCAmelCase ) for i in range(len(chart[0] ) ): snake_case__ :Optional[Any] = 0 snake_case__ :Any = -1 for j in range(len(_UpperCAmelCase ) ): if chart[j][i] == 1: count += 1 snake_case__ :Any = j if count == 1: snake_case__ :Dict = 1 for i in range(len(_UpperCAmelCase ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(_UpperCAmelCase ) ): snake_case__ :List[str] = 0 temp.append(prime_implicants[i] ) while True: snake_case__ :List[str] = 0 snake_case__ :Optional[int] = -1 snake_case__ :Tuple = 0 for i in range(len(_UpperCAmelCase ) ): snake_case__ :Any = chart[i].count(1 ) if count_n > max_n: snake_case__ :Optional[int] = count_n snake_case__ :Optional[Any] = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(_UpperCAmelCase ) ): snake_case__ :List[str] = 0 def lowercase_ ( __snake_case : Optional[Any] , __snake_case : List[Any] ) -> Optional[Any]: '''simple docstring''' snake_case__ :int = [[0 for x in range(len(_UpperCAmelCase ) )] for x in range(len(_UpperCAmelCase ) )] for i in range(len(_UpperCAmelCase ) ): snake_case__ :Union[str, Any] = prime_implicants[i].count("_" ) for j in range(len(_UpperCAmelCase ) ): if is_for_table(prime_implicants[i] , binary[j] , _UpperCAmelCase ): snake_case__ :Tuple = 1 return chart def lowercase_ ( ) -> Any: '''simple docstring''' snake_case__ :Optional[Any] = int(input("Enter the no. of variables\n" ) ) snake_case__ :int = [ float(_UpperCAmelCase ) for x in input( "Enter the decimal representation of Minterms \'Spaces Separated\'\n" ).split() ] snake_case__ :List[Any] = decimal_to_binary(_UpperCAmelCase , _UpperCAmelCase ) snake_case__ :int = check(_UpperCAmelCase ) print("Prime Implicants are:" ) print(_UpperCAmelCase ) snake_case__ :List[str] = prime_implicant_chart(_UpperCAmelCase , _UpperCAmelCase ) snake_case__ :Optional[Any] = selection(_UpperCAmelCase , _UpperCAmelCase ) print("Essential Prime Implicants are:" ) print(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod() main()
241
import argparse import collections import json import os import re import string import sys import numpy as np a_ : Optional[Any] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a_ : List[str] = None def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.') parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.') parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).') parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.') parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.') parser.add_argument('--verbose' , '-v' , action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa['answers']['text']) return qid_to_has_ans def lowerCamelCase__ (_UpperCAmelCase): def remove_articles(_UpperCAmelCase): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase) def white_space_fix(_UpperCAmelCase): return " ".join(text.split()) def remove_punc(_UpperCAmelCase): SCREAMING_SNAKE_CASE = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(_UpperCAmelCase): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase)))) def lowerCamelCase__ (_UpperCAmelCase): if not s: return [] return normalize_answer(_UpperCAmelCase).split() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int(normalize_answer(_UpperCAmelCase) == normalize_answer(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.Counter(_UpperCAmelCase) & collections.Counter(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(common.values()) if len(_UpperCAmelCase) == 0 or len(_UpperCAmelCase) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa['id'] SCREAMING_SNAKE_CASE = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase)] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [''] if qid not in preds: print(F'''Missing prediction for {qid}''') continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) SCREAMING_SNAKE_CASE = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) return exact_scores, fa_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid]) else: SCREAMING_SNAKE_CASE = s return new_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): if not qid_list: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values()) / total), ('f1', 1_00.0 * sum(fa_scores.values()) / total), ('total', total), ]) else: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list) / total), ('total', total), ]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post') plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(_UpperCAmelCase) plt.savefig(_UpperCAmelCase) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(_UpperCAmelCase): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1) SCREAMING_SNAKE_CASE = true_pos / float(_UpperCAmelCase) if i == len(_UpperCAmelCase) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase) recalls.append(_UpperCAmelCase) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return {"ap": 1_00.0 * avg_prec} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if out_image_dir and not os.path.exists(_UpperCAmelCase): os.makedirs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png') , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png') , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE = {k: float(_UpperCAmelCase) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png') , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(_UpperCAmelCase) / float(len(_UpperCAmelCase)) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title(F'''Histogram of no-answer probability: {name}''') plt.savefig(os.path.join(_UpperCAmelCase , F'''na_prob_hist_{name}.png''')) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) for i, qid in enumerate(_UpperCAmelCase): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 1_00.0 * best_score / len(_UpperCAmelCase), best_thresh def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def lowerCamelCase__ (): with open(OPTS.data_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset_json['data'] with open(OPTS.pred_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(_UpperCAmelCase) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns') if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns') histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns') if OPTS.out_file: with open(OPTS.out_file , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) else: print(json.dumps(_UpperCAmelCase , indent=2)) if __name__ == "__main__": a_ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
73
0
"""simple docstring""" def lowerCamelCase ( _snake_case = 100 ): UpperCAmelCase__ : Optional[Any] = 0 UpperCAmelCase__ : List[Any] = 0 for i in range(1 ,n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(f'{solution() = }')
110
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a , ) super().__init__(*a , **a)
73
0
import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowercase = logging.get_logger(__name__) class UpperCamelCase_ ( A__ ): '''simple docstring''' lowerCAmelCase = ['''input_values''', '''attention_mask'''] def __init__( self , a = 1 , a = 1_60_00 , a = 0.0 , a = False , a = 80 , a = 16 , a = 64 , a = "hann_window" , a = 1.0 , a = 80 , a = 76_00 , a = 1E-10 , a = 2 , a = True , **a , ) -> Tuple: super().__init__(feature_size=a , sampling_rate=a , padding_value=a , **a ) snake_case_ = do_normalize snake_case_ = return_attention_mask snake_case_ = num_mel_bins snake_case_ = hop_length snake_case_ = win_length snake_case_ = win_function snake_case_ = frame_signal_scale snake_case_ = fmin snake_case_ = fmax snake_case_ = mel_floor snake_case_ = reduction_factor snake_case_ = win_length * sampling_rate // 10_00 snake_case_ = hop_length * sampling_rate // 10_00 snake_case_ = optimal_fft_length(self.sample_size ) snake_case_ = (self.n_fft // 2) + 1 snake_case_ = window_function(window_length=self.sample_size , name=self.win_function , periodic=a ) snake_case_ = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.num_mel_bins , min_frequency=self.fmin , max_frequency=self.fmax , sampling_rate=self.sampling_rate , norm='slaney' , mel_scale='slaney' , ) if frame_signal_scale != 1.0: warnings.warn( 'The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers' , a , ) if reduction_factor != 2.0: warnings.warn( 'The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers' , a , ) @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def _UpperCamelCase ( a , a , a = 0.0 ) -> List[np.ndarray]: if attention_mask is not None: snake_case_ = np.array(a , np.intaa ) snake_case_ = [] for vector, length in zip(a , attention_mask.sum(-1 ) ): snake_case_ = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7 ) if length < normed_slice.shape[0]: snake_case_ = padding_value normed_input_values.append(a ) else: snake_case_ = [(x - x.mean()) / np.sqrt(x.var() + 1E-7 ) for x in input_values] return normed_input_values def _UpperCamelCase ( self , a , ) -> np.ndarray: snake_case_ = spectrogram( a , window=self.window , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , mel_filters=self.mel_filters , mel_floor=self.mel_floor , log_mel='log10' , ) return log_mel_spec.T def __call__( self , a = None , a = None , a = False , a = None , a = False , a = None , a = None , a = None , a = None , **a , ) -> BatchFeature: if audio is None and audio_target is None: raise ValueError('You must provide either `audio` or `audio_target` values.' ) if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' F''' {self.sampling_rate}. Please make sure that the provided audio input was sampled with''' F''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( 'It is strongly recommended to pass the ``sampling_rate`` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) if audio is not None: snake_case_ = self._process_audio( a , a , a , a , a , a , a , a , **a , ) else: snake_case_ = None if audio_target is not None: snake_case_ = self._process_audio( a , a , a , a , a , a , a , a , **a , ) if inputs is None: return inputs_target else: snake_case_ = inputs_target['input_values'] snake_case_ = inputs_target.get('attention_mask' ) if decoder_attention_mask is not None: snake_case_ = decoder_attention_mask return inputs def _UpperCamelCase ( self , a , a = False , a = False , a = None , a = False , a = None , a = None , a = None , **a , ) -> BatchFeature: snake_case_ = isinstance(a , np.ndarray ) and len(speech.shape ) > 1 if is_batched_numpy and len(speech.shape ) > 2: raise ValueError(F'''Only mono-channel audio is supported for input to {self}''' ) snake_case_ = is_batched_numpy or ( isinstance(a , (list, tuple) ) and (isinstance(speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: snake_case_ = [np.asarray(a , dtype=np.floataa ) for speech in speech] elif not is_batched and not isinstance(a , np.ndarray ): snake_case_ = np.asarray(a , dtype=np.floataa ) elif isinstance(a , np.ndarray ) and speech.dtype is np.dtype(np.floataa ): snake_case_ = speech.astype(np.floataa ) # always return batch if not is_batched: snake_case_ = [speech] # needed to make pad() work on spectrogram inputs snake_case_ = self.feature_size # convert into correct format for padding if is_target: snake_case_ = [self._extract_mel_features(a ) for waveform in speech] snake_case_ = BatchFeature({'input_values': features} ) snake_case_ = self.num_mel_bins else: snake_case_ = BatchFeature({'input_values': speech} ) snake_case_ = self.pad( a , padding=a , max_length=a , truncation=a , pad_to_multiple_of=a , return_attention_mask=a , **a , ) snake_case_ = feature_size_hack # convert input values to correct format snake_case_ = padded_inputs['input_values'] if not isinstance(input_values[0] , np.ndarray ): snake_case_ = [np.asarray(a , dtype=np.floataa ) for array in input_values] elif ( not isinstance(a , np.ndarray ) and isinstance(input_values[0] , np.ndarray ) and input_values[0].dtype is np.dtype(np.floataa ) ): snake_case_ = [array.astype(np.floataa ) for array in input_values] elif isinstance(a , np.ndarray ) and input_values.dtype is np.dtype(np.floataa ): snake_case_ = input_values.astype(np.floataa ) # convert attention_mask to correct format snake_case_ = padded_inputs.get('attention_mask' ) if attention_mask is not None: snake_case_ = [np.asarray(a , dtype=np.intaa ) for array in attention_mask] # zero-mean and unit-variance normalization if not is_target and self.do_normalize: snake_case_ = ( attention_mask if self._get_padding_strategies(a , max_length=a ) is not PaddingStrategy.DO_NOT_PAD else None ) snake_case_ = self.zero_mean_unit_var_norm( padded_inputs['input_values'] , attention_mask=a , padding_value=self.padding_value ) if return_tensors is not None: snake_case_ = padded_inputs.convert_to_tensors(a ) return padded_inputs def _UpperCamelCase ( self ) -> Dict[str, Any]: snake_case_ = super().to_dict() # Don't serialize these as they are derived from the other properties. snake_case_ = ['window', 'mel_filters', 'sample_size', 'sample_stride', 'n_fft', 'n_freqs'] for name in names: if name in output: del output[name] return output
198
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
0
"""simple docstring""" import argparse import torch from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] ): """simple docstring""" snake_case_ : str = RemBertConfig.from_json_file(_UpperCAmelCase ) print("""Building PyTorch model from configuration: {}""".format(str(_UpperCAmelCase ) ) ) snake_case_ : List[str] = RemBertModel(_UpperCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_rembert(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Save pytorch-model print("""Save PyTorch model to {}""".format(_UpperCAmelCase ) ) torch.save(model.state_dict() , _UpperCAmelCase ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--rembert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained RemBERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) a_ = parser.parse_args() convert_rembert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.rembert_config_file, args.pytorch_dump_path)
480
import sys import turtle def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) if depth == 0: return triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) a_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') a_ : str = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
73
0
def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): # noqa: E741 """simple docstring""" UpperCamelCase = len(_UpperCAmelCase ) UpperCamelCase = 0 UpperCamelCase = [0] * n UpperCamelCase = [False] * n UpperCamelCase = [False] * n def dfs(SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : int ): if parent == root: out_edge_count += 1 UpperCamelCase = True UpperCamelCase = at for to in l[at]: if to == parent: pass elif not visited[to]: UpperCamelCase = dfs(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) UpperCamelCase = min(low[at] , low[to] ) # AP found via bridge if at < low[to]: UpperCamelCase = True # AP found via cycle if at == low[to]: UpperCamelCase = True else: UpperCamelCase = min(low[at] , _UpperCAmelCase ) return out_edge_count for i in range(_UpperCAmelCase ): if not visited[i]: UpperCamelCase = 0 UpperCamelCase = dfs(_UpperCAmelCase , _UpperCAmelCase , -1 , _UpperCAmelCase ) UpperCamelCase = out_edge_count > 1 for x in range(len(_UpperCAmelCase ) ): if is_art[x] is True: print(_UpperCAmelCase ) # Adjacency list of graph __snake_case = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
386
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
0
def SCREAMING_SNAKE_CASE ( lowercase_ = 50_000_000 ) -> str: """simple docstring""" A__ = set() A__ = int((limit - 24) ** (1 / 2) ) A__ = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , _UpperCAmelCase ) ) ) for primea in primes: A__ = primea * primea for primea in primes: A__ = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: A__ = primea * primea * primea * primea A__ = square + cube + tetr if total >= limit: break ret.add(_UpperCAmelCase ) return len(_UpperCAmelCase ) if __name__ == "__main__": print(F'''{solution() = }''')
87
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
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. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class __snake_case ( A__ ): """simple docstring""" lowerCAmelCase_ : List[Any] = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCAmelCase_ : Any = '''CIDAS/clipseg-rd64-refined''' lowerCAmelCase_ : List[str] = '''image_segmenter''' lowerCAmelCase_ : str = CLIPSegForImageSegmentation lowerCAmelCase_ : List[Any] = ['''image''', '''text'''] lowerCAmelCase_ : List[str] = ['''image'''] def __init__( self :Tuple , *UpperCamelCase__ :Dict , **UpperCamelCase__ :Any ): requires_backends(self , ["vision"] ) super().__init__(*UpperCamelCase__ , **UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ ( self :Any , UpperCamelCase__ :Union[str, Any] , UpperCamelCase__ :Any ): return self.pre_processor(text=[label] , images=[image] , padding=UpperCamelCase__ , return_tensors="pt" ) def SCREAMING_SNAKE_CASE_ ( self :int , UpperCamelCase__ :Union[str, Any] ): with torch.no_grad(): _a = self.model(**UpperCamelCase__ ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , UpperCamelCase__ :int ): _a = outputs.cpu().detach().numpy() _a = 0 _a = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
388
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path a_ : str = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def lowerCamelCase__ (_UpperCAmelCase=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=A__ ) ) class _snake_case ( A__ ): _lowercase : Optional[Any] = None _lowercase : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = dataset_module_factory(a , cache_dir=a) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=a) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=a , config_name=a , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=a).replace(os.sep , '/'), config.DATASET_INFO_FILENAME, ]) SCREAMING_SNAKE_CASE = cached_path(a , cache_dir=a) self.assertTrue(os.path.exists(a)) @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('test_hf_gcp') / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert "train" in ds assert isinstance(ds['train'] , _UpperCAmelCase) assert next(iter(ds['train']))
73
0
'''simple docstring''' import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCamelCase__ ( A__ , A__ , unittest.TestCase ): """simple docstring""" UpperCamelCase__ = StableDiffusionDiffEditPipeline UpperCamelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} UpperCamelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} UpperCamelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess UpperCamelCase__ = frozenset([] ) def lowerCAmelCase_ ( self : Union[str, Any] ): torch.manual_seed(0 ) a__ = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") ,up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") ,cross_attention_dim=32 ,attention_head_dim=(2, 4) ,use_linear_projection=a__ ,) a__ = DDIMScheduler( beta_start=0.0_0085 ,beta_end=0.012 ,beta_schedule="scaled_linear" ,clip_sample=a__ ,set_alpha_to_one=a__ ,) a__ = DDIMInverseScheduler( beta_start=0.0_0085 ,beta_end=0.012 ,beta_schedule="scaled_linear" ,clip_sample=a__ ,set_alpha_to_zero=a__ ,) torch.manual_seed(0 ) a__ = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] ,up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] ,latent_channels=4 ,sample_size=1_28 ,) torch.manual_seed(0 ) a__ = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=10_00 ,hidden_act="gelu" ,projection_dim=5_12 ,) a__ = CLIPTextModel(a__ ) a__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) a__ = { "unet": unet, "scheduler": scheduler, "inverse_scheduler": inverse_scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def lowerCAmelCase_ ( self : Optional[int] ,a__ : Any ,a__ : Union[str, Any]=0 ): a__ = floats_tensor((1, 16, 16) ,rng=random.Random(a__ ) ).to(a__ ) a__ = floats_tensor((1, 2, 4, 16, 16) ,rng=random.Random(a__ ) ).to(a__ ) if str(a__ ).startswith("mps" ): a__ = torch.manual_seed(a__ ) else: a__ = torch.Generator(device=a__ ).manual_seed(a__ ) a__ = { "prompt": "a dog and a newt", "mask_image": mask, "image_latents": latents, "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def lowerCAmelCase_ ( self : str ,a__ : Optional[Any] ,a__ : int=0 ): a__ = floats_tensor((1, 3, 32, 32) ,rng=random.Random(a__ ) ).to(a__ ) a__ = image.cpu().permute(0 ,2 ,3 ,1 )[0] a__ = Image.fromarray(np.uinta(a__ ) ).convert("RGB" ) if str(a__ ).startswith("mps" ): a__ = torch.manual_seed(a__ ) else: a__ = torch.Generator(device=a__ ).manual_seed(a__ ) a__ = { "image": image, "source_prompt": "a cat and a frog", "target_prompt": "a dog and a newt", "generator": generator, "num_inference_steps": 2, "num_maps_per_mask": 2, "mask_encode_strength": 1.0, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def lowerCAmelCase_ ( self : Optional[Any] ,a__ : str ,a__ : Dict=0 ): a__ = floats_tensor((1, 3, 32, 32) ,rng=random.Random(a__ ) ).to(a__ ) a__ = image.cpu().permute(0 ,2 ,3 ,1 )[0] a__ = Image.fromarray(np.uinta(a__ ) ).convert("RGB" ) if str(a__ ).startswith("mps" ): a__ = torch.manual_seed(a__ ) else: a__ = torch.Generator(device=a__ ).manual_seed(a__ ) a__ = { "image": image, "prompt": "a cat and a frog", "generator": generator, "num_inference_steps": 2, "inpaint_strength": 1.0, "guidance_scale": 6.0, "decode_latents": True, "output_type": "numpy", } return inputs def lowerCAmelCase_ ( self : Tuple ): if not hasattr(self.pipeline_class ,"_optional_components" ): return a__ = self.get_dummy_components() a__ = self.pipeline_class(**a__ ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a__ ,a__ ,a__ ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) a__ = self.get_dummy_inputs(a__ ) a__ = pipe(**a__ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a__ ) a__ = self.pipeline_class.from_pretrained(a__ ) pipe_loaded.to(a__ ) pipe_loaded.set_progress_bar_config(disable=a__ ) for optional_component in pipe._optional_components: self.assertTrue( getattr(a__ ,a__ ) is None ,f'`{optional_component}` did not stay set to None after loading.' ,) a__ = self.get_dummy_inputs(a__ ) a__ = pipe_loaded(**a__ )[0] a__ = np.abs(output - output_loaded ).max() self.assertLess(a__ ,1e-4 ) def lowerCAmelCase_ ( self : Union[str, Any] ): a__ = "cpu" a__ = self.get_dummy_components() a__ = self.pipeline_class(**a__ ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) a__ = self.get_dummy_mask_inputs(a__ ) a__ = pipe.generate_mask(**a__ ) a__ = mask[0, -3:, -3:] self.assertEqual(mask.shape ,(1, 16, 16) ) a__ = np.array([0] * 9 ) a__ = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(a__ ,1e-3 ) self.assertEqual(mask[0, -3, -4] ,0 ) def lowerCAmelCase_ ( self : Tuple ): a__ = "cpu" a__ = self.get_dummy_components() a__ = self.pipeline_class(**a__ ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) a__ = self.get_dummy_inversion_inputs(a__ ) a__ = pipe.invert(**a__ ).images a__ = image[0, -1, -3:, -3:] self.assertEqual(image.shape ,(2, 32, 32, 3) ) a__ = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.5_1050, 0.5015, 0.4407, 0.4799] ,) a__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a__ ,1e-3 ) def lowerCAmelCase_ ( self : Union[str, Any] ): super().test_inference_batch_single_identical(expected_max_diff=5e-3 ) def lowerCAmelCase_ ( self : Optional[int] ): a__ = "cpu" a__ = self.get_dummy_components() a__ = {"beta_start": 0.0_0085, "beta_end": 0.012, "beta_schedule": "scaled_linear"} a__ = DPMSolverMultistepScheduler(**a__ ) a__ = DPMSolverMultistepInverseScheduler(**a__ ) a__ = self.pipeline_class(**a__ ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) a__ = self.get_dummy_inversion_inputs(a__ ) a__ = pipe.invert(**a__ ).images a__ = image[0, -1, -3:, -3:] self.assertEqual(image.shape ,(2, 32, 32, 3) ) a__ = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.5_1050, 0.5015, 0.4407, 0.4799] ,) a__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a__ ,1e-3 ) @require_torch_gpu @slow class lowerCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase_ ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def lowerCAmelCase_ ( cls : Tuple ): a__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png" ) a__ = raw_image.convert("RGB" ).resize((7_68, 7_68) ) a__ = raw_image def lowerCAmelCase_ ( self : Optional[Any] ): a__ = torch.manual_seed(0 ) a__ = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" ,safety_checker=a__ ,torch_dtype=torch.floataa ) a__ = DDIMScheduler.from_config(pipe.scheduler.config ) a__ = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a__ ) a__ = "a bowl of fruit" a__ = "a bowl of pears" a__ = pipe.generate_mask( image=self.raw_image ,source_prompt=a__ ,target_prompt=a__ ,generator=a__ ,) a__ = pipe.invert( prompt=a__ ,image=self.raw_image ,inpaint_strength=0.7 ,generator=a__ ).latents a__ = pipe( prompt=a__ ,mask_image=a__ ,image_latents=a__ ,generator=a__ ,negative_prompt=a__ ,inpaint_strength=0.7 ,output_type="numpy" ,).images[0] a__ = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((7_68, 7_68) ) ) / 2_55 ) assert np.abs((expected_image - image).max() ) < 5e-1 def lowerCAmelCase_ ( self : str ): a__ = torch.manual_seed(0 ) a__ = StableDiffusionDiffEditPipeline.from_pretrained( "stabilityai/stable-diffusion-2-1" ,safety_checker=a__ ,torch_dtype=torch.floataa ) a__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) a__ = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a__ ) a__ = "a bowl of fruit" a__ = "a bowl of pears" a__ = pipe.generate_mask( image=self.raw_image ,source_prompt=a__ ,target_prompt=a__ ,generator=a__ ,) a__ = pipe.invert( prompt=a__ ,image=self.raw_image ,inpaint_strength=0.7 ,generator=a__ ,num_inference_steps=25 ,).latents a__ = pipe( prompt=a__ ,mask_image=a__ ,image_latents=a__ ,generator=a__ ,negative_prompt=a__ ,inpaint_strength=0.7 ,num_inference_steps=25 ,output_type="numpy" ,).images[0] a__ = ( np.array( load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/diffedit/pears.png" ).resize((7_68, 7_68) ) ) / 2_55 ) assert np.abs((expected_image - image).max() ) < 5e-1
331
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
0
"""simple docstring""" import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging __snake_case : Union[str, Any] = { 'cola': 2, 'mnli': 3, 'mrpc': 2, 'sst-2': 2, 'sts-b': 1, 'qqp': 2, 'qnli': 2, 'rte': 2, 'wnli': 2, } logging.set_verbosity_info() def _lowercase ( __snake_case ,__snake_case ,__snake_case ,__snake_case=None ) -> List[Any]: # Initialise PyTorch model __lowerCAmelCase : Union[str, Any] = XLNetConfig.from_json_file(_UpperCAmelCase ) __lowerCAmelCase : str = finetuning_task.lower() if finetuning_task is not None else "" if finetuning_task in GLUE_TASKS_NUM_LABELS: print(F"""Building PyTorch XLNetForSequenceClassification model from configuration: {config}""" ) __lowerCAmelCase : List[str] = finetuning_task __lowerCAmelCase : Optional[int] = GLUE_TASKS_NUM_LABELS[finetuning_task] __lowerCAmelCase : List[Any] = XLNetForSequenceClassification(_UpperCAmelCase ) elif "squad" in finetuning_task: __lowerCAmelCase : Tuple = finetuning_task __lowerCAmelCase : Dict = XLNetForQuestionAnswering(_UpperCAmelCase ) else: __lowerCAmelCase : Dict = XLNetLMHeadModel(_UpperCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # Save pytorch-model __lowerCAmelCase : int = os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) __lowerCAmelCase : List[str] = os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) print(F"""Save PyTorch model to {os.path.abspath(_UpperCAmelCase )}""" ) torch.save(model.state_dict() ,_UpperCAmelCase ) print(F"""Save configuration file to {os.path.abspath(_UpperCAmelCase )}""" ) with open(_UpperCAmelCase ,"w" ,encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __snake_case : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--xlnet_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained XLNet model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--finetuning_task', default=None, type=str, help='Name of a task on which the XLNet TensorFlow model was fine-tuned', ) __snake_case : Dict = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
293
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append('10000000') else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
0
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase ( A__ ): '''simple docstring''' def __init__( self , lowercase__ , lowercase__ , lowercase__ ) -> Optional[int]: super().__init__() self.register_modules(vqvae=lowercase__ , unet=lowercase__ , scheduler=lowercase__ ) @torch.no_grad() def __call__( self , lowercase__ = 1 , lowercase__ = None , lowercase__ = 0.0 , lowercase__ = 50 , lowercase__ = "pil" , lowercase__ = True , **lowercase__ , ) -> Union[Tuple, ImagePipelineOutput]: SCREAMING_SNAKE_CASE : Dict = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=lowercase__ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler SCREAMING_SNAKE_CASE : Union[str, Any] = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(lowercase__ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature SCREAMING_SNAKE_CASE : str = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) SCREAMING_SNAKE_CASE : List[str] = {} if accepts_eta: SCREAMING_SNAKE_CASE : Dict = eta for t in self.progress_bar(self.scheduler.timesteps ): SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.scale_model_input(lowercase__ , lowercase__ ) # predict the noise residual SCREAMING_SNAKE_CASE : Optional[Any] = self.unet(lowercase__ , lowercase__ ).sample # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.step(lowercase__ , lowercase__ , lowercase__ , **lowercase__ ).prev_sample # decode the image latents with the VAE SCREAMING_SNAKE_CASE : int = self.vqvae.decode(lowercase__ ).sample SCREAMING_SNAKE_CASE : Optional[int] = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : Dict = self.numpy_to_pil(lowercase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowercase__ )
251
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ (_UpperCAmelCase): return 1.0 / (1.0 + np.exp(-_outputs)) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=_UpperCAmelCase) SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_UpperCAmelCase) class _snake_case ( A__ ): _lowercase : Tuple = '''sigmoid''' _lowercase : List[str] = '''softmax''' _lowercase : Tuple = '''none''' @add_end_docstrings( A__ , R''' return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. ''' , ) class _snake_case ( A__ ): _lowercase : Optional[Any] = False _lowercase : Tuple = ClassificationFunction.NONE def __init__( self , **a) -> Optional[Any]: super().__init__(**a) 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 , a=None , a=None , a="" , **a) -> Tuple: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" SCREAMING_SNAKE_CASE = tokenizer_kwargs SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , 'return_all_scores') and return_all_scores is None: SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(a , a) or top_k is None: SCREAMING_SNAKE_CASE = top_k SCREAMING_SNAKE_CASE = 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`.' , a , ) if return_all_scores: SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = 1 if isinstance(a , a): SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *a , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = super().__call__(*a , **a) # TODO try and retrieve it in a nicer way from _sanitize_parameters. SCREAMING_SNAKE_CASE = 'top_k' not in kwargs if isinstance(args[0] , a) 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 , a , **a) -> Dict[str, GenericTensor]: SCREAMING_SNAKE_CASE = self.framework if isinstance(a , a): return self.tokenizer(**a , return_tensors=a , **a) elif isinstance(a , a) and len(a) == 1 and isinstance(inputs[0] , a) 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=a , **a) elif isinstance(a , a): # 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(a , return_tensors=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: return self.model(**a) def SCREAMING_SNAKE_CASE__ ( self , a , a=None , a=1 , a=True) -> Any: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply') and function_to_apply is None: SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: SCREAMING_SNAKE_CASE = ClassificationFunction.NONE SCREAMING_SNAKE_CASE = model_outputs['logits'][0] SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: SCREAMING_SNAKE_CASE = sigmoid(a) elif function_to_apply == ClassificationFunction.SOFTMAX: SCREAMING_SNAKE_CASE = softmax(a) elif function_to_apply == ClassificationFunction.NONE: SCREAMING_SNAKE_CASE = 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()} SCREAMING_SNAKE_CASE = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a) ] if not _legacy: dict_scores.sort(key=lambda a: x["score"] , reverse=a) if top_k is not None: SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
73
0
import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format="""%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s""", datefmt="""%Y-%m-%d %H:%M:%S""", level=os.environ.get("""LOGLEVEL""", """INFO""").upper(), stream=sys.stdout, ) __lowerCamelCase = logging.getLogger(__name__) __lowerCamelCase = {'facebook/bart-base': BartForConditionalGeneration} __lowerCamelCase = {'facebook/bart-base': BartTokenizer} def UpperCamelCase ( ): snake_case : Any = argparse.ArgumentParser(description="Export Bart model + Beam Search to ONNX graph." ) parser.add_argument( "--validation_file" , type=_UpperCAmelCase , default=_UpperCAmelCase , help="A csv or a json file containing the validation data." ) parser.add_argument( "--max_length" , type=_UpperCAmelCase , default=5 , help="The maximum total input sequence length after tokenization." , ) parser.add_argument( "--num_beams" , type=_UpperCAmelCase , default=_UpperCAmelCase , help=( "Number of beams to use for evaluation. This argument will be " "passed to ``model.generate``, which is used during ``evaluate`` and ``predict``." ) , ) parser.add_argument( "--model_name_or_path" , type=_UpperCAmelCase , help="Path to pretrained model or model identifier from huggingface.co/models." , required=_UpperCAmelCase , ) parser.add_argument( "--config_name" , type=_UpperCAmelCase , default=_UpperCAmelCase , help="Pretrained config name or path if not the same as model_name" , ) parser.add_argument( "--device" , type=_UpperCAmelCase , default="cpu" , help="Device where the model will be run" , ) parser.add_argument("--output_file_path" , type=_UpperCAmelCase , default=_UpperCAmelCase , help="Where to store the final ONNX file." ) snake_case : Optional[int] = parser.parse_args() return args def UpperCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : Optional[int]="cpu" ): snake_case : Optional[int] = model_dict[model_name].from_pretrained(_UpperCAmelCase ).to(_UpperCAmelCase ) snake_case : Optional[int] = tokenizer_dict[model_name].from_pretrained(_UpperCAmelCase ) if model_name in ["facebook/bart-base"]: snake_case : Any = 0 snake_case : int = None snake_case : Union[str, Any] = 0 return huggingface_model, tokenizer def UpperCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : str , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : int ): model.eval() snake_case : Tuple = None snake_case : List[Any] = torch.jit.script(BARTBeamSearchGenerator(_UpperCAmelCase ) ) with torch.no_grad(): snake_case : Optional[int] = "My friends are cool but they eat too many carbs." snake_case : Optional[Any] = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors="pt" ).to(model.device ) snake_case : Any = model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , num_beams=_UpperCAmelCase , max_length=_UpperCAmelCase , early_stopping=_UpperCAmelCase , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( _UpperCAmelCase , ( inputs["input_ids"], inputs["attention_mask"], num_beams, max_length, model.config.decoder_start_token_id, ) , _UpperCAmelCase , opset_version=14 , input_names=["input_ids", "attention_mask", "num_beams", "max_length", "decoder_start_token_id"] , output_names=["output_ids"] , dynamic_axes={ "input_ids": {0: "batch", 1: "seq"}, "output_ids": {0: "batch", 1: "seq_out"}, } , example_outputs=_UpperCAmelCase , ) logger.info("Model exported to {}".format(_UpperCAmelCase ) ) snake_case : List[str] = remove_dup_initializers(os.path.abspath(_UpperCAmelCase ) ) logger.info("Deduplicated and optimized model written to {}".format(_UpperCAmelCase ) ) snake_case : Optional[int] = onnxruntime.InferenceSession(_UpperCAmelCase ) snake_case : List[str] = ort_sess.run( _UpperCAmelCase , { "input_ids": inputs["input_ids"].cpu().numpy(), "attention_mask": inputs["attention_mask"].cpu().numpy(), "num_beams": np.array(_UpperCAmelCase ), "max_length": np.array(_UpperCAmelCase ), "decoder_start_token_id": np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1E-3 , atol=1E-3 ) logger.info("Model outputs from torch and ONNX Runtime are similar." ) logger.info("Success." ) def UpperCamelCase ( ): snake_case : Tuple = parse_args() snake_case : Dict = 5 snake_case : List[Any] = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() snake_case : List[str] = torch.device(args.device ) snake_case , snake_case : Any = load_model_tokenizer(args.model_name_or_path , _UpperCAmelCase ) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined" ) model.to(_UpperCAmelCase ) if args.max_length: snake_case : int = args.max_length if args.num_beams: snake_case : List[Any] = args.num_beams if args.output_file_path: snake_case : Dict = args.output_file_path else: snake_case : Union[str, Any] = "BART.onnx" logger.info("Exporting model to ONNX" ) export_and_validate_model(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": main()
204
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase : Dict = logging.get_logger(__name__) __UpperCAmelCase : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _A = '''decision_transformer''' _A = ['''past_key_values'''] _A = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self ,UpperCamelCase=17 ,UpperCamelCase=4 ,UpperCamelCase=128 ,UpperCamelCase=4_096 ,UpperCamelCase=True ,UpperCamelCase=1 ,UpperCamelCase=1_024 ,UpperCamelCase=3 ,UpperCamelCase=1 ,UpperCamelCase=None ,UpperCamelCase="relu" ,UpperCamelCase=0.1 ,UpperCamelCase=0.1 ,UpperCamelCase=0.1 ,UpperCamelCase=1E-5 ,UpperCamelCase=0.02 ,UpperCamelCase=True ,UpperCamelCase=True ,UpperCamelCase=50_256 ,UpperCamelCase=50_256 ,UpperCamelCase=False ,UpperCamelCase=False ,**UpperCamelCase ,) -> List[str]: snake_case__ :Optional[Any] = state_dim snake_case__ :Union[str, Any] = act_dim snake_case__ :int = hidden_size snake_case__ :List[Any] = max_ep_len snake_case__ :Optional[Any] = action_tanh snake_case__ :Union[str, Any] = vocab_size snake_case__ :Dict = n_positions snake_case__ :List[str] = n_layer snake_case__ :str = n_head snake_case__ :List[str] = n_inner snake_case__ :Dict = activation_function snake_case__ :int = resid_pdrop snake_case__ :List[str] = embd_pdrop snake_case__ :int = attn_pdrop snake_case__ :Dict = layer_norm_epsilon snake_case__ :List[Any] = initializer_range snake_case__ :int = scale_attn_weights snake_case__ :Optional[int] = use_cache snake_case__ :List[Any] = scale_attn_by_inverse_layer_idx snake_case__ :Any = reorder_and_upcast_attn snake_case__ :Union[str, Any] = bos_token_id snake_case__ :Optional[Any] = eos_token_id super().__init__(bos_token_id=UpperCamelCase ,eos_token_id=UpperCamelCase ,**UpperCamelCase )
241
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure)
73
0
"""simple docstring""" from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def lowerCamelCase ( _snake_case ,_snake_case ,_snake_case = None ): if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path UpperCAmelCase__ : Union[str, Any] = quote(_UpperCAmelCase ) return hfh.hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ,revision=_UpperCAmelCase )
110
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _snake_case ( A__ ): _lowercase : Optional[Any] = '''decision_transformer''' _lowercase : str = ['''past_key_values'''] _lowercase : Union[str, Any] = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=17 , a=4 , a=128 , a=4096 , a=True , a=1 , a=1024 , a=3 , a=1 , a=None , a="relu" , a=0.1 , a=0.1 , a=0.1 , a=1E-5 , a=0.02 , a=True , a=True , a=5_0256 , a=5_0256 , a=False , a=False , **a , ) -> List[str]: SCREAMING_SNAKE_CASE = state_dim SCREAMING_SNAKE_CASE = act_dim SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = max_ep_len SCREAMING_SNAKE_CASE = action_tanh SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scale_attn_weights SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE = reorder_and_upcast_attn SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=a , eos_token_id=a , **a)
73
0
from __future__ import annotations def __UpperCAmelCase ( a_ , a_ , a_): if days_between_payments <= 0: raise ValueError('days_between_payments must be > 0') if daily_interest_rate < 0: raise ValueError('daily_interest_rate must be >= 0') if principal <= 0: raise ValueError('principal must be > 0') return principal * daily_interest_rate * days_between_payments def __UpperCAmelCase ( a_ , a_ , a_ , ): if number_of_compounding_periods <= 0: raise ValueError('number_of_compounding_periods must be > 0') if nominal_annual_interest_rate_percentage < 0: raise ValueError('nominal_annual_interest_rate_percentage must be >= 0') if principal <= 0: raise ValueError('principal must be > 0') return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def __UpperCAmelCase ( a_ , a_ , a_ , ): if number_of_years <= 0: raise ValueError('number_of_years must be > 0') if nominal_annual_percentage_rate < 0: raise ValueError('nominal_annual_percentage_rate must be >= 0') if principal <= 0: raise ValueError('principal must be > 0') return compound_interest( _UpperCAmelCase , nominal_annual_percentage_rate / 3_65 , number_of_years * 3_65) if __name__ == "__main__": import doctest doctest.testmod()
198
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[int] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __lowercase ( A__): """simple docstring""" _A : Tuple = ['''image_processor''', '''tokenizer'''] _A : List[Any] = '''ViTImageProcessor''' _A : Optional[Any] = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__(self , lowercase__=None , lowercase__=None , **lowercase__ ): snake_case_ : Tuple = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , lowercase__ , ) snake_case_ : str = kwargs.pop("""feature_extractor""" ) snake_case_ : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(lowercase__ , lowercase__ ) def __call__(self , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , **lowercase__ ): if text is None and visual_prompt is None and images is None: raise ValueError("""You have to specify either text, visual prompt or images.""" ) if text is not None and visual_prompt is not None: raise ValueError("""You have to specify exactly one type of prompt. Either text or visual prompt.""" ) if text is not None: snake_case_ : Tuple = self.tokenizer(lowercase__ , return_tensors=lowercase__ , **lowercase__ ) if visual_prompt is not None: snake_case_ : Tuple = self.image_processor(lowercase__ , return_tensors=lowercase__ , **lowercase__ ) if images is not None: snake_case_ : int = self.image_processor(lowercase__ , return_tensors=lowercase__ , **lowercase__ ) if visual_prompt is not None and images is not None: snake_case_ : Optional[Any] = { """pixel_values""": image_features.pixel_values, """conditional_pixel_values""": prompt_features.pixel_values, } return encoding elif text is not None and images is not None: snake_case_ : List[Any] = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: snake_case_ : int = { """conditional_pixel_values""": prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**lowercase__ ) , tensor_type=lowercase__ ) def __UpperCamelCase (self , *lowercase__ , **lowercase__ ): return self.tokenizer.batch_decode(*lowercase__ , **lowercase__ ) def __UpperCamelCase (self , *lowercase__ , **lowercase__ ): return self.tokenizer.decode(*lowercase__ , **lowercase__ ) @property def __UpperCamelCase (self ): warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , lowercase__ , ) return self.image_processor_class @property def __UpperCamelCase (self ): warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , lowercase__ , ) return self.image_processor
480
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : int = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
from __future__ import annotations import os import tempfile import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import is_tensorflow_text_available, is_tf_available from transformers.testing_utils import require_tensorflow_text, require_tf, slow from ..test_modeling_tf_common import floats_tensor from .test_framework_agnostic import GenerationIntegrationTestsMixin if is_tf_available(): import tensorflow as tf from transformers import ( AutoTokenizer, TFAutoModelForCausalLM, TFAutoModelForSeqaSeqLM, TFAutoModelForSpeechSeqaSeq, TFAutoModelForVisionaSeq, TFBartForConditionalGeneration, TFLogitsProcessorList, TFMinLengthLogitsProcessor, tf_top_k_top_p_filtering, ) if is_tensorflow_text_available(): import tensorflow_text as text @require_tf class UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = tf.convert_to_tensor( [ [ 8.2_220_991, # 3rd highest value; idx. 0 -0.5_620_044, 5.23_229_752, 4.0_386_393, -6.8_798_378, -0.54_785_802, -3.2_012_153, 2.92_777_176, 1.88_171_953, 7.35_341_276, # 5th highest value; idx. 9 8.43_207_833, # 2nd highest value; idx. 10 -9.85_711_836, -5.96_209_236, -1.13_039_161, -7.1_115_294, -0.8_369_633, -5.3_186_408, 7.06_427_407, 0.81_369_344, -0.82_023_817, -5.9_179_796, 0.58_813_443, -6.99_778_438, 4.71_551_189, -0.18_771_637, 7.44_020_759, # 4th highest value; idx. 25 9.38_450_987, # 1st highest value; idx. 26 2.12_662_941, -9.32_562_038, 2.35_652_522, ], # cummulative prob of 5 highest values <= 0.6 [ 0.58_425_518, 4.53_139_238, -5.57_510_464, -6.28_030_699, -7.19_529_503, -4.02_122_551, 1.39_337_037, -6.06_707_057, 1.59_480_517, -9.643_119, 0.03_907_799, 0.67_231_762, -8.88_206_726, 6.27_115_922, # 4th highest value; idx. 13 2.28_520_723, 4.82_767_506, 4.30_421_368, 8.8_275_313, # 2nd highest value; idx. 17 5.44_029_958, # 5th highest value; idx. 18 -4.4_735_794, 7.38_579_536, # 3rd highest value; idx. 20 -2.91_051_663, 2.61_946_077, -2.5_674_762, -9.48_959_302, -4.02_922_645, -1.35_416_918, 9.67_702_323, # 1st highest value; idx. 27 -5.89_478_553, 1.85_370_467, ], # cummulative prob of 5 highest values <= 0.6 ] , dtype=tf.floataa , ) UpperCamelCase = tf.convert_to_tensor( [[0, 0], [0, 9], [0, 1_0], [0, 2_5], [0, 2_6], [1, 1_3], [1, 1_7], [1, 1_8], [1, 2_0], [1, 2_7]] , dtype=tf.intaa , ) # expected non filtered idx as noted above UpperCamelCase = tf.convert_to_tensor( [8.222_099, 7.3_534_126, 8.432_078, 7.4_402_075, 9.38_451, 6.271_159, 8.827_531, 5.4_402_995, 7.3_857_956, 9.677_023] , dtype=tf.floataa , ) # expected non filtered values as noted above UpperCamelCase = tf_top_k_top_p_filtering(__magic_name__ , top_k=1_0 , top_p=0.6 , min_tokens_to_keep=4 ) UpperCamelCase = output[output != -float("""inf""" )] UpperCamelCase = tf.cast( tf.where(tf.not_equal(__magic_name__ , tf.constant(-float("""inf""" ) , dtype=tf.floataa ) ) ) , dtype=tf.intaa , ) tf.debugging.assert_near(__magic_name__ , __magic_name__ , rtol=1e-12 ) tf.debugging.assert_equal(__magic_name__ , __magic_name__ ) @require_tf class UpperCAmelCase ( unittest.TestCase , A__ ): # setting framework_dependent_parameters needs to be gated, just like its contents' imports if is_tf_available(): lowercase = { '''AutoModelForCausalLM''': TFAutoModelForCausalLM, '''AutoModelForSpeechSeq2Seq''': TFAutoModelForSpeechSeqaSeq, '''AutoModelForSeq2SeqLM''': TFAutoModelForSeqaSeqLM, '''AutoModelForVision2Seq''': TFAutoModelForVisionaSeq, '''LogitsProcessorList''': TFLogitsProcessorList, '''MinLengthLogitsProcessor''': TFMinLengthLogitsProcessor, '''create_tensor_fn''': tf.convert_to_tensor, '''floats_tensor''': floats_tensor, '''return_tensors''': '''tf''', } @slow def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = TFAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""" ) UpperCamelCase = 2 UpperCamelCase = 2 class UpperCAmelCase ( tf.Module ): def __init__( self : Any , __magic_name__ : Optional[int] ): """simple docstring""" super(__magic_name__ , self ).__init__() UpperCamelCase = model @tf.function( input_signature=( tf.TensorSpec((None, input_length) , tf.intaa , name="""input_ids""" ), tf.TensorSpec((None, input_length) , tf.intaa , name="""attention_mask""" ), ) , jit_compile=__magic_name__ , ) def lowerCamelCase_ ( self : Any , __magic_name__ : int , __magic_name__ : Union[str, Any] ): """simple docstring""" UpperCamelCase = self.model.generate( input_ids=__magic_name__ , attention_mask=__magic_name__ , max_new_tokens=__magic_name__ , return_dict_in_generate=__magic_name__ , ) return {"sequences": outputs["sequences"]} UpperCamelCase = [[2, 0], [1_0_2, 1_0_3]] UpperCamelCase = [[1, 0], [1, 1]] UpperCamelCase = DummyModel(model=__magic_name__ ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(__magic_name__ , __magic_name__ , signatures={"""serving_default""": dummy_model.serving} ) UpperCamelCase = tf.saved_model.load(__magic_name__ ).signatures["""serving_default"""] for batch_size in range(1 , len(__magic_name__ ) + 1 ): UpperCamelCase = { """input_ids""": tf.constant(dummy_input_ids[:batch_size] ), """attention_mask""": tf.constant(dummy_attention_masks[:batch_size] ), } UpperCamelCase = serving_func(**__magic_name__ )["""sequences"""] UpperCamelCase = test_model.generate(**__magic_name__ , max_new_tokens=__magic_name__ ) tf.debugging.assert_equal(__magic_name__ , __magic_name__ ) @slow def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = TFAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""" ) UpperCamelCase = 1 UpperCamelCase = 2 class UpperCAmelCase ( tf.Module ): def __init__( self : int , __magic_name__ : Any ): """simple docstring""" super(__magic_name__ , self ).__init__() UpperCamelCase = model @tf.function( input_signature=( tf.TensorSpec((batch_size, None) , tf.intaa , name="""input_ids""" ), tf.TensorSpec((batch_size, None) , tf.intaa , name="""attention_mask""" ), ) , jit_compile=__magic_name__ , ) def lowerCamelCase_ ( self : Tuple , __magic_name__ : str , __magic_name__ : Dict ): """simple docstring""" UpperCamelCase = self.model.generate( input_ids=__magic_name__ , attention_mask=__magic_name__ , max_new_tokens=__magic_name__ , return_dict_in_generate=__magic_name__ , ) return {"sequences": outputs["sequences"]} UpperCamelCase = [[2], [1_0_2, 1_0_3]] UpperCamelCase = [[1], [1, 1]] UpperCamelCase = DummyModel(model=__magic_name__ ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(__magic_name__ , __magic_name__ , signatures={"""serving_default""": dummy_model.serving} ) UpperCamelCase = tf.saved_model.load(__magic_name__ ).signatures["""serving_default"""] for input_row in range(len(__magic_name__ ) ): UpperCamelCase = { """input_ids""": tf.constant([dummy_input_ids[input_row]] ), """attention_mask""": tf.constant([dummy_attention_masks[input_row]] ), } UpperCamelCase = serving_func(**__magic_name__ )["""sequences"""] UpperCamelCase = test_model.generate(**__magic_name__ , max_new_tokens=__magic_name__ ) tf.debugging.assert_equal(__magic_name__ , __magic_name__ ) @slow @require_tensorflow_text def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: # file needed to load the TF tokenizer hf_hub_download(repo_id="""google/flan-t5-small""" , filename="""spiece.model""" , local_dir=__magic_name__ ) class UpperCAmelCase ( tf.keras.layers.Layer ): def __init__( self : List[str] ): """simple docstring""" super().__init__() UpperCamelCase = text.SentencepieceTokenizer( model=tf.io.gfile.GFile(os.path.join(__magic_name__ , """spiece.model""" ) , """rb""" ).read() ) UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) def lowerCamelCase_ ( self : Union[str, Any] , __magic_name__ : int , *__magic_name__ : Optional[Any] , **__magic_name__ : List[Any] ): """simple docstring""" UpperCamelCase = self.tokenizer.tokenize(__magic_name__ ) UpperCamelCase , UpperCamelCase = text.pad_model_inputs( __magic_name__ , max_seq_length=6_4 , pad_value=self.model.config.pad_token_id ) UpperCamelCase = self.model.generate(input_ids=__magic_name__ , attention_mask=__magic_name__ ) return self.tokenizer.detokenize(__magic_name__ ) UpperCamelCase = CompleteSentenceTransformer() UpperCamelCase = tf.keras.layers.Input(shape=(1,) , dtype=tf.string , name="""inputs""" ) UpperCamelCase = complete_model(__magic_name__ ) UpperCamelCase = tf.keras.Model(__magic_name__ , __magic_name__ ) keras_model.save(__magic_name__ ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = { """do_sample""": True, """num_beams""": 1, """top_p""": 0.7, """top_k""": 1_0, """temperature""": 0.7, } UpperCamelCase = 1_4 UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""" ) UpperCamelCase = """Hello, my dog is cute and""" UpperCamelCase = tokenizer(__magic_name__ , return_tensors="""tf""" ) UpperCamelCase = TFAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-random-gpt2""" ) UpperCamelCase = 6_3_8 # forces the generation to happen on CPU, to avoid GPU-related quirks with tf.device(""":/CPU:0""" ): tf.random.set_seed(0 ) UpperCamelCase = model.generate(**__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ ) self.assertTrue(expectation == len(generated_tokens[0] ) ) UpperCamelCase = [6_3_8, 1_9_8] with tf.device(""":/CPU:0""" ): tf.random.set_seed(0 ) UpperCamelCase = model.generate(**__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ ) self.assertTrue(expectation == len(generated_tokens[0] ) ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bart""" ) UpperCamelCase = """Hugging Face is a technology company based in New York and Paris.""" UpperCamelCase = bart_tokenizer(__magic_name__ , return_tensors="""tf""" ).input_ids UpperCamelCase = TFBartForConditionalGeneration.from_pretrained("""hf-internal-testing/tiny-random-bart""" ) UpperCamelCase = bart_model.generate(__magic_name__ ).numpy() class UpperCAmelCase ( A__ ): def lowerCamelCase_ ( self : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : Optional[Any]=None , **__magic_name__ : Dict ): """simple docstring""" return super().call(__magic_name__ , **__magic_name__ ) UpperCamelCase = FakeBart.from_pretrained("""hf-internal-testing/tiny-random-bart""" ) UpperCamelCase = bart_model.generate(__magic_name__ , foo="""bar""" ).numpy() self.assertTrue(np.array_equal(__magic_name__ , __magic_name__ ) ) class UpperCAmelCase ( bart_model.model.encoder.__class__ ): def lowerCamelCase_ ( self : Any , __magic_name__ : Optional[int] , **__magic_name__ : List[str] ): """simple docstring""" return super().call(__magic_name__ , **__magic_name__ ) UpperCamelCase = FakeEncoder(bart_model.config , bart_model.model.shared ) UpperCamelCase = fake_encoder # Normal generation still works (the output will be different because the encoder weights are different) UpperCamelCase = bart_model.generate(__magic_name__ ).numpy() with self.assertRaises(__magic_name__ ): # FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo" bart_model.generate(__magic_name__ , foo="""bar""" )
386
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): if radian_mode: return [magnitude * cos(_UpperCAmelCase), magnitude * sin(_UpperCAmelCase)] return [magnitude * cos(radians(_UpperCAmelCase)), magnitude * sin(radians(_UpperCAmelCase))] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 10**-1): SCREAMING_SNAKE_CASE = cross(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(_UpperCAmelCase) return abs(_UpperCAmelCase) < eps if __name__ == "__main__": # Test to check if it works a_ : int = array( [ polar_force(718.4, 1_80 - 30), polar_force(879.54, 45), polar_force(1_00, -90), ] ) a_ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg a_ : Dict = array( [ polar_force(30 * 9.81, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) a_ : Any = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg a_ : int = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) a_ : Optional[Any] = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
73
0
_lowerCamelCase : str = 'Alexander Joslin' import operator as op from .stack import Stack def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" A__ = {'''*''': op.mul, '''/''': op.truediv, '''+''': op.add, '''-''': op.sub} A__ = Stack() A__ = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(_UpperCAmelCase ) ) elif i in operators: # RULE 2 operator_stack.push(_UpperCAmelCase ) elif i == ")": # RULE 4 A__ = operator_stack.peek() operator_stack.pop() A__ = operand_stack.peek() operand_stack.pop() A__ = operand_stack.peek() operand_stack.pop() A__ = operators[opr](_UpperCAmelCase , _UpperCAmelCase ) operand_stack.push(_UpperCAmelCase ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": _lowerCamelCase : Dict = '(5 + ((4 * 2) * (2 + 3)))' # answer = 45 print(F'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
87
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : int = { '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 _snake_case ( A__ ): _lowercase : Dict = '''cvt''' def __init__( self , a=3 , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[64, 192, 384] , a=[1, 3, 6] , a=[1, 2, 10] , a=[4.0, 4.0, 4.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.0] , a=[0.0, 0.0, 0.1] , a=[True, True, True] , a=[False, False, True] , a=["dw_bn", "dw_bn", "dw_bn"] , a=[3, 3, 3] , a=[1, 1, 1] , a=[2, 2, 2] , a=[1, 1, 1] , a=[1, 1, 1] , a=0.02 , a=1E-12 , **a , ) -> List[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_sizes SCREAMING_SNAKE_CASE = patch_stride SCREAMING_SNAKE_CASE = patch_padding SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = depth SCREAMING_SNAKE_CASE = mlp_ratio SCREAMING_SNAKE_CASE = attention_drop_rate SCREAMING_SNAKE_CASE = drop_rate SCREAMING_SNAKE_CASE = drop_path_rate SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = cls_token SCREAMING_SNAKE_CASE = qkv_projection_method SCREAMING_SNAKE_CASE = kernel_qkv SCREAMING_SNAKE_CASE = padding_kv SCREAMING_SNAKE_CASE = stride_kv SCREAMING_SNAKE_CASE = padding_q SCREAMING_SNAKE_CASE = stride_q SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = layer_norm_eps
73
0
"""simple docstring""" # We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("""ignore""", category=UserWarning, module="""torch.optim.lr_scheduler""") class __snake_case : """simple docstring""" def __init__( self :Tuple , UpperCamelCase__ :int , UpperCamelCase__ :Optional[int] , UpperCamelCase__ :Union[str, Any] = True , UpperCamelCase__ :int = False ): _a = scheduler _a = optimizers if isinstance(UpperCamelCase__ , (list, tuple) ) else [optimizers] _a = split_batches _a = step_with_optimizer _a = GradientState() def SCREAMING_SNAKE_CASE_ ( self :List[str] , *UpperCamelCase__ :Optional[int] , **UpperCamelCase__ :Any ): if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*UpperCamelCase__ , **UpperCamelCase__ ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*UpperCamelCase__ , **UpperCamelCase__ ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step _a = AcceleratorState().num_processes for _ in range(UpperCamelCase__ ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , "total_steps" ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*UpperCamelCase__ , **UpperCamelCase__ ) else: self.scheduler.step(*UpperCamelCase__ , **UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return self.scheduler.get_last_lr() def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return self.scheduler.state_dict() def SCREAMING_SNAKE_CASE_ ( self :List[str] , UpperCamelCase__ :Tuple ): self.scheduler.load_state_dict(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.scheduler.get_lr() def SCREAMING_SNAKE_CASE_ ( self :List[str] , *UpperCamelCase__ :int , **UpperCamelCase__ :Optional[int] ): return self.scheduler.print_lr(*UpperCamelCase__ , **UpperCamelCase__ )
388
def lowerCamelCase__ (_UpperCAmelCase = 10 , _UpperCAmelCase = 1000 , _UpperCAmelCase = True): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)') return min_val if option else max_val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int((number_a + number_a) / 2) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): assert ( isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) and isinstance(_UpperCAmelCase , _UpperCAmelCase) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)') if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value') def answer(_UpperCAmelCase) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...') SCREAMING_SNAKE_CASE = lower SCREAMING_SNAKE_CASE = higher SCREAMING_SNAKE_CASE = [] while True: SCREAMING_SNAKE_CASE = get_avg(_UpperCAmelCase , _UpperCAmelCase) last_numbers.append(_UpperCAmelCase) if answer(_UpperCAmelCase) == "low": SCREAMING_SNAKE_CASE = number elif answer(_UpperCAmelCase) == "high": SCREAMING_SNAKE_CASE = number else: break print(F'''guess the number : {last_numbers[-1]}''') print(F'''details : {last_numbers!s}''') def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Enter lower value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter high value : ').strip()) SCREAMING_SNAKE_CASE = int(input('Enter value to guess : ').strip()) guess_the_number(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
73
0
'''simple docstring''' def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , _lowercase ): """simple docstring""" global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: a__ = mf_knapsack(i - 1 , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) else: a__ = max( mf_knapsack(i - 1 , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) , mf_knapsack(i - 1 , _UpperCAmelCase , _UpperCAmelCase , j - wt[i - 1] ) + val[i - 1] , ) a__ = val return f[i][j] def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , _lowercase ): """simple docstring""" a__ = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1 , n + 1 ): for w_ in range(1 , w + 1 ): if wt[i - 1] <= w_: a__ = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] ) else: a__ = dp[i - 1][w_] return dp[n][w_], dp def _lowerCAmelCase (_lowercase , _lowercase , _lowercase ): """simple docstring""" if not (isinstance(_UpperCAmelCase , (list, tuple) ) and isinstance(_UpperCAmelCase , (list, tuple) )): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) a__ = len(_UpperCAmelCase ) if num_items != len(_UpperCAmelCase ): a__ = ( "The number of weights must be the same as the number of values.\n" F'But got {num_items} weights and {len(_UpperCAmelCase )} values' ) raise ValueError(_UpperCAmelCase ) for i in range(_UpperCAmelCase ): if not isinstance(wt[i] , _UpperCAmelCase ): a__ = ( "All weights must be integers but got weight of " F'type {type(wt[i] )} at index {i}' ) raise TypeError(_UpperCAmelCase ) a__ , a__ = knapsack(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) a__ = set() _construct_solution(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) return optimal_val, example_optional_set def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): """simple docstring""" if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(_UpperCAmelCase , _UpperCAmelCase , i - 1 , _UpperCAmelCase , _UpperCAmelCase ) else: optimal_set.add(_UpperCAmelCase ) _construct_solution(_UpperCAmelCase , _UpperCAmelCase , i - 1 , j - wt[i - 1] , _UpperCAmelCase ) if __name__ == "__main__": UpperCamelCase_ : int = [3, 2, 4, 4] UpperCamelCase_ : Union[str, Any] = [4, 3, 2, 3] UpperCamelCase_ : Tuple = 4 UpperCamelCase_ : Optional[int] = 6 UpperCamelCase_ : Dict = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] UpperCamelCase_ : str = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 UpperCamelCase_ : Union[str, Any] = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("""optimal_value = """, optimal_solution) print("""An optimal subset corresponding to the optimal value""", optimal_subset)
331
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class _snake_case : def __init__( self , a , a=13 , 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=512 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> Union[str, 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 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: 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 = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , use_stable_embedding=a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Any: SCREAMING_SNAKE_CASE = OpenLlamaModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaModel(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , ) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , ) SCREAMING_SNAKE_CASE = model(a , attention_mask=a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = OpenLlamaForCausalLM(config=a) model.to(a) model.eval() # first forward pass SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , use_cache=a , ) SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1) SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , output_hidden_states=a , )['hidden_states'][0] SCREAMING_SNAKE_CASE = model( a , attention_mask=a , encoder_hidden_states=a , encoder_attention_mask=a , past_key_values=a , output_hidden_states=a , )['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1]).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a , a , atol=1E-3)) def SCREAMING_SNAKE_CASE__ ( self) -> 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, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) _lowercase : str = (OpenLlamaForCausalLM,) if is_torch_available() else () _lowercase : List[str] = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) _lowercase : List[str] = False _lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = OpenLlamaModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'single_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 'multi_label_classification' SCREAMING_SNAKE_CASE = input_dict['input_ids'] SCREAMING_SNAKE_CASE = input_ids.ne(1).to(a) SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float) SCREAMING_SNAKE_CASE = OpenLlamaForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels)) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass @parameterized.expand([('linear',), ('dynamic',)]) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ids_tensor([1, 10] , config.vocab_size) SCREAMING_SNAKE_CASE = ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = OpenLlamaModel(a) original_model.to(a) original_model.eval() SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state SCREAMING_SNAKE_CASE = original_model(a).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE = {'type': scaling_type, 'factor': 10.0} SCREAMING_SNAKE_CASE = OpenLlamaModel(a) scaled_model.to(a) scaled_model.eval() SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state SCREAMING_SNAKE_CASE = scaled_model(a).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a , a , atol=1E-5)) else: self.assertFalse(torch.allclose(a , a , atol=1E-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(a , a , atol=1E-5))
73
0
"""simple docstring""" # Algorithm for the pigeonhole sorting def _lowercase ( __snake_case ) -> Optional[int]: __lowerCAmelCase : Optional[Any] = min(_UpperCAmelCase ) # min() finds the minimum value __lowerCAmelCase : str = max(_UpperCAmelCase ) # max() finds the maximum value __lowerCAmelCase : int = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size __lowerCAmelCase : int = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. __lowerCAmelCase : Dict = 0 for count in range(_UpperCAmelCase ): while holes[count] > 0: holes[count] -= 1 __lowerCAmelCase : Dict = count + min_val i += 1 def _lowercase ( ) -> Tuple: __lowerCAmelCase : str = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(_UpperCAmelCase ) print("Sorted order is:" ," ".join(_UpperCAmelCase ) ) if __name__ == "__main__": main()
293
from __future__ import annotations a_ : str = [] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for i in range(len(_UpperCAmelCase)): if board[row][i] == 1: return False for i in range(len(_UpperCAmelCase)): if board[i][column] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , -1 , -1)): if board[i][j] == 1: return False for i, j in zip(range(_UpperCAmelCase , -1 , -1) , range(_UpperCAmelCase , len(_UpperCAmelCase))): if board[i][j] == 1: return False return True def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if row >= len(_UpperCAmelCase): solution.append(_UpperCAmelCase) printboard(_UpperCAmelCase) print() return True for i in range(len(_UpperCAmelCase)): if is_safe(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 solve(_UpperCAmelCase , row + 1) SCREAMING_SNAKE_CASE = 0 return False def lowerCamelCase__ (_UpperCAmelCase): for i in range(len(_UpperCAmelCase)): for j in range(len(_UpperCAmelCase)): if board[i][j] == 1: print('Q' , end=' ') else: print('.' , end=' ') print() # n=int(input("The no. of queens")) a_ : Tuple = 8 a_ : int = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
73
0
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np _lowerCAmelCase :Optional[Any] = re.compile(R"""\b(a|an|the)\b""", re.UNICODE) _lowerCAmelCase :List[str] = None def __lowerCAmelCase ( ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.' ) parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.' ) parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.' ) parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).' ) parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.' ) parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.' ) parser.add_argument('--verbose' , '-v' , action='store_true' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __lowerCAmelCase ( a_ ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE : Any = bool(qa['answers']['text'] ) return qid_to_has_ans def __lowerCAmelCase ( a_ ) -> List[str]: '''simple docstring''' def remove_articles(a_ ): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase ) def white_space_fix(a_ ): return " ".join(text.split() ) def remove_punc(a_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(a_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase ) ) ) ) def __lowerCAmelCase ( a_ ) -> Dict: '''simple docstring''' if not s: return [] return normalize_answer(_UpperCAmelCase ).split() def __lowerCAmelCase ( a_ , a_ ) -> str: '''simple docstring''' return int(normalize_answer(_UpperCAmelCase ) == normalize_answer(_UpperCAmelCase ) ) def __lowerCAmelCase ( a_ , a_ ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = get_tokens(_UpperCAmelCase ) SCREAMING_SNAKE_CASE : str = get_tokens(_UpperCAmelCase ) SCREAMING_SNAKE_CASE : List[str] = collections.Counter(_UpperCAmelCase ) & collections.Counter(_UpperCAmelCase ) SCREAMING_SNAKE_CASE : Any = sum(common.values() ) if len(_UpperCAmelCase ) == 0 or len(_UpperCAmelCase ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 SCREAMING_SNAKE_CASE : str = 1.0 * num_same / len(_UpperCAmelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = 1.0 * num_same / len(_UpperCAmelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = (2 * precision * recall) / (precision + recall) return fa def __lowerCAmelCase ( a_ , a_ ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Optional[int] = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE : Optional[Any] = qa['id'] SCREAMING_SNAKE_CASE : Dict = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase )] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE : int = [''] if qid not in preds: print(f"""Missing prediction for {qid}""" ) continue SCREAMING_SNAKE_CASE : Optional[int] = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE : str = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase ) for a in gold_answers ) SCREAMING_SNAKE_CASE : Optional[int] = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase ) for a in gold_answers ) return exact_scores, fa_scores def __lowerCAmelCase ( a_ , a_ , a_ , a_ ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE : List[str] = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE : List[str] = float(not qid_to_has_ans[qid] ) else: SCREAMING_SNAKE_CASE : List[str] = s return new_scores def __lowerCAmelCase ( a_ , a_ , a_=None ) -> Optional[Any]: '''simple docstring''' if not qid_list: SCREAMING_SNAKE_CASE : Dict = len(_UpperCAmelCase ) return collections.OrderedDict( [ ('exact', 100.0 * sum(exact_scores.values() ) / total), ('f1', 100.0 * sum(fa_scores.values() ) / total), ('total', total), ] ) else: SCREAMING_SNAKE_CASE : Tuple = len(_UpperCAmelCase ) return collections.OrderedDict( [ ('exact', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('f1', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('total', total), ] ) def __lowerCAmelCase ( a_ , a_ , a_ ) -> str: '''simple docstring''' for k in new_eval: SCREAMING_SNAKE_CASE : Tuple = new_eval[k] def __lowerCAmelCase ( a_ , a_ , a_ , a_ ) -> Optional[int]: '''simple docstring''' plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post' ) plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b' ) plt.xlabel('Recall' ) plt.ylabel('Precision' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(_UpperCAmelCase ) plt.savefig(_UpperCAmelCase ) plt.clf() def __lowerCAmelCase ( a_ , a_ , a_ , a_ , a_=None , a_=None ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = sorted(_UpperCAmelCase , key=lambda a_ : na_probs[k] ) SCREAMING_SNAKE_CASE : Optional[int] = 0.0 SCREAMING_SNAKE_CASE : Union[str, Any] = 1.0 SCREAMING_SNAKE_CASE : Union[str, Any] = 0.0 SCREAMING_SNAKE_CASE : Tuple = [1.0] SCREAMING_SNAKE_CASE : int = [0.0] SCREAMING_SNAKE_CASE : str = 0.0 for i, qid in enumerate(_UpperCAmelCase ): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE : Any = true_pos / float(i + 1 ) SCREAMING_SNAKE_CASE : Any = true_pos / float(_UpperCAmelCase ) if i == len(_UpperCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase ) recalls.append(_UpperCAmelCase ) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) return {"ap": 100.0 * avg_prec} def __lowerCAmelCase ( a_ , a_ , a_ , a_ , a_ , a_ ) -> Optional[int]: '''simple docstring''' if out_image_dir and not os.path.exists(_UpperCAmelCase ): os.makedirs(_UpperCAmelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return SCREAMING_SNAKE_CASE : List[Any] = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png' ) , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE : str = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png' ) , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE : int = {k: float(_UpperCAmelCase ) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE : Optional[Any] = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png' ) , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact' ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1' ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle' ) def __lowerCAmelCase ( a_ , a_ , a_ , a_ ) -> List[Any]: '''simple docstring''' if not qid_list: return SCREAMING_SNAKE_CASE : Optional[Any] = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE : str = np.ones_like(_UpperCAmelCase ) / float(len(_UpperCAmelCase ) ) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0) ) plt.xlabel('Model probability of no-answer' ) plt.ylabel('Proportion of dataset' ) plt.title(f"""Histogram of no-answer probability: {name}""" ) plt.savefig(os.path.join(_UpperCAmelCase , f"""na_prob_hist_{name}.png""" ) ) plt.clf() def __lowerCAmelCase ( a_ , a_ , a_ , a_ ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) SCREAMING_SNAKE_CASE : str = num_no_ans SCREAMING_SNAKE_CASE : Union[str, Any] = cur_score SCREAMING_SNAKE_CASE : Union[str, Any] = 0.0 SCREAMING_SNAKE_CASE : Optional[Any] = sorted(_UpperCAmelCase , key=lambda a_ : na_probs[k] ) for i, qid in enumerate(_UpperCAmelCase ): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE : List[str] = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE : str = -1 else: SCREAMING_SNAKE_CASE : Union[str, Any] = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE : Tuple = cur_score SCREAMING_SNAKE_CASE : Optional[int] = na_probs[qid] return 100.0 * best_score / len(_UpperCAmelCase ), best_thresh def __lowerCAmelCase ( a_ , a_ , a_ , a_ , a_ , a_ ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE : Optional[int] = best_exact SCREAMING_SNAKE_CASE : List[str] = exact_thresh SCREAMING_SNAKE_CASE : str = best_fa SCREAMING_SNAKE_CASE : int = fa_thresh def __lowerCAmelCase ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: SCREAMING_SNAKE_CASE : Optional[Any] = json.load(_UpperCAmelCase ) SCREAMING_SNAKE_CASE : List[str] = dataset_json['data'] with open(OPTS.pred_file ) as f: SCREAMING_SNAKE_CASE : Union[str, Any] = json.load(_UpperCAmelCase ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: SCREAMING_SNAKE_CASE : Any = json.load(_UpperCAmelCase ) else: SCREAMING_SNAKE_CASE : List[str] = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE : Union[str, Any] = make_qid_to_has_ans(_UpperCAmelCase ) # maps qid to True/False SCREAMING_SNAKE_CASE : Optional[Any] = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE : Optional[Any] = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE : Optional[int] = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh ) SCREAMING_SNAKE_CASE : Optional[int] = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh ) SCREAMING_SNAKE_CASE : Dict = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase ) if has_ans_qids: SCREAMING_SNAKE_CASE : Optional[int] = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns' ) if no_ans_qids: SCREAMING_SNAKE_CASE : Any = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns' ) if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir ) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns' ) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns' ) if OPTS.out_file: with open(OPTS.out_file , 'w' ) as f: json.dump(_UpperCAmelCase , _UpperCAmelCase ) else: print(json.dumps(_UpperCAmelCase , indent=2 ) ) if __name__ == "__main__": _lowerCAmelCase :Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("""Agg""") import matplotlib.pyplot as plt main()
251
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = StableDiffusionDiffEditPipeline _lowercase : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''} _lowercase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''} _lowercase : List[str] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowercase : List[str] = frozenset([] ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: torch.manual_seed(0) SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a , ) SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=a , set_alpha_to_zero=a , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0) SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) SCREAMING_SNAKE_CASE = CLIPTextModel(a) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(a)).to(a) if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> List[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(a)).to(a) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1)[0] SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(a)).convert('RGB') if str(a).startswith('mps'): SCREAMING_SNAKE_CASE = torch.manual_seed(a) else: SCREAMING_SNAKE_CASE = torch.Generator(device=a).manual_seed(a) SCREAMING_SNAKE_CASE = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if not hasattr(self.pipeline_class , '_optional_components'): return SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(a , a , a) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe(**a)[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(a) pipe_loaded.to(a) pipe_loaded.set_progress_bar_config(disable=a) for optional_component in pipe._optional_components: self.assertTrue( getattr(a , a) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(a) SCREAMING_SNAKE_CASE = pipe_loaded(**a)[0] SCREAMING_SNAKE_CASE = np.abs(output - output_loaded).max() self.assertLess(a , 1E-4) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(a) SCREAMING_SNAKE_CASE = pipe.generate_mask(**a) SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16)) SCREAMING_SNAKE_CASE = np.array([0] * 9) SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) self.assertEqual(mask[0, -3, -4] , 0) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=5E-3) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'cpu' SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**a) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**a) SCREAMING_SNAKE_CASE = self.pipeline_class(**a) pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(a) SCREAMING_SNAKE_CASE = pipe.invert(**a).images SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3)) SCREAMING_SNAKE_CASE = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(a , 1E-3) @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> List[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png') SCREAMING_SNAKE_CASE = raw_image.convert('RGB').resize((768, 768)) SCREAMING_SNAKE_CASE = raw_image def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=a , torch_dtype=torch.floataa) SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'a bowl of fruit' SCREAMING_SNAKE_CASE = 'a bowl of pears' SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=a , target_prompt=a , generator=a , ) SCREAMING_SNAKE_CASE = pipe.invert( prompt=a , image=self.raw_image , inpaint_strength=0.7 , generator=a , num_inference_steps=25 , ).latents SCREAMING_SNAKE_CASE = pipe( prompt=a , mask_image=a , image_latents=a , generator=a , negative_prompt=a , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] SCREAMING_SNAKE_CASE = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png').resize((768, 768))) / 255 ) assert np.abs((expected_image - image).max()) < 5E-1
73
0
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : Optional[Any] ): snake_case : List[Any] = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" snake_case : Union[str, Any] = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase ).raw ).convert("RGB" ) snake_case : Dict = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) snake_case : Dict = transform(_UpperCAmelCase ).unsqueeze(0 ).to(_UpperCAmelCase ) return image def UpperCamelCase ( __lowerCamelCase : str ): if "visual_encoder" in key: snake_case : List[str] = re.sub("visual_encoder*" , "vision_model.encoder" , _UpperCAmelCase ) if "blocks" in key: snake_case : Optional[int] = re.sub(r"blocks" , "layers" , _UpperCAmelCase ) if "attn" in key: snake_case : List[Any] = re.sub(r"attn" , "self_attn" , _UpperCAmelCase ) if "norm1" in key: snake_case : str = re.sub(r"norm1" , "layer_norm1" , _UpperCAmelCase ) if "norm2" in key: snake_case : Optional[Any] = re.sub(r"norm2" , "layer_norm2" , _UpperCAmelCase ) if "encoder.norm" in key: snake_case : List[Any] = re.sub(r"encoder.norm" , "post_layernorm" , _UpperCAmelCase ) if "encoder.patch_embed.proj" in key: snake_case : int = re.sub(r"encoder.patch_embed.proj" , "embeddings.patch_embedding" , _UpperCAmelCase ) if "encoder.pos_embed" in key: snake_case : Dict = re.sub(r"encoder.pos_embed" , "embeddings.position_embedding" , _UpperCAmelCase ) if "encoder.cls_token" in key: snake_case : Optional[Any] = re.sub(r"encoder.cls_token" , "embeddings.class_embedding" , _UpperCAmelCase ) if "self_attn" in key: snake_case : Optional[Any] = re.sub(r"self_attn.proj" , "self_attn.projection" , _UpperCAmelCase ) return key @torch.no_grad() def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : Any=None ): if config_path is not None: snake_case : Optional[int] = BlipConfig.from_pretrained(_UpperCAmelCase ) else: snake_case : Any = BlipConfig(projection_dim=512 , text_config={} , vision_config={} ) snake_case : Union[str, Any] = BlipForConditionalGeneration(_UpperCAmelCase ).eval() snake_case : str = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" snake_case : Optional[Any] = blip_decoder(pretrained=_UpperCAmelCase , image_size=384 , vit="base" ) snake_case : List[str] = pt_model.eval() snake_case : Any = pt_model.state_dict() for key in modified_state_dict.copy(): snake_case : Tuple = modified_state_dict.pop(_UpperCAmelCase ) snake_case : Optional[Any] = rename_key(_UpperCAmelCase ) snake_case : Tuple = value hf_model.load_state_dict(_UpperCAmelCase ) snake_case : int = 384 snake_case : List[str] = load_demo_image(image_size=_UpperCAmelCase , device="cpu" ) snake_case : List[str] = BertTokenizer.from_pretrained("bert-base-uncased" ) snake_case : Optional[Any] = tokenizer(["a picture of"] ).input_ids snake_case : Optional[int] = hf_model.generate(_UpperCAmelCase , _UpperCAmelCase ) assert out[0].tolist() == [30522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] snake_case : Optional[Any] = hf_model.generate(_UpperCAmelCase ) assert out[0].tolist() == [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(_UpperCAmelCase ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' snake_case : List[str] = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) snake_case : List[Any] = blip_vqa(pretrained=_UpperCAmelCase , image_size=_UpperCAmelCase , vit="base" ) vqa_model.eval() snake_case : int = vqa_model.state_dict() for key in modified_state_dict.copy(): snake_case : List[Any] = modified_state_dict.pop(_UpperCAmelCase ) snake_case : Optional[int] = rename_key(_UpperCAmelCase ) snake_case : List[str] = value snake_case : List[str] = BlipForQuestionAnswering(_UpperCAmelCase ) hf_vqa_model.load_state_dict(_UpperCAmelCase ) snake_case : List[str] = ["How many dogs are in this image?"] snake_case : Optional[Any] = tokenizer(_UpperCAmelCase , return_tensors="pt" ).input_ids snake_case : str = hf_vqa_model.generate(_UpperCAmelCase , _UpperCAmelCase ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) snake_case : str = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" snake_case : List[Any] = blip_itm(pretrained=_UpperCAmelCase , image_size=_UpperCAmelCase , vit="base" ) itm_model.eval() snake_case : Optional[Any] = itm_model.state_dict() for key in modified_state_dict.copy(): snake_case : Optional[Any] = modified_state_dict.pop(_UpperCAmelCase ) snake_case : List[str] = rename_key(_UpperCAmelCase ) snake_case : Tuple = value snake_case : Dict = BlipForImageTextRetrieval(_UpperCAmelCase ) snake_case : Optional[Any] = ["A picture of a woman with a dog sitting in a beach"] snake_case : Dict = tokenizer( _UpperCAmelCase , return_tensors="pt" , padding="max_length" , truncation=_UpperCAmelCase , max_length=35 , ).input_ids hf_itm_model.load_state_dict(_UpperCAmelCase ) hf_itm_model.eval() snake_case : Union[str, Any] = hf_itm_model(_UpperCAmelCase , _UpperCAmelCase , use_itm_head=_UpperCAmelCase ) snake_case : int = hf_itm_model(_UpperCAmelCase , _UpperCAmelCase , use_itm_head=_UpperCAmelCase ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": __lowerCamelCase = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") __lowerCamelCase = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
204
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Any = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _snake_case ( A__ ): _lowercase : Optional[int] = '''unispeech''' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="mean" , a=False , a=False , a=256 , a=80 , a=0 , a=1 , a=2 , a=0.5 , **a , ) -> Optional[int]: super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = list(a) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_ctc_classes SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum SCREAMING_SNAKE_CASE = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE = replace_prob @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return functools.reduce(operator.mul , self.conv_stride , 1)
73
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _snake_case ( A__ ): _A = '''ClapFeatureExtractor''' _A = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self ,UpperCamelCase ,UpperCamelCase ) -> Optional[int]: super().__init__(UpperCamelCase ,UpperCamelCase ) def __call__( self ,UpperCamelCase=None ,UpperCamelCase=None ,UpperCamelCase=None ,**UpperCamelCase ) -> int: snake_case__ :int = kwargs.pop("sampling_rate" ,UpperCamelCase ) if text is None and audios is None: raise ValueError("You have to specify either text or audios. Both cannot be none." ) if text is not None: snake_case__ :Optional[Any] = self.tokenizer(UpperCamelCase ,return_tensors=UpperCamelCase ,**UpperCamelCase ) if audios is not None: snake_case__ :Optional[int] = self.feature_extractor( UpperCamelCase ,sampling_rate=UpperCamelCase ,return_tensors=UpperCamelCase ,**UpperCamelCase ) if text is not None and audios is not None: snake_case__ :Dict = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCamelCase ) ,tensor_type=UpperCamelCase ) def lowerCAmelCase_ ( self ,*UpperCamelCase ,**UpperCamelCase ) -> List[str]: return self.tokenizer.batch_decode(*UpperCamelCase ,**UpperCamelCase ) def lowerCAmelCase_ ( self ,*UpperCamelCase ,**UpperCamelCase ) -> Union[str, Any]: return self.tokenizer.decode(*UpperCamelCase ,**UpperCamelCase ) @property def lowerCAmelCase_ ( self ) -> str: snake_case__ :Any = self.tokenizer.model_input_names snake_case__ :Optional[Any] = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
241
import argparse import collections import json import os import re import string import sys import numpy as np a_ : Optional[Any] = re.compile(R'\b(a|an|the)\b', re.UNICODE) a_ : List[str] = None def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.') parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.') parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).') parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.') parser.add_argument( '--na-prob-thresh' , '-t' , type=_UpperCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=_UpperCAmelCase , help='Save precision-recall curves to directory.') parser.add_argument('--verbose' , '-v' , action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa['answers']['text']) return qid_to_has_ans def lowerCamelCase__ (_UpperCAmelCase): def remove_articles(_UpperCAmelCase): return ARTICLES_REGEX.sub(' ' , _UpperCAmelCase) def white_space_fix(_UpperCAmelCase): return " ".join(text.split()) def remove_punc(_UpperCAmelCase): SCREAMING_SNAKE_CASE = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(_UpperCAmelCase): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_UpperCAmelCase)))) def lowerCamelCase__ (_UpperCAmelCase): if not s: return [] return normalize_answer(_UpperCAmelCase).split() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return int(normalize_answer(_UpperCAmelCase) == normalize_answer(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_tokens(_UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.Counter(_UpperCAmelCase) & collections.Counter(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(common.values()) if len(_UpperCAmelCase) == 0 or len(_UpperCAmelCase) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa['id'] SCREAMING_SNAKE_CASE = [t for t in qa['answers']['text'] if normalize_answer(_UpperCAmelCase)] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [''] if qid not in preds: print(F'''Missing prediction for {qid}''') continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) SCREAMING_SNAKE_CASE = max(compute_fa(_UpperCAmelCase , _UpperCAmelCase) for a in gold_answers) return exact_scores, fa_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid]) else: SCREAMING_SNAKE_CASE = s return new_scores def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): if not qid_list: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values()) / total), ('f1', 1_00.0 * sum(fa_scores.values()) / total), ('total', total), ]) else: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list) / total), ('total', total), ]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): plt.step(_UpperCAmelCase , _UpperCAmelCase , color='b' , alpha=0.2 , where='post') plt.fill_between(_UpperCAmelCase , _UpperCAmelCase , step='post' , alpha=0.2 , color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(_UpperCAmelCase) plt.savefig(_UpperCAmelCase) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(_UpperCAmelCase): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1) SCREAMING_SNAKE_CASE = true_pos / float(_UpperCAmelCase) if i == len(_UpperCAmelCase) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_UpperCAmelCase) recalls.append(_UpperCAmelCase) if out_image: plot_pr_curve(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) return {"ap": 1_00.0 * avg_prec} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if out_image_dir and not os.path.exists(_UpperCAmelCase): os.makedirs(_UpperCAmelCase) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_exact.png') , title='Precision-Recall curve for Exact Match score' , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_f1.png') , title='Precision-Recall curve for F1 score' , ) SCREAMING_SNAKE_CASE = {k: float(_UpperCAmelCase) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , out_image=os.path.join(_UpperCAmelCase , 'pr_oracle.png') , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_exact') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_f1') merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'pr_oracle') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(_UpperCAmelCase) / float(len(_UpperCAmelCase)) plt.hist(_UpperCAmelCase , weights=_UpperCAmelCase , bins=20 , range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title(F'''Histogram of no-answer probability: {name}''') plt.savefig(os.path.join(_UpperCAmelCase , F'''na_prob_hist_{name}.png''')) plt.clf() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase: na_probs[k]) for i, qid in enumerate(_UpperCAmelCase): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 1_00.0 * best_score / len(_UpperCAmelCase), best_thresh def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def lowerCamelCase__ (): with open(OPTS.data_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) SCREAMING_SNAKE_CASE = dataset_json['data'] with open(OPTS.pred_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: SCREAMING_SNAKE_CASE = json.load(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(_UpperCAmelCase) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.na_prob_thresh) SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'HasAns') if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(_UpperCAmelCase , _UpperCAmelCase , qid_list=_UpperCAmelCase) merge_eval(_UpperCAmelCase , _UpperCAmelCase , 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir) histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'hasAns') histogram_na_prob(_UpperCAmelCase , _UpperCAmelCase , OPTS.out_image_dir , 'noAns') if OPTS.out_file: with open(OPTS.out_file , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase) else: print(json.dumps(_UpperCAmelCase , indent=2)) if __name__ == "__main__": a_ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
73
0
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger UpperCamelCase__ = '<<<<<<< This should probably be modified because it mentions: ' UpperCamelCase__ = '=======\n>>>>>>>\n' UpperCamelCase__ = [ 'TextEncoderConfig', 'ByteTextEncoder', 'SubwordTextEncoder', 'encoder_config', 'maybe_build_from_corpus', 'manual_dir', ] UpperCamelCase__ = [ # (pattern, replacement) # Order is important here for some replacements (R'tfds\.core', R'datasets'), (R'tf\.io\.gfile\.GFile', R'open'), (R'tf\.([\w\d]+)', R'datasets.Value(\'\1\')'), (R'tfds\.features\.Text\(\)', R'datasets.Value(\'string\')'), (R'tfds\.features\.Text\(', R'datasets.Value(\'string\'),'), (R'features\s*=\s*tfds.features.FeaturesDict\(', R'features=datasets.Features('), (R'tfds\.features\.FeaturesDict\(', R'dict('), (R'The TensorFlow Datasets Authors', R'The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'), (R'tfds\.', R'datasets.'), (R'dl_manager\.manual_dir', R'self.config.data_dir'), (R'self\.builder_config', R'self.config'), ] def lowerCamelCase ( _snake_case ): return ConvertCommand(args.tfds_path ,args.datasets_directory ) class a ( A__ ): @staticmethod def __snake_case ( UpperCamelCase_ ): UpperCAmelCase__ : Tuple = parser.add_parser( 'convert' , help='Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.' , ) train_parser.add_argument( '--tfds_path' , type=UpperCamelCase_ , required=UpperCamelCase_ , help='Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.' , ) train_parser.add_argument( '--datasets_directory' , type=UpperCamelCase_ , required=UpperCamelCase_ , help='Path to the HuggingFace Datasets folder.' ) train_parser.set_defaults(func=UpperCamelCase_ ) def __init__( self , UpperCamelCase_ , UpperCamelCase_ , *UpperCamelCase_ ): UpperCAmelCase__ : Optional[int] = get_logger('datasets-cli/converting' ) UpperCAmelCase__ : Optional[Any] = tfds_path UpperCAmelCase__ : int = datasets_directory def __snake_case ( self ): if os.path.isdir(self._tfds_path ): UpperCAmelCase__ : Any = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): UpperCAmelCase__ : Optional[int] = os.path.dirname(self._tfds_path ) else: raise ValueError('--tfds_path is neither a directory nor a file. Please check path.' ) UpperCAmelCase__ : Tuple = os.path.abspath(self._datasets_directory ) self._logger.info(F'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) UpperCAmelCase__ : List[str] = [] UpperCAmelCase__ : List[Any] = [] UpperCAmelCase__ : List[Any] = {} if os.path.isdir(self._tfds_path ): UpperCAmelCase__ : Dict = os.listdir(UpperCamelCase_ ) else: UpperCAmelCase__ : Dict = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(F'''Looking at file {f_name}''' ) UpperCAmelCase__ : List[str] = os.path.join(UpperCamelCase_ , UpperCamelCase_ ) UpperCAmelCase__ : List[str] = os.path.join(UpperCamelCase_ , UpperCamelCase_ ) if not os.path.isfile(UpperCamelCase_ ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info('Skipping file' ) continue with open(UpperCamelCase_ , encoding='utf-8' ) as f: UpperCAmelCase__ : Optional[Any] = f.readlines() UpperCAmelCase__ : Any = [] UpperCAmelCase__ : List[Any] = False UpperCAmelCase__ : str = False UpperCAmelCase__ : Any = [] for line in lines: UpperCAmelCase__ : int = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: UpperCAmelCase__ : str = 'import datasets\n' elif "import tensorflow" in out_line: # order is important here UpperCAmelCase__ : int = '' continue elif "from absl import logging" in out_line: UpperCAmelCase__ : Any = 'from datasets import logging\n' elif "getLogger" in out_line: UpperCAmelCase__ : List[Any] = out_line.replace('getLogger' , 'get_logger' ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): UpperCAmelCase__ : int = True UpperCAmelCase__ : Any = list(filter(lambda UpperCamelCase_ : e in out_line , UpperCamelCase_ ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(UpperCamelCase_ ) + '\n' ) out_lines.append(UpperCamelCase_ ) out_lines.append(UpperCamelCase_ ) continue else: for pattern, replacement in TO_CONVERT: UpperCAmelCase__ : int = re.sub(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: UpperCAmelCase__ : Optional[Any] = re.match(R'from\stensorflow_datasets.*import\s([^\.\r\n]+)' , UpperCamelCase_ ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(',' ) ) UpperCAmelCase__ : Optional[Any] = 'from . import ' + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(F'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: UpperCAmelCase__ : int = True out_lines.append(UpperCamelCase_ ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset UpperCAmelCase__ : Union[str, Any] = f_name.replace('.py' , '' ) UpperCAmelCase__ : List[str] = os.path.join(UpperCamelCase_ , UpperCamelCase_ ) UpperCAmelCase__ : Dict = os.path.join(UpperCamelCase_ , UpperCamelCase_ ) os.makedirs(UpperCamelCase_ , exist_ok=UpperCamelCase_ ) self._logger.info(F'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(UpperCamelCase_ ) if needs_manual_update: with_manual_update.append(UpperCamelCase_ ) with open(UpperCamelCase_ , 'w' , encoding='utf-8' ) as f: f.writelines(UpperCamelCase_ ) self._logger.info(F'''Converted in {output_file}''' ) for utils_file in utils_files: try: UpperCAmelCase__ : Optional[Any] = os.path.basename(UpperCamelCase_ ) UpperCAmelCase__ : Any = imports_to_builder_map[f_name.replace('.py' , '' )] self._logger.info(F'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(UpperCamelCase_ , UpperCamelCase_ ) except KeyError: self._logger.error(F'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( F'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
110
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , a , ) super().__init__(*a , **a)
73
0
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING lowercase = logging.get_logger(__name__) @add_end_docstrings(A__ ) class UpperCamelCase_ ( A__ ): '''simple docstring''' def __init__( self , **a ) -> Dict: super().__init__(**a ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F'''The {self.__class__} is only available in PyTorch.''' ) self.check_model_type(a ) def _UpperCamelCase ( self , **a ) -> Tuple: snake_case_ = {} snake_case_ = {} snake_case_ = {} # preprocess args if "points_per_batch" in kwargs: snake_case_ = kwargs['points_per_batch'] if "points_per_crop" in kwargs: snake_case_ = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: snake_case_ = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: snake_case_ = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: snake_case_ = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: snake_case_ = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: snake_case_ = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: snake_case_ = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: snake_case_ = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: snake_case_ = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: snake_case_ = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: snake_case_ = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , a , *a , a=None , a=None , **a ) -> List[str]: return super().__call__(a , *a , num_workers=a , batch_size=a , **a ) def _UpperCamelCase ( self , a , a=64 , a = 0 , a = 5_12 / 15_00 , a = 32 , a = 1 , ) -> List[Any]: snake_case_ = load_image(a ) snake_case_ = self.image_processor.size['longest_edge'] snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.image_processor.generate_crop_boxes( a , a , a , a , a , a ) snake_case_ = self.image_processor(images=a , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": snake_case_ = self.get_inference_context() with inference_context(): snake_case_ = self._ensure_tensor_on_device(a , device=self.device ) snake_case_ = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) snake_case_ = image_embeddings snake_case_ = grid_points.shape[1] snake_case_ = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , a , a ): snake_case_ = grid_points[:, i : i + points_per_batch, :, :] snake_case_ = input_labels[:, i : i + points_per_batch] snake_case_ = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def _UpperCamelCase ( self , a , a=0.88 , a=0.95 , a=0 , a=1 , ) -> Tuple: snake_case_ = model_inputs.pop('input_boxes' ) snake_case_ = model_inputs.pop('is_last' ) snake_case_ = model_inputs.pop('original_sizes' ).tolist() snake_case_ = model_inputs.pop('reshaped_input_sizes' ).tolist() snake_case_ = self.model(**a ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks snake_case_ = model_outputs['pred_masks'] snake_case_ = self.image_processor.post_process_masks( a , a , a , a , binarize=a ) snake_case_ = model_outputs['iou_scores'] snake_case_ , snake_case_ , snake_case_ = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , a , a , a , a , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def _UpperCamelCase ( self , a , a=False , a=False , a=0.7 , ) -> Union[str, Any]: snake_case_ = [] snake_case_ = [] snake_case_ = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) snake_case_ = torch.cat(a ) snake_case_ = torch.cat(a ) snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.image_processor.post_process_for_mask_generation( a , a , a , a ) snake_case_ = defaultdict(a ) for output in model_outputs: for k, v in output.items(): extra[k].append(a ) snake_case_ = {} if output_rle_mask: snake_case_ = rle_mask if output_bboxes_mask: snake_case_ = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
198
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_tool('text-classification') self.tool.setup() SCREAMING_SNAKE_CASE = load_tool('text-classification' , remote=a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.remote_tool('That\'s quite cool' , ['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative']) self.assertEqual(a , 'positive')
73
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys a_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
480
import sys import turtle def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) my_pen.goto(vertexa[0] , vertexa[1]) if depth == 0: return triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) triangle(_UpperCAmelCase , get_mid(_UpperCAmelCase , _UpperCAmelCase) , get_mid(_UpperCAmelCase , _UpperCAmelCase) , depth - 1) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) a_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') a_ : str = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
73
0
from __future__ import annotations def _lowercase ( SCREAMING_SNAKE_CASE_ : List[str] ): """simple docstring""" UpperCamelCase = 2 UpperCamelCase = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase ) if n > 1: factors.append(_UpperCAmelCase ) return factors if __name__ == "__main__": import doctest doctest.testmod()
386
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ : Any = 'true' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=16): set_seed(42) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = RegressionDataset(length=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , batch_size=_UpperCAmelCase) model.to(accelerator.device) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return model, ddp_model, dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation') def tokenize_function(_UpperCAmelCase): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): if use_longest: return tokenizer.pad(_UpperCAmelCase , padding='longest' , return_tensors='pt') return tokenizer.pad(_UpperCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt') return DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=16) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=_UpperCAmelCase , split_batches=_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_dataloader(_UpperCAmelCase , not dispatch_batches) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(_UpperCAmelCase , _UpperCAmelCase) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target)) logits_and_targets.append((logit, target)) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCAmelCase) targs.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(_UpperCAmelCase), torch.cat(_UpperCAmelCase) return logits, targs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=82 , _UpperCAmelCase=False , _UpperCAmelCase=False , _UpperCAmelCase=16): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) assert ( len(_UpperCAmelCase) == num_samples ), F'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCAmelCase)}''' def lowerCamelCase__ (_UpperCAmelCase = False , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(_UpperCAmelCase , _UpperCAmelCase) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(_UpperCAmelCase) model.eval() for batch in dataloader: batch.to(_UpperCAmelCase) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) metric.add_batch(predictions=_UpperCAmelCase , references=batch['labels']) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references)) metric.add_batch(predictions=_UpperCAmelCase , references=_UpperCAmelCase) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key]), F'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''') test_mrpc(_UpperCAmelCase , _UpperCAmelCase) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**') for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=_UpperCAmelCase , dispatch_batches=_UpperCAmelCase) if accelerator.is_local_main_process: print(F'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''') test_torch_metrics(_UpperCAmelCase , 99) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**') SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(_UpperCAmelCase , 512) accelerator.state._reset_state() def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
0
import json import logging import os import sys from time import time from unittest.mock import patch from transformers.testing_utils import TestCasePlus, require_torch_tpu logging.basicConfig(level=logging.DEBUG) _lowerCamelCase : Any = logging.getLogger() def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Optional[int]: """simple docstring""" A__ = {} A__ = os.path.join(_UpperCAmelCase , '''all_results.json''' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase , '''r''' ) as f: A__ = json.load(_UpperCAmelCase ) else: raise ValueError(f"""can\'t find {path}""" ) return results _lowerCamelCase : Union[str, Any] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @require_torch_tpu class UpperCamelCase_ ( A__ ): '''simple docstring''' def SCREAMING_SNAKE_CASE ( self : int) ->List[Any]: '''simple docstring''' import xla_spawn A__ = self.get_auto_remove_tmp_dir() A__ = f""" ./examples/pytorch/text-classification/run_glue.py --num_cores=8 ./examples/pytorch/text-classification/run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --overwrite_output_dir --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --do_train --do_eval --debug tpu_metrics_debug --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --max_steps=10 --warmup_steps=2 --seed=42 --max_seq_length=128 """.split() with patch.object(UpperCAmelCase__ , '''argv''' , UpperCAmelCase__): A__ = time() xla_spawn.main() A__ = time() A__ = get_results(UpperCAmelCase__) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75) # Assert that the script takes less than 500 seconds to make sure it doesn't hang. self.assertLess(end - start , 500) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[Any]: '''simple docstring''' import xla_spawn A__ = '''\n ./tests/test_trainer_tpu.py\n --num_cores=8\n ./tests/test_trainer_tpu.py\n '''.split() with patch.object(UpperCAmelCase__ , '''argv''' , UpperCAmelCase__): xla_spawn.main()
87
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : List[str] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
73
0
"""simple docstring""" import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class __snake_case ( A__ , A__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ : List[Any] = IFPipeline lowerCAmelCase_ : List[Any] = TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''} lowerCAmelCase_ : Dict = TEXT_TO_IMAGE_BATCH_PARAMS lowerCAmelCase_ : List[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return self._get_dummy_components() def SCREAMING_SNAKE_CASE_ ( self :List[Any] , UpperCamelCase__ :Tuple , UpperCamelCase__ :Tuple=0 ): if str(UpperCamelCase__ ).startswith("mps" ): _a = torch.manual_seed(UpperCamelCase__ ) else: _a = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) _a = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): self._test_save_load_local() def SCREAMING_SNAKE_CASE_ ( self :Dict ): self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class __snake_case ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE_ ( self :Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # if _a = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0" , variant="fp16" , torch_dtype=torch.floataa ) _a = IFSuperResolutionPipeline.from_pretrained( "DeepFloyd/IF-II-L-v1.0" , variant="fp16" , torch_dtype=torch.floataa , text_encoder=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to("cuda" ) _a , _a = pipe_a.encode_prompt("anime turtle" , device="cuda" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() _a = None _a = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img _a = IFImgaImgPipeline(**pipe_a.components ) _a = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting _a = IFInpaintingPipeline(**pipe_a.components ) _a = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ ( self :int , UpperCamelCase__ :Union[str, Any] , UpperCamelCase__ :Any , UpperCamelCase__ :Dict , UpperCamelCase__ :Optional[int] ): # pipeline 1 _start_torch_memory_measurement() _a = torch.Generator(device="cpu" ).manual_seed(0 ) _a = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type="np" , ) _a = output.images[0] assert image.shape == (64, 64, 3) _a = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy" ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() _a = torch.Generator(device="cpu" ).manual_seed(0 ) _a = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) _a = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type="np" , ) _a = output.images[0] assert image.shape == (256, 256, 3) _a = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy" ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , UpperCamelCase__ :Tuple , UpperCamelCase__ :int , UpperCamelCase__ :Optional[int] , UpperCamelCase__ :List[Any] ): # pipeline 1 _start_torch_memory_measurement() _a = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) _a = torch.Generator(device="cpu" ).manual_seed(0 ) _a = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type="np" , ) _a = output.images[0] assert image.shape == (64, 64, 3) _a = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy" ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() _a = torch.Generator(device="cpu" ).manual_seed(0 ) _a = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) _a = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) _a = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type="np" , ) _a = output.images[0] assert image.shape == (256, 256, 3) _a = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy" ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , UpperCamelCase__ :List[str] , UpperCamelCase__ :Any , UpperCamelCase__ :List[str] , UpperCamelCase__ :Any ): # pipeline 1 _start_torch_memory_measurement() _a = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) _a = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) _a = torch.Generator(device="cpu" ).manual_seed(0 ) _a = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , num_inference_steps=2 , generator=UpperCamelCase__ , output_type="np" , ) _a = output.images[0] assert image.shape == (64, 64, 3) _a = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy" ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) # pipeline 2 _start_torch_memory_measurement() _a = torch.Generator(device="cpu" ).manual_seed(0 ) _a = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) _a = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCamelCase__ ) _a = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(UpperCamelCase__ ) _a = pipe_a( prompt_embeds=UpperCamelCase__ , negative_prompt_embeds=UpperCamelCase__ , image=UpperCamelCase__ , mask_image=UpperCamelCase__ , original_image=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=2 , output_type="np" , ) _a = output.images[0] assert image.shape == (256, 256, 3) _a = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _a = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy" ) assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ ) def __a ( ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
388
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path a_ : str = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def lowerCamelCase__ (_UpperCAmelCase=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=A__ ) ) class _snake_case ( A__ ): _lowercase : Optional[Any] = None _lowercase : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = dataset_module_factory(a , cache_dir=a) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=a) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=a , config_name=a , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=a).replace(os.sep , '/'), config.DATASET_INFO_FILENAME, ]) SCREAMING_SNAKE_CASE = cached_path(a , cache_dir=a) self.assertTrue(os.path.exists(a)) @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp('test_hf_gcp') / 'test_wikipedia_simple' SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE = builder_instance.as_dataset() assert ds @pytest.mark.integration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = dataset_module_factory('wikipedia' , cache_dir=_UpperCAmelCase) SCREAMING_SNAKE_CASE = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = builder_cls( cache_dir=_UpperCAmelCase , config_name='20220301.frr' , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert "train" in ds assert isinstance(ds['train'] , _UpperCAmelCase) assert next(iter(ds['train']))
73
0
'''simple docstring''' def _lowerCAmelCase (_lowercase ): """simple docstring""" if p < 2: raise ValueError("p should not be less than 2!" ) elif p == 2: return True a__ = 4 a__ = (1 << p) - 1 for _ in range(p - 2 ): a__ = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
331
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase) if n > 1: factors.append(_UpperCAmelCase) return factors if __name__ == "__main__": import doctest doctest.testmod()
73
0
"""simple docstring""" # using dfs for finding eulerian path traversal def _lowercase ( __snake_case ,__snake_case ,__snake_case ,__snake_case=None ) -> Union[str, Any]: __lowerCAmelCase : Tuple = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: __lowerCAmelCase , __lowerCAmelCase : Any = True, True __lowerCAmelCase : Any = dfs(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) return path def _lowercase ( __snake_case ,__snake_case ) -> Optional[int]: __lowerCAmelCase : Tuple = 0 __lowerCAmelCase : Tuple = -1 for i in range(_UpperCAmelCase ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 __lowerCAmelCase : int = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def _lowercase ( __snake_case ,__snake_case ) -> Union[str, Any]: __lowerCAmelCase : Optional[int] = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] __lowerCAmelCase , __lowerCAmelCase : Optional[int] = check_circuit_or_path(_UpperCAmelCase ,_UpperCAmelCase ) if check == 3: print("graph is not Eulerian" ) print("no path" ) return __lowerCAmelCase : List[Any] = 1 if check == 2: __lowerCAmelCase : int = odd_node print("graph has a Euler path" ) if check == 1: print("graph has a Euler cycle" ) __lowerCAmelCase : Optional[Any] = dfs(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) print(_UpperCAmelCase ) def _lowercase ( ) -> List[Any]: __lowerCAmelCase : List[str] = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} __lowerCAmelCase : Optional[int] = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} __lowerCAmelCase : Optional[Any] = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} __lowerCAmelCase : List[str] = {1: [2, 3], 2: [1, 3], 3: [1, 2]} __lowerCAmelCase : Union[str, Any] = { 1: [], 2: [] # all degree is zero } __lowerCAmelCase : int = 10 check_euler(_UpperCAmelCase ,_UpperCAmelCase ) check_euler(_UpperCAmelCase ,_UpperCAmelCase ) check_euler(_UpperCAmelCase ,_UpperCAmelCase ) check_euler(_UpperCAmelCase ,_UpperCAmelCase ) check_euler(_UpperCAmelCase ,_UpperCAmelCase ) if __name__ == "__main__": main()
293
import math import os import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = last_match_id if math.loga(_UpperCAmelCase).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE = '0' + lexicon[curr_key] SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) index += 1 SCREAMING_SNAKE_CASE = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.getsize(_UpperCAmelCase) SCREAMING_SNAKE_CASE = bin(_UpperCAmelCase)[2:] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append('10000000') else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = compress_data(_UpperCAmelCase) SCREAMING_SNAKE_CASE = add_file_length(_UpperCAmelCase , _UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
73
0