code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = [ ('''bert.bert''', '''visual_bert'''), ('''bert.cls''', '''cls'''), ('''bert.classifier''', '''cls'''), ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''), ('''position_embeddings_visual''', '''visual_position_embeddings'''), ('''projection''', '''visual_projection'''), ] UpperCAmelCase : Any = [ '''nlvr2_coco_pre_trained.th''', '''nlvr2_fine_tuned.th''', '''nlvr2_pre_trained.th''', '''vcr_coco_pre_train.th''', '''vcr_fine_tune.th''', '''vcr_pre_train.th''', '''vqa_coco_pre_trained.th''', '''vqa_fine_tuned.th''', '''vqa_pre_trained.th''', ] def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : List[str] = torch.load(a , map_location='cpu' ) return sd def _SCREAMING_SNAKE_CASE ( a , a , a=rename_keys_prefix ) -> int: __A : Any = OrderedDict() __A : Any = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __A : List[Any] = key for name_pair in rename_keys_prefix: __A : Union[str, Any] = new_key.replace(name_pair[0] , name_pair[1] ) __A : str = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __A : Union[str, Any] = new_d['cls.predictions.bias'] return new_d @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F"""The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.""" # Get Config if "pre" in checkpoint_path: __A : List[Any] = 'pretraining' if "vcr" in checkpoint_path: __A : List[Any] = {'visual_embedding_dim': 5_12} elif "vqa_advanced" in checkpoint_path: __A : Optional[Any] = {'visual_embedding_dim': 20_48} elif "vqa" in checkpoint_path: __A : List[str] = {'visual_embedding_dim': 20_48} elif "nlvr" in checkpoint_path: __A : Optional[int] = {'visual_embedding_dim': 10_24} else: raise NotImplementedError(F"""No implementation found for `{checkpoint_path}`.""" ) else: if "vcr" in checkpoint_path: __A : Optional[Any] = {'visual_embedding_dim': 5_12} __A : int = 'multichoice' elif "vqa_advanced" in checkpoint_path: __A : Dict = {'visual_embedding_dim': 20_48} __A : int = 'vqa_advanced' elif "vqa" in checkpoint_path: __A : Any = {'visual_embedding_dim': 20_48, 'num_labels': 31_29} __A : Any = 'vqa' elif "nlvr" in checkpoint_path: __A : Any = { 'visual_embedding_dim': 10_24, 'num_labels': 2, } __A : List[str] = 'nlvr' __A : Dict = VisualBertConfig(**a ) # Load State Dict __A : Tuple = load_state_dict(a ) __A : Union[str, Any] = get_new_dict(a , a ) if model_type == "pretraining": __A : Optional[int] = VisualBertForPreTraining(a ) elif model_type == "vqa": __A : Any = VisualBertForQuestionAnswering(a ) elif model_type == "nlvr": __A : Tuple = VisualBertForVisualReasoning(a ) elif model_type == "multichoice": __A : Union[str, Any] = VisualBertForMultipleChoice(a ) model.load_state_dict(a ) # Save Checkpoints Path(a ).mkdir(exist_ok=a ) model.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''') UpperCAmelCase : Dict = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
77
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _A( nn.Module ): """simple docstring""" def __init__( self ): super().__init__() __A : List[str] = nn.Linear(3 , 4 ) __A : Optional[Any] = nn.BatchNormad(4 ) __A : List[Any] = nn.Linear(4 , 5 ) def UpperCAmelCase_ ( self , _A ): return self.lineara(self.batchnorm(self.lineara(_A ) ) ) class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Dict = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , model.state_dict() ) __A : str = os.path.join(_A , 'index.json' ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: __A : Optional[int] = os.path.join(_A , F"""{key}.dat""" ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on the fact weights are properly loaded def UpperCAmelCase_ ( self ): __A : Dict = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: __A : Tuple = torch.randn(2 , 3 , dtype=_A ) with TemporaryDirectory() as tmp_dir: __A : int = offload_weight(_A , 'weight' , _A , {} ) __A : Union[str, Any] = os.path.join(_A , 'weight.dat' ) self.assertTrue(os.path.isfile(_A ) ) self.assertDictEqual(_A , {'weight': {'shape': [2, 3], 'dtype': str(_A ).split('.' )[1]}} ) __A : List[str] = load_offloaded_weight(_A , index['weight'] ) self.assertTrue(torch.equal(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : int = ModelForTest() __A : Union[str, Any] = model.state_dict() __A : Optional[Any] = {k: v for k, v in state_dict.items() if 'linear2' not in k} __A : str = {k: v for k, v in state_dict.items() if 'linear2' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : List[str] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) __A : Union[str, Any] = {k: v for k, v in state_dict.items() if 'weight' in k} __A : List[Any] = {k: v for k, v in state_dict.items() if 'weight' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : Optional[int] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) # Duplicates are removed __A : str = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) def UpperCAmelCase_ ( self ): __A : Dict = {'a.1': 0, 'a.10': 1, 'a.2': 2} __A : str = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1': 0, 'a.2': 2} ) __A : Optional[Any] = {'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2} __A : Any = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1.a': 0, 'a.2.a': 2} )
77
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class _A( snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = StableDiffusionPanoramaPipeline UpperCamelCase : Dict = TEXT_TO_IMAGE_PARAMS UpperCamelCase : List[str] = TEXT_TO_IMAGE_BATCH_PARAMS UpperCamelCase : Optional[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS UpperCamelCase : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Union[str, Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) __A : Union[str, Any] = DDIMScheduler() torch.manual_seed(0 ) __A : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) __A : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) __A : Tuple = CLIPTextModel(_A ) __A : int = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __A : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): __A : int = torch.manual_seed(_A ) __A : Union[str, Any] = { 'prompt': 'a photo of the dolomites', 'generator': generator, # Setting height and width to None to prevent OOMs on CPU. 'height': None, 'width': None, 'num_inference_steps': 1, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def UpperCAmelCase_ ( self ): __A : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __A : Tuple = self.get_dummy_components() __A : Optional[Any] = StableDiffusionPanoramaPipeline(**_A ) __A : Dict = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) __A : Dict = self.get_dummy_inputs(_A ) __A : str = sd_pipe(**_A ).images __A : int = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __A : Tuple = np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCAmelCase_ ( self ): super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.2_5e-3 ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator __A : Optional[Any] = self.get_dummy_components() __A : List[str] = StableDiffusionPanoramaPipeline(**_A ) __A : Optional[Any] = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) __A : Any = self.get_dummy_inputs(_A ) __A : str = 'french fries' __A : List[str] = sd_pipe(**_A , negative_prompt=_A ) __A : List[str] = output.images __A : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __A : List[Any] = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): __A : str = 'cpu' # ensure determinism for the device-dependent torch.Generator __A : Tuple = self.get_dummy_components() __A : str = StableDiffusionPanoramaPipeline(**_A ) __A : Dict = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) __A : List[Any] = self.get_dummy_inputs(_A ) __A : str = sd_pipe(**_A , view_batch_size=2 ) __A : int = output.images __A : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __A : str = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): __A : List[str] = 'cpu' # ensure determinism for the device-dependent torch.Generator __A : Dict = self.get_dummy_components() __A : Tuple = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' ) __A : Optional[Any] = StableDiffusionPanoramaPipeline(**_A ) __A : Dict = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) __A : List[Any] = self.get_dummy_inputs(_A ) __A : List[Any] = sd_pipe(**_A ).images __A : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __A : List[str] = np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): __A : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator __A : int = self.get_dummy_components() __A : Union[str, Any] = PNDMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' , skip_prk_steps=_A ) __A : List[Any] = StableDiffusionPanoramaPipeline(**_A ) __A : Optional[int] = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) __A : Tuple = self.get_dummy_inputs(_A ) __A : List[Any] = sd_pipe(**_A ).images __A : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __A : Tuple = np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self , _A=0 ): __A : int = torch.manual_seed(_A ) __A : Optional[Any] = { 'prompt': 'a photo of the dolomites', 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def UpperCAmelCase_ ( self ): __A : List[Any] = 'stabilityai/stable-diffusion-2-base' __A : Union[str, Any] = DDIMScheduler.from_pretrained(_A , subfolder='scheduler' ) __A : Optional[int] = StableDiffusionPanoramaPipeline.from_pretrained(_A , scheduler=_A , safety_checker=_A ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() __A : Any = self.get_inputs() __A : Any = pipe(**_A ).images __A : int = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) __A : Optional[Any] = np.array( [ 0.3_6_9_6_8_3_9_2, 0.2_7_0_2_5_3_7_2, 0.3_2_4_4_6_7_6_6, 0.2_8_3_7_9_3_8_7, 0.3_6_3_6_3_2_7_4, 0.3_0_7_3_3_3_4_7, 0.2_7_1_0_0_0_2_7, 0.2_7_0_5_4_1_2_5, 0.2_5_5_3_6_0_9_6, ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): __A : Dict = StableDiffusionPanoramaPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-base' , safety_checker=_A ) __A : List[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() __A : List[Any] = self.get_inputs() __A : Union[str, Any] = pipe(**_A ).images __A : int = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) __A : str = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def UpperCAmelCase_ ( self ): __A : Any = 0 def callback_fn(_A , _A , _A ) -> None: __A : Dict = True nonlocal number_of_steps number_of_steps += 1 if step == 1: __A : int = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) __A : List[str] = latents[0, -3:, -3:, -1] __A : str = np.array( [ 0.1_8_6_8_1_8_6_9, 0.3_3_9_0_7_8_1_6, 0.5_3_6_1_2_7_6, 0.1_4_4_3_2_8_6_5, -0.0_2_8_5_6_6_1_1, -0.7_3_9_4_1_1_2_3, 0.2_3_3_9_7_9_8_7, 0.4_7_3_2_2_6_8_2, -0.3_7_8_2_3_1_6_4, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: __A : Tuple = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) __A : Dict = latents[0, -3:, -3:, -1] __A : Union[str, Any] = np.array( [ 0.1_8_5_3_9_6_4_5, 0.3_3_9_8_7_2_4_8, 0.5_3_7_8_5_5_9, 0.1_4_4_3_7_1_4_2, -0.0_2_4_5_5_2_6_1, -0.7_3_3_8_3_1_7, 0.2_3_9_9_0_7_5_5, 0.4_7_3_5_6_2_7_2, -0.3_7_8_6_5_0_5, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 __A : Optional[int] = False __A : Optional[int] = 'stabilityai/stable-diffusion-2-base' __A : Optional[Any] = DDIMScheduler.from_pretrained(_A , subfolder='scheduler' ) __A : List[str] = StableDiffusionPanoramaPipeline.from_pretrained(_A , scheduler=_A , safety_checker=_A ) __A : Optional[Any] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() __A : int = self.get_inputs() pipe(**_A , callback=_A , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def UpperCAmelCase_ ( self ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __A : Union[str, Any] = 'stabilityai/stable-diffusion-2-base' __A : Any = DDIMScheduler.from_pretrained(_A , subfolder='scheduler' ) __A : str = StableDiffusionPanoramaPipeline.from_pretrained(_A , scheduler=_A , safety_checker=_A ) __A : Dict = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __A : List[str] = self.get_inputs() __A : Dict = pipe(**_A ) __A : Optional[Any] = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
77
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): __A : Any = data def __iter__( self ): for element in self.data: yield element def _SCREAMING_SNAKE_CASE ( a=True ) -> Any: __A : List[Any] = Accelerator(even_batches=a ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str: if iterable: __A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) ) else: __A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) ) __A : Optional[Any] = DataLoader(a , batch_size=a ) __A : Optional[int] = accelerator.prepare(a ) return dl def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]: __A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a ) __A : Tuple = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : int = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : str = create_accelerator(even_batches=a ) verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _SCREAMING_SNAKE_CASE ( ) -> str: __A : Optional[Any] = create_accelerator(even_batches=a ) __A : str = torch.nn.Linear(1 , 1 ) __A : Optional[int] = accelerator.prepare(a ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : str = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(a ): __A : Dict = ddp_model(batch[0].float() ) __A : List[str] = output.sum() loss.backward() batch_idxs.append(a ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , a ) assert "only supported for multi-GPU" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : int = True __A : Union[str, Any] = False __A : Optional[int] = create_accelerator(even_batches=a ) __A : int = torch.nn.Linear(1 , 1 ) __A : List[Any] = accelerator.prepare(a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : List[str] = train_dl.batch_sampler.even_batches __A : Dict = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Any = True __A : List[Any] = False __A : Tuple = create_accelerator(even_batches=a ) __A : List[str] = torch.nn.Linear(1 , 1 ) __A : Optional[Any] = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('ignore' ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : Tuple = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Any = create_accelerator() __A : Union[str, Any] = torch.nn.Linear(1 , 1 ) __A : str = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): pass assert issubclass(w[-1].category , a ) assert "only supported for map-style datasets" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : str = create_accelerator() accelerator.print('Test that even_batches variable ensures uniform batches across processes' ) test_default_ensures_even_batch_sizes() accelerator.print('Run tests with even_batches disabled' ) test_can_disable_even_batches() accelerator.print('Test joining uneven inputs' ) test_can_join_uneven_inputs() accelerator.print('Test overriding even_batches when joining uneven inputs' ) test_join_can_override_even_batches() accelerator.print('Test overriding even_batches for mixed dataloader types' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('Test join with non DDP distributed raises warning' ) __A : int = accelerator.state.distributed_type __A : Tuple = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(a ) __A : str = original_state if __name__ == "__main__": main()
77
1
import unittest import torch from torch import nn from diffusers.models.activations import get_activation class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Any = get_activation('swish' ) self.assertIsInstance(_A , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def UpperCAmelCase_ ( self ): __A : Optional[int] = get_activation('silu' ) self.assertIsInstance(_A , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def UpperCAmelCase_ ( self ): __A : str = get_activation('mish' ) self.assertIsInstance(_A , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def UpperCAmelCase_ ( self ): __A : str = get_activation('gelu' ) self.assertIsInstance(_A , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
77
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : str = { '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''', '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''', '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''', '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''', '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''', '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''', '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''', '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''', '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''', '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''', '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''', '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = '''codegen''' UpperCamelCase : List[str] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ): __A : Any = vocab_size __A : Tuple = n_ctx __A : Union[str, Any] = n_positions __A : Optional[Any] = n_embd __A : Any = n_layer __A : Dict = n_head __A : Union[str, Any] = n_inner __A : List[Any] = rotary_dim __A : str = activation_function __A : Any = resid_pdrop __A : Tuple = embd_pdrop __A : Tuple = attn_pdrop __A : Union[str, Any] = layer_norm_epsilon __A : str = initializer_range __A : Optional[Any] = use_cache __A : Union[str, Any] = bos_token_id __A : Tuple = eos_token_id super().__init__( bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A ) class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A = "default" , _A = None , _A = False , ): super().__init__(_A , task=_A , patching_specs=_A , use_past=_A ) if not getattr(self._config , 'pad_token_id' , _A ): # TODO: how to do that better? __A : Dict = 0 @property def UpperCAmelCase_ ( self ): __A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) __A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'} else: __A : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase_ ( self ): return self._config.n_layer @property def UpperCAmelCase_ ( self ): return self._config.n_head def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Any = super(_A , self ).generate_dummy_inputs( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) # We need to order the input in the way they appears in the forward() __A : str = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __A , __A : Any = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Any = seqlen + 2 __A : List[str] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __A : Optional[Any] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] __A : Tuple = common_inputs['attention_mask'] if self.use_past: __A : str = ordered_inputs['attention_mask'].dtype __A : List[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self ): return 13
77
1
import math def _SCREAMING_SNAKE_CASE ( a , a = 0 , a = 0 ) -> list: __A : Union[str, Any] = end or len(a ) for i in range(a , a ): __A : Union[str, Any] = i __A : List[Any] = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: __A : Dict = array[temp_index - 1] temp_index -= 1 __A : int = temp_index_value return array def _SCREAMING_SNAKE_CASE ( a , a , a ) -> None: # Max Heap __A : Tuple = index __A : Union[str, Any] = 2 * index + 1 # Left Node __A : Optional[Any] = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: __A : Any = left_index if right_index < heap_size and array[largest] < array[right_index]: __A : str = right_index if largest != index: __A , __A : Optional[Any] = array[largest], array[index] heapify(a , a , a ) def _SCREAMING_SNAKE_CASE ( a ) -> list: __A : str = len(a ) for i in range(n // 2 , -1 , -1 ): heapify(a , a , a ) for i in range(n - 1 , 0 , -1 ): __A , __A : Optional[int] = array[0], array[i] heapify(a , 0 , a ) return array def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> int: if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> int: __A : List[str] = low __A : Union[str, Any] = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i __A , __A : Optional[int] = array[j], array[i] i += 1 def _SCREAMING_SNAKE_CASE ( a ) -> list: if len(a ) == 0: return array __A : Optional[int] = 2 * math.ceil(math.loga(len(a ) ) ) __A : Dict = 16 return intro_sort(a , 0 , len(a ) , a , a ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> list: while end - start > size_threshold: if max_depth == 0: return heap_sort(a ) max_depth -= 1 __A : List[str] = median_of_a(a , a , start + ((end - start) // 2) + 1 , end - 1 ) __A : Any = partition(a , a , a , a ) intro_sort(a , a , a , a , a ) __A : Tuple = p return insertion_sort(a , a , a ) if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase : Union[str, Any] = input('''Enter numbers separated by a comma : ''').strip() UpperCAmelCase : Dict = [float(item) for item in user_input.split(''',''')] print(sort(unsorted))
77
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase : List[Any] = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _A , ) super().__init__(*_A , **_A )
77
1
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 UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Any = { '''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 _A( snake_case__ ): """simple docstring""" UpperCamelCase : Any = '''gpt_neo''' UpperCamelCase : Union[str, Any] = ['''past_key_values'''] UpperCamelCase : Any = {'''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self , _A=50257 , _A=2048 , _A=2048 , _A=24 , _A=[[["global", "local"], 12]] , _A=16 , _A=None , _A=256 , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=0.1 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , **_A , ): __A : int = vocab_size __A : Union[str, Any] = max_position_embeddings __A : List[str] = hidden_size __A : Union[str, Any] = num_layers __A : str = num_heads __A : Optional[int] = intermediate_size __A : Dict = window_size __A : Optional[int] = activation_function __A : int = resid_dropout __A : List[Any] = embed_dropout __A : List[Any] = attention_dropout __A : str = classifier_dropout __A : Any = layer_norm_epsilon __A : Tuple = initializer_range __A : Any = use_cache __A : Optional[int] = bos_token_id __A : Any = eos_token_id __A : str = attention_types __A : Optional[int] = self.expand_attention_types_params(_A ) 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=_A , eos_token_id=_A , **_A ) @staticmethod def UpperCAmelCase_ ( _A ): __A : List[str] = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Optional[Any]: import torch __A : Optional[int] = input.size() __A : List[Any] = len(a ) __A : Tuple = shape[dimension] __A : str = torch.arange(0 , a , a ) __A : Union[str, Any] = torch.div(sizedim - size , a , rounding_mode='floor' ) + 1 __A : Tuple = torch.arange(a ) + low_indices[:min_length][:, None] __A : List[str] = [slice(a )] * rank __A : Tuple = indices __A : int = input[s] __A : List[str] = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(a ) def _SCREAMING_SNAKE_CASE ( a , a ) -> List[Any]: import torch __A : Dict = torch.arange(1 , a ) __A : Optional[int] = torch.remainder(a , a ) __A : str = remainders == 0 __A : Union[str, Any] = candidates[divisor_indices] __A : str = torch.max(a ) return largest_divisor, torch.div(a , a , rounding_mode='floor' ) class _A( snake_case__ ): """simple docstring""" @property def UpperCAmelCase_ ( self ): __A : Dict = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) __A : Optional[Any] = {0: 'batch', 1: 'past_sequence + sequence'} else: __A : str = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase_ ( self ): return self._config.num_heads def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Tuple = super(_A , self ).generate_dummy_inputs( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) # We need to order the input in the way they appears in the forward() __A : Optional[int] = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __A , __A : Optional[int] = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Tuple = seqlen + 2 __A : str = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __A : Any = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] __A : List[str] = common_inputs['attention_mask'] if self.use_past: __A : List[Any] = ordered_inputs['attention_mask'].dtype __A : Optional[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self ): return 13
77
import glob import os import random from string import ascii_lowercase, digits import cva UpperCAmelCase : Dict = '''''' UpperCAmelCase : Union[str, Any] = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal) def _SCREAMING_SNAKE_CASE ( ) -> None: __A , __A : List[Any] = get_dataset(a , a ) print('Processing...' ) __A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a ) for index, image in enumerate(a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __A : Optional[int] = random_chars(32 ) __A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] __A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Success {index+1}/{len(a )} with {file_name}""" ) __A : int = [] for anno in new_annos[index]: __A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(a ) with open(F"""/{file_root}.txt""" , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]: __A : int = [] __A : List[Any] = [] for label_file in glob.glob(os.path.join(a , '*.txt' ) ): __A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(a ) as in_file: __A : Tuple = in_file.readlines() __A : Dict = os.path.join(a , F"""{label_name}.jpg""" ) __A : Dict = [] for obj_list in obj_lists: __A : int = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(a ) labels.append(a ) return img_paths, labels def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]: __A : int = [] __A : Optional[Any] = [] __A : Dict = [] for idx in range(len(a ) ): __A : Dict = [] __A : Optional[Any] = img_list[idx] path_list.append(a ) __A : Union[str, Any] = anno_list[idx] __A : Optional[Any] = cva.imread(a ) if flip_type == 1: __A : Any = cva.flip(a , a ) for bbox in img_annos: __A : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __A : Union[str, Any] = cva.flip(a , a ) for bbox in img_annos: __A : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(a ) new_imgs_list.append(a ) return new_imgs_list, new_annos_lists, path_list def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __A : List[Any] = ascii_lowercase + digits return "".join(random.choice(a ) for _ in range(a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
77
1
import requests UpperCAmelCase : Dict = '''https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=''' def _SCREAMING_SNAKE_CASE ( a ) -> None: # fetching a list of articles in json format __A : Any = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(F"""{i}.) {article["title"]}""" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key='''<Your BBC News API key goes here>''')
77
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A: """simple docstring""" def __init__( self , _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.0_2 , _A=3 , _A=4 , _A=None , ): __A : Union[str, Any] = parent __A : List[str] = batch_size __A : Optional[int] = seq_length __A : List[Any] = is_training __A : Optional[Any] = use_input_mask __A : List[Any] = use_token_type_ids __A : Optional[Any] = use_labels __A : List[str] = vocab_size __A : Optional[int] = hidden_size __A : List[Any] = num_hidden_layers __A : int = num_attention_heads __A : Dict = intermediate_size __A : Any = hidden_act __A : Union[str, Any] = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : Optional[int] = max_position_embeddings __A : Dict = type_vocab_size __A : Any = type_sequence_label_size __A : Dict = initializer_range __A : str = num_labels __A : Union[str, Any] = num_choices __A : str = scope def UpperCAmelCase_ ( self ): __A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : Optional[Any] = None if self.use_input_mask: __A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __A : Dict = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = None __A : List[Any] = None __A : List[Any] = None if self.use_labels: __A : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __A : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[str] = LlamaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A , attention_mask=_A ) __A : Any = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Dict = True __A : int = LlamaModel(_A ) model.to(_A ) model.eval() __A : str = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __A : int = model( _A , attention_mask=_A , encoder_hidden_states=_A , ) __A : List[Any] = model(_A , attention_mask=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Optional[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : int = True __A : List[Any] = True __A : List[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() # first forward pass __A : Optional[Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , ) __A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __A : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) __A : str = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __A : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : str = torch.cat([input_mask, next_mask] , dim=-1 ) __A : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['hidden_states'][0] __A : Union[str, Any] = 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 __A : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() __A : Tuple = 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 UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Tuple = config_and_inputs __A : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () UpperCamelCase : Optional[Any] = (LlamaForCausalLM,) if is_torch_available() else () UpperCamelCase : Optional[Any] = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False def UpperCAmelCase_ ( self ): __A : List[Any] = LlamaModelTester(self ) __A : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : int = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() __A : str = 3 __A : Optional[int] = input_dict['input_ids'] __A : int = input_ids.ne(1 ).to(_A ) __A : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Union[str, Any] = 3 __A : Tuple = 'single_label_classification' __A : Union[str, Any] = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[int] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Any = 3 __A : int = 'multi_label_classification' __A : int = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __A : List[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def UpperCAmelCase_ ( self ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def UpperCAmelCase_ ( self , _A ): __A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Dict = ids_tensor([1, 10] , config.vocab_size ) __A : Union[str, Any] = 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 __A : List[Any] = LlamaModel(_A ) original_model.to(_A ) original_model.eval() __A : Dict = original_model(_A ).last_hidden_state __A : int = original_model(_A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : int = {'type': scaling_type, 'factor': 1_0.0} __A : str = LlamaModel(_A ) scaled_model.to(_A ) scaled_model.eval() __A : Dict = scaled_model(_A ).last_hidden_state __A : str = 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 ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) __A : Union[str, Any] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __A : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[str] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) __A : int = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) __A : Optional[int] = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : Optional[Any] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) __A : List[Any] = model(torch.tensor(_A ) ) __A : Tuple = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # fmt: off __A : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' __A : List[str] = 'Simply put, the theory of relativity states that ' __A : Union[str, Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) __A : List[str] = tokenizer.encode(_A , return_tensors='pt' ) __A : Tuple = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=_A ) # greedy generation outputs __A : Union[str, Any] = model.generate(_A , max_new_tokens=64 , top_p=_A , temperature=1 , do_sample=_A ) __A : List[str] = tokenizer.decode(generated_ids[0] , skip_special_tokens=_A ) self.assertEqual(_A , _A )
77
1
def _SCREAMING_SNAKE_CASE ( a , a ) -> int: if len(a ) != len(a ): raise ValueError('String lengths must match!' ) __A : Tuple = 0 for chara, chara in zip(a , a ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
77
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
1
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ProphetNetTokenizer UpperCamelCase : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() __A : Any = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = 'UNwant\u00E9d,running' __A : List[str] = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class(self.vocab_file ) __A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase_ ( self ): __A : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCAmelCase_ ( self ): __A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __A : Optional[int] = {} for i, token in enumerate(_A ): __A : Tuple = i __A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __A : str = tokenizer(_A , padding=_A , return_tensors='pt' ) self.assertIsInstance(_A , _A ) __A : List[str] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A ) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A ) __A : str = tokenizer.build_inputs_with_special_tokens(_A ) __A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
77
import numpy as np from PIL import Image def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : Union[str, Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : List[Any] = 0 __A : Optional[Any] = 0 __A : List[Any] = 0 __A : Dict = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __A : Tuple = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : List[str] = 0 __A : Union[str, Any] = 0 return updated_arr def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : List[Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : Dict = 0 __A : str = 0 __A : Tuple = 0 __A : Optional[int] = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __A : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : Dict = 0 __A : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image UpperCAmelCase : int = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
77
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class _A: """simple docstring""" def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=True , _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.0_2 , _A=3 , _A=4 , _A=None , ): __A : List[str] = parent __A : Optional[Any] = batch_size __A : Any = seq_length __A : int = is_training __A : Dict = use_token_type_ids __A : Dict = use_labels __A : Dict = vocab_size __A : List[Any] = hidden_size __A : Optional[Any] = num_hidden_layers __A : Dict = num_attention_heads __A : Optional[int] = intermediate_size __A : List[Any] = hidden_act __A : str = hidden_dropout_prob __A : Optional[Any] = attention_probs_dropout_prob __A : List[str] = max_position_embeddings __A : List[str] = type_vocab_size __A : Union[str, Any] = type_sequence_label_size __A : Union[str, Any] = initializer_range __A : Union[str, Any] = num_labels __A : Tuple = num_choices __A : Union[str, Any] = scope __A : List[Any] = self.vocab_size - 1 def UpperCAmelCase_ ( self ): __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : Any = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : str = None __A : Union[str, Any] = None __A : Tuple = None if self.use_labels: __A : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) __A : Tuple = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) __A : Dict = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , *_A ): __A : Any = OpenAIGPTModel(config=_A ) model.to(_A ) model.eval() __A : Optional[Any] = model(_A , token_type_ids=_A , head_mask=_A ) __A : Tuple = model(_A , token_type_ids=_A ) __A : Optional[Any] = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , *_A ): __A : Dict = OpenAIGPTLMHeadModel(_A ) model.to(_A ) model.eval() __A : Union[str, Any] = model(_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , *_A ): __A : Optional[Any] = OpenAIGPTDoubleHeadsModel(_A ) model.to(_A ) model.eval() __A : Optional[Any] = model(_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , *_A ): __A : List[str] = self.num_labels __A : Any = OpenAIGPTForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Dict = model(_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self ): __A : List[str] = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Optional[Any] = config_and_inputs __A : int = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask, } return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) UpperCamelCase : Optional[int] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly UpperCamelCase : str = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def UpperCAmelCase_ ( self , _A , _A , _A=False ): __A : int = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": __A : Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=_A , ) __A : Union[str, Any] = inputs_dict['labels'] __A : Tuple = inputs_dict['labels'] __A : List[str] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=_A , ) __A : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_A ) return inputs_dict def UpperCAmelCase_ ( self ): __A : int = OpenAIGPTModelTester(self ) __A : Union[str, Any] = ConfigTester(self , config_class=_A , n_embd=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*_A ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*_A ) def UpperCAmelCase_ ( self ): __A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_A ) @slow def UpperCAmelCase_ ( self ): for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A : Optional[int] = OpenAIGPTModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ ( self ): __A : str = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt' ) model.to(_A ) __A : Dict = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=_A ) # the president is __A : int = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 40477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the __A : Union[str, Any] = model.generate(_A , do_sample=_A ) self.assertListEqual(output_ids[0].tolist() , _A )
77
from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float: __A : Any = x_start __A : List[str] = fnc(a ) __A : Optional[Any] = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area __A : Any = (x_end - x_start) / steps + xa __A : List[str] = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __A : Any = xa __A : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( a ) -> int: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') UpperCAmelCase : Tuple = 10 while i <= 10_00_00: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
77
1
from __future__ import annotations UpperCAmelCase : Tuple = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] UpperCAmelCase : List[Any] = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def _SCREAMING_SNAKE_CASE ( a ) -> list[float]: __A : Any = [] __A : int = len(a ) for i in range(a ): __A : float = -1 for j in range(i + 1 , a ): if arr[i] < arr[j]: __A : Optional[Any] = arr[j] break result.append(a ) return result def _SCREAMING_SNAKE_CASE ( a ) -> list[float]: __A : List[Any] = [] for i, outer in enumerate(a ): __A : float = -1 for inner in arr[i + 1 :]: if outer < inner: __A : Optional[int] = inner break result.append(a ) return result def _SCREAMING_SNAKE_CASE ( a ) -> list[float]: __A : Tuple = len(a ) __A : list[float] = [] __A : list[float] = [-1] * arr_size for index in reversed(range(a ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: __A : int = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) UpperCAmelCase : Optional[int] = ( '''from __main__ import arr, next_greatest_element_slow, ''' '''next_greatest_element_fast, next_greatest_element''' ) print( '''next_greatest_element_slow():''', timeit('''next_greatest_element_slow(arr)''', setup=setup), ) print( '''next_greatest_element_fast():''', timeit('''next_greatest_element_fast(arr)''', setup=setup), ) print( ''' next_greatest_element():''', timeit('''next_greatest_element(arr)''', setup=setup), )
77
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def _SCREAMING_SNAKE_CASE ( ) -> None: print('Making key files...' ) make_key_files('rsa' , 10_24 ) print('Key files generation successful.' ) def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]: print('Generating prime p...' ) __A : Optional[Any] = rabinMiller.generate_large_prime(a ) print('Generating prime q...' ) __A : Union[str, Any] = rabinMiller.generate_large_prime(a ) __A : Tuple = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...' ) while True: __A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1: break print('Calculating d that is mod inverse of e...' ) __A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) ) __A : Dict = (n, e) __A : Dict = (n, d) return (public_key, private_key) def _SCREAMING_SNAKE_CASE ( a , a ) -> None: if os.path.exists(F"""{name}_pubkey.txt""" ) or os.path.exists(F"""{name}_privkey.txt""" ): print('\nWARNING:' ) print( F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n""" 'Use a different name or delete these files and re-run this program.' ) sys.exit() __A , __A : Optional[int] = generate_key(a ) print(F"""\nWriting public key to file {name}_pubkey.txt...""" ) with open(F"""{name}_pubkey.txt""" , 'w' ) as out_file: out_file.write(F"""{key_size},{public_key[0]},{public_key[1]}""" ) print(F"""Writing private key to file {name}_privkey.txt...""" ) with open(F"""{name}_privkey.txt""" , 'w' ) as out_file: out_file.write(F"""{key_size},{private_key[0]},{private_key[1]}""" ) if __name__ == "__main__": main()
77
1
def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , a ) -> List[Any]: if index == r: for j in range(a ): print(data[j] , end=' ' ) print(' ' ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location __A : List[str] = arr[i] combination_util(a , a , a , index + 1 , a , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(a , a , a , a , a , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]: # A temporary array to store all combination one by one __A : int = [0] * r # Print all combination using temporary array 'data[]' combination_util(a , a , a , 0 , a , 0 ) if __name__ == "__main__": # Driver code to check the function above UpperCAmelCase : Any = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
77
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ProphetNetTokenizer UpperCamelCase : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() __A : Any = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = 'UNwant\u00E9d,running' __A : List[str] = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class(self.vocab_file ) __A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase_ ( self ): __A : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCAmelCase_ ( self ): __A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __A : Optional[int] = {} for i, token in enumerate(_A ): __A : Tuple = i __A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __A : str = tokenizer(_A , padding=_A , return_tensors='pt' ) self.assertIsInstance(_A , _A ) __A : List[str] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A ) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A ) __A : str = tokenizer.build_inputs_with_special_tokens(_A ) __A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
77
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: UpperCAmelCase : List[Any] = None UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase : List[str] = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : str = { '''vocab_file''': { '''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model''', '''google/bigbird-roberta-large''': ( '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model''' ), '''google/bigbird-base-trivia-itc''': ( '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model''' ), }, '''tokenizer_file''': { '''google/bigbird-roberta-base''': ( '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json''' ), '''google/bigbird-roberta-large''': ( '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json''' ), '''google/bigbird-base-trivia-itc''': ( '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Any = { '''google/bigbird-roberta-base''': 40_96, '''google/bigbird-roberta-large''': 40_96, '''google/bigbird-base-trivia-itc''': 40_96, } UpperCAmelCase : Tuple = '''▁''' class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Optional[Any] = BigBirdTokenizer UpperCamelCase : Dict = ['''input_ids''', '''attention_mask'''] UpperCamelCase : List[int] = [] def __init__( self , _A=None , _A=None , _A="<unk>" , _A="<s>" , _A="</s>" , _A="<pad>" , _A="[SEP]" , _A="[MASK]" , _A="[CLS]" , **_A , ): __A : Optional[Any] = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else bos_token __A : Tuple = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else eos_token __A : Optional[int] = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else unk_token __A : Any = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else pad_token __A : Optional[Any] = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else cls_token __A : Dict = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else sep_token # Mask token behave like a normal word, i.e. include the space before it __A : int = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else mask_token super().__init__( _A , tokenizer_file=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , **_A , ) __A : int = vocab_file __A : str = False if not self.vocab_file else True def UpperCAmelCase_ ( self , _A , _A = None ): __A : List[str] = [self.sep_token_id] __A : List[Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCAmelCase_ ( self , _A , _A = None , _A = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(_A )) + [1] return [1] + ([0] * len(_A )) + [1] + ([0] * len(_A )) + [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[int] = [self.sep_token_id] __A : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(_A ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __A : Any = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ): copyfile(self.vocab_file , _A ) return (out_vocab_file,)
77
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Optional[int] = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } UpperCAmelCase : List[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = BertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : Any = getattr(_A , normalizer_state.pop('type' ) ) __A : Union[str, Any] = do_lower_case __A : Optional[int] = strip_accents __A : List[Any] = tokenize_chinese_chars __A : int = normalizer_class(**_A ) __A : Union[str, Any] = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : Tuple = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[Any] = [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : int = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): __A : Any = data def __iter__( self ): for element in self.data: yield element def _SCREAMING_SNAKE_CASE ( a=True ) -> Any: __A : List[Any] = Accelerator(even_batches=a ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str: if iterable: __A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) ) else: __A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) ) __A : Optional[Any] = DataLoader(a , batch_size=a ) __A : Optional[int] = accelerator.prepare(a ) return dl def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]: __A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a ) __A : Tuple = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : int = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : str = create_accelerator(even_batches=a ) verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _SCREAMING_SNAKE_CASE ( ) -> str: __A : Optional[Any] = create_accelerator(even_batches=a ) __A : str = torch.nn.Linear(1 , 1 ) __A : Optional[int] = accelerator.prepare(a ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : str = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(a ): __A : Dict = ddp_model(batch[0].float() ) __A : List[str] = output.sum() loss.backward() batch_idxs.append(a ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , a ) assert "only supported for multi-GPU" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : int = True __A : Union[str, Any] = False __A : Optional[int] = create_accelerator(even_batches=a ) __A : int = torch.nn.Linear(1 , 1 ) __A : List[Any] = accelerator.prepare(a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : List[str] = train_dl.batch_sampler.even_batches __A : Dict = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Any = True __A : List[Any] = False __A : Tuple = create_accelerator(even_batches=a ) __A : List[str] = torch.nn.Linear(1 , 1 ) __A : Optional[Any] = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('ignore' ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : Tuple = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Any = create_accelerator() __A : Union[str, Any] = torch.nn.Linear(1 , 1 ) __A : str = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): pass assert issubclass(w[-1].category , a ) assert "only supported for map-style datasets" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : str = create_accelerator() accelerator.print('Test that even_batches variable ensures uniform batches across processes' ) test_default_ensures_even_batch_sizes() accelerator.print('Run tests with even_batches disabled' ) test_can_disable_even_batches() accelerator.print('Test joining uneven inputs' ) test_can_join_uneven_inputs() accelerator.print('Test overriding even_batches when joining uneven inputs' ) test_join_can_override_even_batches() accelerator.print('Test overriding even_batches for mixed dataloader types' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('Test join with non DDP distributed raises warning' ) __A : int = accelerator.state.distributed_type __A : Tuple = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(a ) __A : str = original_state if __name__ == "__main__": main()
77
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): debug_launcher(test_script.main ) def UpperCAmelCase_ ( self ): debug_launcher(test_ops.main )
77
1
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: # Checks if the entire collection has been sorted if len(a ) <= 1 or n <= 1: return insert_next(a , n - 1 ) rec_insertion_sort(a , n - 1 ) def _SCREAMING_SNAKE_CASE ( a , a ) -> List[str]: # Checks order between adjacent elements if index >= len(a ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order __A , __A : Union[str, Any] = ( collection[index], collection[index - 1], ) insert_next(a , index + 1 ) if __name__ == "__main__": UpperCAmelCase : Any = input('''Enter integers separated by spaces: ''') UpperCAmelCase : list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
77
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Tuple = tempfile.mkdtemp() # fmt: off __A : Union[str, Any] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Dict = dict(zip(_A , range(len(_A ) ) ) ) __A : int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : Optional[Any] = {'unk_token': '<unk>'} __A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : Union[str, Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : List[str] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[str] = self.get_tokenizer() __A : Dict = self.get_rust_tokenizer() __A : Optional[Any] = self.get_image_processor() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Any = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : int = self.get_image_processor(do_normalize=_A ) __A : int = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : List[Any] = self.prepare_image_inputs() __A : Any = image_processor(_A , return_tensors='np' ) __A : Tuple = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_image_processor() __A : int = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = 'lower newer' __A : Any = processor(text=_A , return_tensors='np' ) __A : Dict = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Tuple = 'lower newer' __A : Union[str, Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[int] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Any = ['cat', 'nasa badge'] __A : List[Any] = processor(text=_A ) __A : Dict = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : int = [['cat', 'nasa badge'], ['person']] __A : str = processor(text=_A ) __A : int = 16 __A : Optional[int] = len(_A ) __A : int = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : int = 'google/owlvit-base-patch32' __A : List[str] = OwlViTProcessor.from_pretrained(_A ) __A : Tuple = ['cat', 'nasa badge'] __A : Dict = processor(text=_A ) __A : Tuple = 16 __A : str = inputs['input_ids'] __A : str = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Dict = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = self.prepare_image_inputs() __A : Tuple = self.prepare_image_inputs() __A : Any = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Union[str, Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
77
1
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import sys import transformers UpperCAmelCase : Dict = '''3''' print('''Python version:''', sys.version) print('''transformers version:''', transformers.__version__) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) print('''NCCL version:''', torch.cuda.nccl.version()) except ImportError: print('''Torch version:''', None) try: import deepspeed print('''DeepSpeed version:''', deepspeed.__version__) except ImportError: print('''DeepSpeed version:''', None) try: import tensorflow as tf print('''TensorFlow version:''', tf.__version__) print('''TF GPUs available:''', bool(tf.config.list_physical_devices('''GPU'''))) print('''Number of TF GPUs available:''', len(tf.config.list_physical_devices('''GPU'''))) except ImportError: print('''TensorFlow version:''', None)
77
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase : Union[str, Any] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Tuple: for attribute in key.split('.' ): __A : Dict = getattr(a , a ) if weight_type is not None: __A : Any = getattr(a , a ).shape else: __A : Any = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __A : Union[str, Any] = value elif weight_type == "weight_g": __A : Dict = value elif weight_type == "weight_v": __A : Optional[int] = value elif weight_type == "bias": __A : int = value elif weight_type == "running_mean": __A : Union[str, Any] = value elif weight_type == "running_var": __A : Union[str, Any] = value elif weight_type == "num_batches_tracked": __A : Any = value elif weight_type == "inv_freq": __A : Optional[Any] = value else: __A : int = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]: __A : Any = [] __A : Optional[int] = fairseq_model.state_dict() __A : Union[str, Any] = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __A : int = False if "conv_layers" in name: load_conv_layer( a , a , a , a , hf_model.config.feat_extract_norm == 'group' , ) __A : Optional[int] = True else: for key, mapped_key in MAPPING.items(): __A : Any = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __A : Optional[Any] = True if "*" in mapped_key: __A : str = name.split(a )[0].split('.' )[-2] __A : int = mapped_key.replace('*' , a ) if "pos_bias_u" in name: __A : Optional[int] = None elif "pos_bias_v" in name: __A : Dict = None elif "weight_g" in name: __A : Optional[Any] = 'weight_g' elif "weight_v" in name: __A : Dict = 'weight_v' elif "bias" in name: __A : Tuple = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __A : int = 'weight' elif "running_mean" in name: __A : str = 'running_mean' elif "inv_freq" in name: __A : List[Any] = 'inv_freq' elif "running_var" in name: __A : Union[str, Any] = 'running_var' elif "num_batches_tracked" in name: __A : Optional[Any] = 'num_batches_tracked' else: __A : List[str] = None set_recursively(a , a , a , a , a ) continue if not is_used: unused_weights.append(a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Any: __A : str = full_name.split('conv_layers.' )[-1] __A : str = name.split('.' ) __A : Dict = int(items[0] ) __A : Any = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) __A : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) __A : List[str] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a ) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a=None , a=None , a=True ) -> Any: if config_path is not None: __A : Tuple = WavaVecaConformerConfig.from_pretrained(a , hidden_act='swish' ) else: __A : Optional[Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: __A : Dict = 'rotary' if is_finetuned: if dict_path: __A : Dict = Dictionary.load(a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __A : int = target_dict.pad_index __A : List[Any] = target_dict.bos_index __A : Any = target_dict.eos_index __A : Dict = len(target_dict.symbols ) __A : Optional[Any] = os.path.join(a , 'vocab.json' ) if not os.path.isdir(a ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(a ) ) return os.makedirs(a , exist_ok=a ) __A : List[str] = target_dict.indices # fairseq has the <pad> and <s> switched __A : int = 0 __A : Optional[Any] = 1 with open(a , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(a , a ) __A : Optional[Any] = WavaVecaCTCTokenizer( a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=a , ) __A : Tuple = True if config.feat_extract_norm == 'layer' else False __A : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=a , return_attention_mask=a , ) __A : Optional[int] = WavaVecaProcessor(feature_extractor=a , tokenizer=a ) processor.save_pretrained(a ) __A : List[Any] = WavaVecaConformerForCTC(a ) else: __A : List[Any] = WavaVecaConformerForPreTraining(a ) if is_finetuned: __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: __A : Optional[Any] = argparse.Namespace(task='audio_pretraining' ) __A : str = fairseq.tasks.setup_task(a ) __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=a ) __A : Tuple = model[0].eval() recursively_load_weights(a , a , not is_finetuned ) hf_wavavec.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) UpperCAmelCase : List[str] = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
77
1
def _SCREAMING_SNAKE_CASE ( ) -> int: return [ a * b * (10_00 - a - b) for a in range(1 , 9_99 ) for b in range(a , 9_99 ) if (a * a + b * b == (10_00 - a - b) ** 2) ][0] if __name__ == "__main__": print(F"""{solution() = }""")
77
from abc import ABC, abstractmethod from argparse import ArgumentParser class _A( snake_case__ ): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( _A ): raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self ): raise NotImplementedError()
77
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCAmelCase : List[str] = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( a ) -> List[List[ImageInput]]: if isinstance(a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(a ): return [[videos]] raise ValueError(F"""Could not make batched video from {videos}""" ) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Dict = ['''pixel_values'''] def __init__( self , _A = True , _A = None , _A = PILImageResampling.BILINEAR , _A = True , _A = None , _A = True , _A = 1 / 255 , _A = True , _A = None , _A = None , **_A , ): super().__init__(**_A ) __A : Optional[Any] = size if size is not None else {'shortest_edge': 224} __A : Dict = get_size_dict(_A , default_to_square=_A ) __A : Dict = crop_size if crop_size is not None else {'height': 224, 'width': 224} __A : Any = get_size_dict(_A , param_name='crop_size' ) __A : Union[str, Any] = do_resize __A : List[Any] = size __A : List[str] = do_center_crop __A : List[Any] = crop_size __A : Any = resample __A : Tuple = do_rescale __A : Tuple = rescale_factor __A : Optional[int] = do_normalize __A : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __A : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCAmelCase_ ( self , _A , _A , _A = PILImageResampling.BILINEAR , _A = None , **_A , ): __A : Dict = get_size_dict(_A , default_to_square=_A ) if "shortest_edge" in size: __A : Tuple = get_resize_output_image_size(_A , size['shortest_edge'] , default_to_square=_A ) elif "height" in size and "width" in size: __A : List[Any] = (size['height'], size['width']) else: raise ValueError(F"""Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) return resize(_A , size=_A , resample=_A , data_format=_A , **_A ) def UpperCAmelCase_ ( self , _A , _A , _A = None , **_A , ): __A : Any = get_size_dict(_A ) if "height" not in size or "width" not in size: raise ValueError(F"""Size must have 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(_A , size=(size['height'], size['width']) , data_format=_A , **_A ) def UpperCAmelCase_ ( self , _A , _A , _A = None , **_A , ): return rescale(_A , scale=_A , data_format=_A , **_A ) def UpperCAmelCase_ ( self , _A , _A , _A , _A = None , **_A , ): return normalize(_A , mean=_A , std=_A , data_format=_A , **_A ) def UpperCAmelCase_ ( self , _A , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = ChannelDimension.FIRST , ): if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. __A : Any = to_numpy_array(_A ) if do_resize: __A : Union[str, Any] = self.resize(image=_A , size=_A , resample=_A ) if do_center_crop: __A : Optional[int] = self.center_crop(_A , size=_A ) if do_rescale: __A : str = self.rescale(image=_A , scale=_A ) if do_normalize: __A : Optional[Any] = self.normalize(image=_A , mean=_A , std=_A ) __A : int = to_channel_dimension_format(_A , _A ) return image def UpperCAmelCase_ ( self , _A , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = ChannelDimension.FIRST , **_A , ): __A : Optional[Any] = do_resize if do_resize is not None else self.do_resize __A : List[str] = resample if resample is not None else self.resample __A : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop __A : Any = do_rescale if do_rescale is not None else self.do_rescale __A : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor __A : List[Any] = do_normalize if do_normalize is not None else self.do_normalize __A : List[Any] = image_mean if image_mean is not None else self.image_mean __A : Optional[int] = image_std if image_std is not None else self.image_std __A : List[str] = size if size is not None else self.size __A : Any = get_size_dict(_A , default_to_square=_A ) __A : List[Any] = crop_size if crop_size is not None else self.crop_size __A : List[Any] = get_size_dict(_A , param_name='crop_size' ) if not valid_images(_A ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) __A : int = make_batched(_A ) __A : str = [ [ self._preprocess_image( image=_A , do_resize=_A , size=_A , resample=_A , do_center_crop=_A , crop_size=_A , do_rescale=_A , rescale_factor=_A , do_normalize=_A , image_mean=_A , image_std=_A , data_format=_A , ) for img in video ] for video in videos ] __A : Optional[Any] = {'pixel_values': videos} return BatchFeature(data=_A , tensor_type=_A )
77
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
1
import json import os import unittest from typing import Tuple from transformers import WavaVecaPhonemeCTCTokenizer from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.models.wavaveca_phoneme.tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizerOutput from transformers.testing_utils import require_phonemizer from ...test_tokenization_common import TokenizerTesterMixin @require_phonemizer class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = WavaVecaPhonemeCTCTokenizer UpperCamelCase : Union[str, Any] = False def UpperCAmelCase_ ( self ): super().setUp() __A : List[Any] = ( '<s> <pad> </s> <unk> n s t ə l a i k d m ɛ ɾ e ɪ p o ɐ z ð f j v b ɹ ʁ ʊ iː r w ʌ u ɡ æ aɪ ʃ h ɔ ɑː ' 'ŋ ɚ eɪ β uː y ɑ̃ oʊ ᵻ eː θ aʊ ts oː ɔ̃ ɣ ɜ ɑ dʒ əl x ɜː ç ʒ tʃ ɔː ɑːɹ ɛ̃ ʎ ɔːɹ ʋ aː ɕ œ ø oːɹ ɲ yː ' 'ʔ iə i5 s. tɕ ?? nʲ ɛː œ̃ ɭ ɔø ʑ tʲ ɨ ɛɹ ts. rʲ ɪɹ ɭʲ i.5 ɔɪ q sʲ u5 ʊɹ iɜ a5 iɛ5 øː ʕ ja əɜ th ɑ5 ' 'oɪ dʲ ə5 tɕh ts.h mʲ ɯ dʑ vʲ e̞ tʃʲ ei5 o5 onɡ5 ɑu5 iɑ5 ai5 aɪɚ kh ə1 ʐ i2 ʉ ħ t[ aɪə ʲ ju ə2 u2 oɜ ' 'pː iɛɜ ou5 y5 uɜ tː uo5 d[ uoɜ tsh ɑɜ ɵ i̪5 uei5 ɟ aɜ ɑɨ i.ɜ eʊ o2 ɐ̃ ä pʲ kʲ n̩ ɒ ph ɑu2 uɨ əɪ ɫ ɬ ' 'yɜ bʲ ɑ2 s̪ aiɜ χ ɐ̃ʊ̃ 1 ə4 yæɜ a2 ɨː t̪ iouɜ ũ onɡɜ aɨ iɛ2 ɔɨ ɑuɜ o̞ ei2 iou2 c kː y2 ɖ oe dˤ yɛɜ ' 'əʊ S ɡʲ onɡ2 u" eiɜ ʈ ɯᵝ iou5 dZ r̝̊ i.2 tS s^ ʝ yə5 iɑɜ uə5 pf ɨu iɑ2 ou2 ər2 fʲ ai2 r̝ uəɜ ɳ əɨ ' 'ua5 uɪ ɽ bː yu5 uo2 yɛ5 l̩ ɻ ərɜ ʂ i̪2 ouɜ uaɜ a. a.ː yæ5 dː r̩ ee ɪu ər5 i̪ ɜ æi u: i.ː t^ o1 ɪ^ ' 'ai ueiɜ æː ɛɪ eə i. ɴ ie ua2 ɑ1 o4 tʃː o: ɑ: u1 N i̪1 au yæ2 u. qː yəɜ y: kʰ tʃʰ iʊ sx õ uo tʰ ' 'uai5 bʰ u.ː uə2 ʊə d^ s̪ː yiɜ dʰ r. oe: i1 ɟː yu2 nʲʲ i̪4 uei2 tsʲ ɸ ĩ ɑ4 t̪ː eɑ u4 e: tsː ʈʰ ɡʰ ' 'ɯɯ dʒʲ ʂʲ X ɵː uaiɜ tɕʲ ã t^ː ẽː yɛ2 cː i.1 ɛʊ dˤdˤ dʒː i4 ɡː yi ɕʲ ɟʰ pʰ dʑʲ yuɜ ua1 ua4 æiː ɐɐ ' 'ui iou1 ʊː a1 iou4 cʰ iɛ1 yə2 ɖʰ ẽ ʒʲ ää ər4 iːː ɪː iɑ1 ər1 œː øi ɪuː cʰcʰ əː1 iː1 ũ kʰː o̞o̞ xʲ ' 'ou1 iɛ4 e̞e̞ y1 dzː dʲʲ dʰː ɯᵝɯᵝ lː uo1 i.4 i: yɛ5ʲ a4' ).split(' ' ) __A : Tuple = dict(zip(_A , range(len(_A ) ) ) ) __A : Any = {'pad_token': '<pad>', 'unk_token': '<unk>', 'bos_token': '<s>', 'eos_token': '</s>'} __A : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) def UpperCAmelCase_ ( self , _A , _A=False , _A=20 , _A=5 ): __A : Dict = [(i, tokenizer.decode([i] , clean_up_tokenization_spaces=_A )) for i in range(len(_A ) )] __A : Tuple = list(filter(lambda _A : [t[0]] == tokenizer.encode(t[1] , do_phonemize=_A ) , _A ) ) if max_length is not None and len(_A ) > max_length: __A : List[Any] = toks[:max_length] if min_length is not None and len(_A ) < min_length and len(_A ) > 0: while len(_A ) < min_length: __A : List[Any] = toks + toks # toks_str = [t[1] for t in toks] __A : str = [t[0] for t in toks] # Ensure consistency __A : List[str] = tokenizer.decode(_A , clean_up_tokenization_spaces=_A ) if " " not in output_txt and len(_A ) > 1: __A : Union[str, Any] = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_A ) + ' ' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_A ) ) if with_prefix_space: __A : Tuple = ' ' + output_txt __A : Optional[Any] = tokenizer.encode(_A , add_special_tokens=_A ) return output_txt, output_ids def UpperCAmelCase_ ( self , **_A ): kwargs.update(self.special_tokens_map ) return WavaVecaPhonemeCTCTokenizer.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): __A : Any = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' ) # check adding a single token tokenizer.add_tokens('xxx' ) __A : List[Any] = tokenizer('m xxx ɪ' , do_phonemize=_A ).input_ids self.assertEqual(_A , [13, 392, 17] ) # xxx should be last token tokenizer.add_tokens(['aaa', 'bbb', 'ccc'] ) __A : Tuple = tokenizer('m aaa ɪ ccc' , do_phonemize=_A ).input_ids self.assertEqual(_A , [13, 393, 17, 395] ) # aaa and ccc should be after xxx and 2 after aaa __A : int = tokenizer('maɪ c' , do_phonemize=_A ).input_ids self.assertEqual(_A , [3, 200] ) # mai should be <unk> (=3) def UpperCAmelCase_ ( self ): __A : str = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' ) __A : int = 'Hello how are you' __A : Optional[int] = tokenizer.phonemize(_A , phonemizer_lang='en-us' ) self.assertEqual(_A , 'h ə l oʊ h aʊ ɑːɹ j uː' ) def UpperCAmelCase_ ( self ): __A : str = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' ) __A : Tuple = 'Hello how are you' __A : Optional[int] = tokenizer.phonemize(_A , phonemizer_lang='en-us' ) self.assertEqual(tokenizer(_A ).input_ids , tokenizer(_A , do_phonemize=_A ).input_ids ) def UpperCAmelCase_ ( self ): __A : Dict = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' ) __A : Optional[int] = 'Hello how are you' __A : Dict = tokenizer.phonemize(_A , phonemizer_lang='en-us' ) __A : Any = tokenizer.decode(tokenizer(_A ).input_ids ) self.assertEqual(_A , _A ) def UpperCAmelCase_ ( self ): __A : Dict = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' ) __A : str = [ [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98], [24, 22, 5, 24, 22, 5, 77], ] __A : List[str] = tokenizer.decode(sample_ids[0] ) __A : Any = tokenizer.batch_decode(_A ) self.assertEqual(_A , batch_tokens[0] ) self.assertEqual(_A , ['k s ɾ ɾ l ɭʲ', 'j ð s j ð s oːɹ'] ) def UpperCAmelCase_ ( self ): __A : List[str] = self.tokenizer_class.from_pretrained( 'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token='|' ) tokenizer.add_tokens('|' ) __A : str = 'Hello how are you' __A : Any = tokenizer.phonemize(_A , phonemizer_lang='en-us' ) self.assertEqual(_A , 'h ə l oʊ | h aʊ | ɑːɹ | j uː |' ) def UpperCAmelCase_ ( self ): __A : str = self.tokenizer_class.from_pretrained( 'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token='|' ) tokenizer.add_tokens('|' ) __A : Tuple = 'Hello how are you' __A : Dict = tokenizer.phonemize(_A , phonemizer_lang='en-us' ) self.assertEqual(tokenizer(_A ).input_ids , tokenizer(_A , do_phonemize=_A ).input_ids ) def UpperCAmelCase_ ( self ): __A : List[str] = self.tokenizer_class.from_pretrained( 'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token='|' ) tokenizer.add_tokens('|' ) # fmt: off __A : str = [ [11, 5, 15, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 15, 8, tokenizer.word_delimiter_token_id, 98], [tokenizer.word_delimiter_token_id, 24, 22, tokenizer.word_delimiter_token_id, 5, 24, 22, 5, 77], ] # fmt: on # decode with word_del_token filter __A : Dict = tokenizer.decode(sample_ids[0] ) __A : Any = tokenizer.batch_decode(_A ) self.assertEqual(_A , batch_tokens[0] ) self.assertEqual(_A , ['k s ɾ ɾ l ɭʲ', 'j ð s j ð s oːɹ'] ) # decode with no word_del_token filter __A : List[Any] = tokenizer.decode(sample_ids[0] , filter_word_delimiter_token=_A ) __A : List[str] = tokenizer.batch_decode(_A , filter_word_delimiter_token=_A ) self.assertEqual(_A , batch_tokens[0] ) self.assertEqual(_A , ['k s ɾ | ɾ l | ɭʲ', '| j ð | s j ð s oːɹ'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = self.tokenizer_class.from_pretrained( 'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token='|' ) tokenizer.add_tokens('|' ) __A : Dict = 'Hello how are you' __A : List[str] = tokenizer.phonemize(_A , phonemizer_lang='en-us' ) __A : Dict = tokenizer.decode(tokenizer(_A ).input_ids , filter_word_delimiter_token=_A ) self.assertEqual(_A , _A ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.tokenizer_class.from_pretrained( 'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token='|' ) tokenizer.add_tokens('|' ) __A : Any = 'Hello how are you' __A : Dict = tokenizer.phonemize(_A , phonemizer_lang='en-us' ) __A : Optional[Any] = tokenizer.decode(tokenizer(_A ).input_ids , filter_word_delimiter_token=_A ) self.assertEqual(' '.join([p.strip() for p in phonemes.split(' |' )] ).strip() , _A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.tokenizer_class.from_pretrained( 'facebook/wav2vec2-lv-60-espeak-cv-ft' , word_delimiter_token=_A ) __A : Optional[Any] = 'Hello how are you' __A : List[str] = tokenizer(_A , phonemizer_lang='en-us' ).input_ids __A : str = tokenizer(_A , phonemizer_lang='fr-fr' ).input_ids self.assertNotEqual(_A , _A ) __A : List[Any] = tokenizer.decode(_A ) __A : Optional[int] = tokenizer.decode(_A ) self.assertEqual(_A , 'h ə l oʊ h aʊ ɑːɹ j uː' ) self.assertEqual(_A , 'ɛ l o h aʊ a ʁ j u' ) def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' ) __A : Union[str, Any] = 'Hello how Are you' __A : Union[str, Any] = 'hello how are you' __A : List[str] = tokenizer(_A ).input_ids __A : Optional[int] = tokenizer(_A ).input_ids self.assertEqual(_A , _A ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft' ) tokenizer.add_tokens(['!', '?'] ) tokenizer.add_special_tokens({'cls_token': '$$$'} ) # fmt: off __A : Optional[int] = [ [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98, 392, 392, 393, 392, 392, 393, 394, 394], [24, 22, 5, 24, 22, 5, 77, tokenizer.pad_token_id, 394, 394], ] # fmt: on __A : Any = tokenizer.batch_decode(_A ) self.assertEqual(_A , ['k s ɾ ɾ l ɭʲ!?!? $$$', 'j ð s j ð s oːɹ $$$'] ) @staticmethod def UpperCAmelCase_ ( _A , _A ): __A : str = [d[key] for d in offsets] return retrieved_list def UpperCAmelCase_ ( self ): __A : Optional[int] = self.get_tokenizer(word_delimiter_token='|' ) tokenizer.add_tokens('|' ) # fmt: off # ksssɾɾ|ɾɾ<pad>ɾɾ|<pad>ɾlll|ɭʲ -> k s ɾ ɾ | ɾ l | ɭʲ" __A : Tuple = [11, 5, 5, 5, 15, 15, tokenizer.pad_token_id, 15, 15, tokenizer.word_delimiter_token_id, tokenizer.pad_token_id, 15, 8, 8, 8, tokenizer.word_delimiter_token_id, 98] # fmt: on __A : int = tokenizer.decode(_A , output_char_offsets=_A , filter_word_delimiter_token=_A ) # check Wav2Vec2CTCTokenizerOutput keys for char self.assertEqual(len(outputs.keys() ) , 2 ) self.assertTrue('text' in outputs ) self.assertTrue('char_offsets' in outputs ) self.assertTrue(isinstance(_A , _A ) ) # check that order of chars is correct and identical for both outputs self.assertEqual(' '.join(self.get_from_offsets(outputs['char_offsets'] , 'char' ) ) , outputs.text ) self.assertListEqual( self.get_from_offsets(outputs['char_offsets'] , 'char' ) , ['k', 's', 'ɾ', 'ɾ', '|', 'ɾ', 'l', '|', 'ɭʲ'] ) # check that offsets are actually correct for char # 0-1 is 11, 1-4 is 5, 4-6 is first 15, 6-7 is <pad> (thus not shown), 7-9 is second 15, 9-10 is word_delimiter_token, # 10-11 is <pad> (thus not shown), 11-12 is third 15, 12-15 is 8, 15-16 is word_delimiter_token, 16-17 is 98 self.assertListEqual( self.get_from_offsets(outputs['char_offsets'] , 'start_offset' ) , [0, 1, 4, 7, 9, 11, 12, 15, 16] ) self.assertListEqual( self.get_from_offsets(outputs['char_offsets'] , 'end_offset' ) , [1, 4, 6, 9, 10, 12, 15, 16, 17] ) def UpperCAmelCase_ ( self ): __A : List[str] = self.get_tokenizer(word_delimiter_token='|' ) def check_list_tuples_equal(_A , _A ): self.assertTrue(isinstance(_A , _A ) ) self.assertTrue(isinstance(outputs_list[0] , _A ) ) # transform list to ModelOutput __A : Union[str, Any] = WavaVecaPhonemeCTCTokenizerOutput( {k: [d[k] for d in outputs_list] for k in outputs_list[0]} ) self.assertListEqual(outputs_batch['text'] , outputs_batch_a['text'] ) def recursive_check(_A , _A ): if isinstance(_A , _A ): [recursive_check(_A , _A ) for la, la in zip(_A , _A )] self.assertEqual(_A , _A ) if "char_offsets" in outputs_batch: recursive_check(outputs_batch['char_offsets'] , outputs_batch_a['char_offsets'] ) # fmt: off __A : Dict = [ [11, 5, 15, tokenizer.pad_token_id, 15, 4, 8, 98, 32, 32, 32, 32, 4, 33, tokenizer.word_delimiter_token_id, 32, 32, 33, 34, 34], [24, 22, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 24, 22, 22, 22, 4, 5, 77, tokenizer.pad_token_id, 22, 22, 4, 34, 34, 34, 34], ] # fmt: on # We assume that `decode` works as expected. All we will check now is # the output type is correct and the output is identical to `decode` # char __A : List[str] = tokenizer.batch_decode(_A , output_char_offsets=_A ) __A : Tuple = [tokenizer.decode(_A , output_char_offsets=_A ) for ids in sample_ids] check_list_tuples_equal(_A , _A ) @unittest.skip('Wav2Vec2PhonemeTokenizer always lower cases letters to correctly map to phonemes' ) def UpperCAmelCase_ ( self ): pass @unittest.skip('Wav2Vec2PhonemeTokenizer always puts spaces between phonemes' ) def UpperCAmelCase_ ( self ): pass @unittest.skip('encodes to text to ids, but decodes ids to phonemes -> not possible to have internal consistency' ) def UpperCAmelCase_ ( self ): pass @unittest.skip('Wav2Vec2PhonemeModel has no max model length => no testing' ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): __A : List[str] = self.get_tokenizers(do_lower_case=_A ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __A : Optional[Any] = tokenizer.vocab_size __A : List[str] = len(_A ) self.assertNotEqual(_A , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) __A : int = ['aaaaa bbbbbb', 'cccccccccdddddddd'] __A : Tuple = tokenizer.add_tokens(_A ) __A : Optional[int] = tokenizer.vocab_size __A : Union[str, Any] = len(_A ) self.assertNotEqual(_A , 0 ) self.assertEqual(_A , _A ) self.assertEqual(_A , len(_A ) ) self.assertEqual(_A , all_size + len(_A ) ) __A : str = tokenizer.encode('aaaaa bbbbbb low cccccccccdddddddd l' , add_special_tokens=_A ) self.assertGreaterEqual(len(_A ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) __A : List[str] = {'eos_token': '>>>>|||<||<<|<<', 'pad_token': '<<<<<|||>|>>>>|>'} __A : Union[str, Any] = tokenizer.add_special_tokens(_A ) __A : Optional[Any] = tokenizer.vocab_size __A : Optional[Any] = len(_A ) self.assertNotEqual(_A , 0 ) self.assertEqual(_A , _A ) self.assertEqual(_A , len(_A ) ) self.assertEqual(_A , all_size_a + len(_A ) ) __A : Any = tokenizer.encode( '>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l' , add_special_tokens=_A ) self.assertGreaterEqual(len(_A ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) @unittest.skip('The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode.' ) def UpperCAmelCase_ ( self ): pass @unittest.skip('The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode.' ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # The default common tokenizer tests assumes that the output of `convert_tokens_to_string` is a string which # is not the case for Wav2Vec2PhonemeCTCTokenizer. __A : Optional[Any] = self.get_tokenizers(fast=_A , do_lower_case=_A ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __A : Dict = ['ð', 'ɪ', 's', 'ɪ', 'z', 'ɐ', 't', 'ɛ', 'k', 's', 't'] __A : Union[str, Any] = tokenizer.convert_tokens_to_string(_A ) self.assertIsInstance(output['text'] , _A )
77
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = ShapEPipeline UpperCamelCase : str = ['''prompt'''] UpperCamelCase : Tuple = ['''prompt'''] UpperCamelCase : Optional[int] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] UpperCamelCase : int = False @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self ): return 8 @property def UpperCAmelCase_ ( self ): __A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_A ) @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : int = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __A : Optional[Any] = PriorTransformer(**_A ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : List[str] = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __A : List[Any] = ShapERenderer(**_A ) return model def UpperCAmelCase_ ( self ): __A : List[str] = self.dummy_prior __A : Optional[int] = self.dummy_text_encoder __A : List[Any] = self.dummy_tokenizer __A : str = self.dummy_renderer __A : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=_A , clip_sample=_A , clip_sample_range=1.0 , ) __A : Any = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): if str(_A ).startswith('mps' ): __A : List[Any] = torch.manual_seed(_A ) else: __A : Dict = torch.Generator(device=_A ).manual_seed(_A ) __A : int = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def UpperCAmelCase_ ( self ): __A : Tuple = 'cpu' __A : Any = self.get_dummy_components() __A : Tuple = self.pipeline_class(**_A ) __A : List[str] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Tuple = pipe(**self.get_dummy_inputs(_A ) ) __A : int = output.images[0] __A : str = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __A : Any = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCAmelCase_ ( self ): __A : List[str] = torch_device == 'cpu' __A : Any = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_A , relax_max_difference=_A , ) def UpperCAmelCase_ ( self ): __A : Any = self.get_dummy_components() __A : Any = self.pipeline_class(**_A ) __A : Dict = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Any = 1 __A : Dict = 2 __A : Tuple = self.get_dummy_inputs(_A ) for key in inputs.keys(): if key in self.batch_params: __A : Optional[int] = batch_size * [inputs[key]] __A : Optional[int] = pipe(**_A , num_images_per_prompt=_A )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __A : Dict = ShapEPipeline.from_pretrained('openai/shap-e' ) __A : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : str = torch.Generator(device=_A ).manual_seed(0 ) __A : Tuple = pipe( 'a shark' , generator=_A , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_A , _A )
77
1
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration UpperCAmelCase : Optional[Any] = '''facebook/wmt19-en-de''' UpperCAmelCase : str = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model UpperCAmelCase : Optional[int] = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) UpperCAmelCase : str = FSMTForConditionalGeneration(config) print(F"""num of params {tiny_model.num_parameters()}""") # Test UpperCAmelCase : Dict = tokenizer(['''Making tiny model'''], return_tensors='''pt''') UpperCAmelCase : Dict = tiny_model(**batch) print('''test output:''', len(outputs.logits[0])) # Save UpperCAmelCase : Optional[int] = '''tiny-wmt19-en-de''' tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"""Generated {mname_tiny}""") # Upload # transformers-cli upload tiny-wmt19-en-de
77
from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if len(a ) != 2 or len(a[0] ) != 2 or len(a ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __A : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> str: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a ) -> tuple[list, list, list, list]: if len(a ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __A : str = len(a ) __A : List[Any] = matrix_length // 2 __A : List[str] = [[a[i][j] for j in range(a , a )] for i in range(a )] __A : Dict = [ [a[i][j] for j in range(a , a )] for i in range(a , a ) ] __A : int = [[a[i][j] for j in range(a )] for i in range(a )] __A : Any = [[a[i][j] for j in range(a )] for i in range(a , a )] return top_left, top_right, bot_left, bot_right def _SCREAMING_SNAKE_CASE ( a ) -> tuple[int, int]: return len(a ), len(matrix[0] ) def _SCREAMING_SNAKE_CASE ( a ) -> None: print('\n'.join(str(a ) for line in matrix ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a ) == (2, 2): return default_matrix_multiplication(a , a ) __A , __A , __A , __A : str = split_matrix(a ) __A , __A , __A , __A : List[Any] = split_matrix(a ) __A : Any = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Tuple = actual_strassen(matrix_addition(a , a ) , a ) __A : List[str] = actual_strassen(matrix_addition(a , a ) , a ) __A : Optional[int] = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Any = actual_strassen(matrix_addition(a , a ) , matrix_addition(a , a ) ) __A : Any = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = matrix_addition(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) __A : Union[str, Any] = matrix_addition(a , a ) __A : str = matrix_addition(a , a ) __A : Dict = matrix_subtraction(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) # construct the new matrix from our 4 quadrants __A : List[Any] = [] for i in range(len(a ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(a ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a )[1] != matrix_dimensions(a )[0]: __A : Dict = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"""Matrix A: {matrixa}\n""" F"""Matrix B: {matrixa}""" ) raise Exception(a ) __A : int = matrix_dimensions(a ) __A : Any = matrix_dimensions(a ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __A : List[Any] = max(*a , *a ) __A : Optional[Any] = int(math.pow(2 , math.ceil(math.loga(a ) ) ) ) __A : Union[str, Any] = matrixa __A : Optional[int] = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __A : str = actual_strassen(a , a ) # Removing the additional zeros for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] UpperCAmelCase : Optional[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
77
1
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase : Tuple = logging.get_logger(__name__) UpperCAmelCase : Tuple = {'''vocab_file''': '''spiece.model'''} UpperCAmelCase : int = { '''vocab_file''': { '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''', } } UpperCAmelCase : str = { '''AI-Sweden/gpt-sw3-126m''': 20_48, '''AI-Sweden/gpt-sw3-350m''': 20_48, '''AI-Sweden/gpt-sw3-1.6b''': 20_48, '''AI-Sweden/gpt-sw3-6.7b''': 20_48, '''AI-Sweden/gpt-sw3-20b''': 20_48, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : str = VOCAB_FILES_NAMES UpperCamelCase : str = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : str = ['''input_ids''', '''attention_mask'''] def __init__( self , _A , _A=False , _A=False , _A=False , _A=None , _A=None , _A=None , _A=None , _A = None , **_A , ): __A : Any = {} if sp_model_kwargs is None else sp_model_kwargs __A : str = kwargs.get('name_or_path' ) if name_or_path is None: logger.warning( 'name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,' ' you are testing the model, this can safely be ignored' ) __A : Any = 'None' # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __A : int = '<|endoftext|>' if eos_token is None else eos_token __A : Any = '<unk>' if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __A : Optional[int] = unk_token if pad_token is None else pad_token __A : List[Any] = eos_token if bos_token is None else bos_token else: __A : List[str] = '<pad>' if pad_token is None else pad_token __A : Optional[int] = '<s>' if bos_token is None else bos_token super().__init__( do_lower_case=_A , remove_space=_A , keep_accents=_A , bos_token=_A , eos_token=_A , unk_token=_A , pad_token=_A , sp_model_kwargs=self.sp_model_kwargs , **_A , ) __A : Union[str, Any] = do_lower_case __A : int = remove_space __A : Any = keep_accents __A : str = vocab_file __A : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_A ) # Used for whitespace normalization in input texts # fmt : off __A : str = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '', '„'} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __A : Union[str, Any] = re.compile( F"""[{"".join(map(_A , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]""" ) def __getstate__( self ): __A : List[str] = self.__dict__.copy() __A : Tuple = None return state def __setstate__( self , _A ): __A : Union[str, Any] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __A : List[Any] = {} __A : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def UpperCAmelCase_ ( self ): return len(self.sp_model ) def UpperCAmelCase_ ( self , _A ): __A : Optional[Any] = self.non_printing_characters_re.sub('' , _A ) # Normalize whitespaces __A : str = ''.join([char if char not in self.whitespaces else ' ' for char in text] ) # NFC Unicode normalization __A : Optional[Any] = unicodedata.normalize('NFC' , _A ) return text def UpperCAmelCase_ ( self , _A , **_A ): __A : List[str] = self.preprocess_text(_A ) return self.sp_model.encode(_A , out_type=_A ) def UpperCAmelCase_ ( self , _A ): return self.sp_model.PieceToId(_A ) def UpperCAmelCase_ ( self , _A ): return self.sp_model.IdToPiece(_A ) @staticmethod def UpperCAmelCase_ ( _A ): return out_string def UpperCAmelCase_ ( self , _A ): __A : int = [] __A : Optional[int] = '' __A : List[str] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_A ) + token __A : Tuple = True __A : int = [] else: current_sub_tokens.append(_A ) __A : List[str] = False out_string += self.sp_model.decode(_A ) return out_string def UpperCAmelCase_ ( self ): __A : Optional[Any] = {self.convert_ids_to_tokens(_A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCAmelCase_ ( self , _A , _A = None ): if not os.path.isdir(_A ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __A : List[str] = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _A ) elif not os.path.isfile(self.vocab_file ): with open(_A , 'wb' ) as fi: __A : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(_A ) return (out_vocab_file,) def UpperCAmelCase_ ( self , _A , _A = False ): if isinstance(_A , _A ): __A : Union[str, Any] = self.preprocess_text(_A ) __A : Optional[Any] = self.sp_model.encode(_A ) else: __A : Any = [self.preprocess_text(_A ) for t in text] __A : str = self.sp_model.encode(_A ) if return_tensors is True or return_tensors == "pt": __A : Dict = torch.tensor(_A ) return token_ids def UpperCAmelCase_ ( self , _A ): return self.sp_model.decode(_A ) def UpperCAmelCase_ ( self , _A ): __A : Tuple = [F"""User: {text}""" if is_user else F"""Bot: {text}""" for is_user, text in conversation.iter_texts()] __A : Any = ( F"""{self.eos_token}{self.bos_token}""" + F"""{self.bos_token}""".join(_A ) + F"""{self.bos_token}Bot:""" ) return self.encode(text=_A )
77
def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : List[str] = [] __A : Tuple = [] __A : Union[str, Any] = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, } # Priority of each operator __A : List[str] = len(a ) if (len(a ) > 7) else 7 # Print table header for output print( 'Symbol'.center(8 ) , 'Stack'.center(a ) , 'Postfix'.center(a ) , sep=' | ' , ) print('-' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(a ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(a ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(a ) == 0: stack.append(a ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(a ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(a ) # push x to stack print( x.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format while len(a ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ' '.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format return "".join(a ) # return Postfix as str def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : List[Any] = list(infix[::-1] ) # reverse the infix equation for i in range(len(a ) ): if infix[i] == "(": __A : List[str] = ')' # change "(" to ")" elif infix[i] == ")": __A : Any = '(' # change ")" to "(" return (infix_2_postfix(''.join(a ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": UpperCAmelCase : List[str] = input('''\nEnter an Infix Equation = ''') # Input an Infix equation UpperCAmelCase : Union[str, Any] = ''''''.join(Infix.split()) # Remove spaces from the input print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
77
1
def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : List[Any] = [1] __A , __A , __A : Union[str, Any] = 0, 0, 0 __A : Optional[int] = ugly_nums[ia] * 2 __A : Any = ugly_nums[ia] * 3 __A : str = ugly_nums[ia] * 5 for _ in range(1 , a ): __A : Tuple = min(a , a , a ) ugly_nums.append(a ) if next_num == next_a: ia += 1 __A : int = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 __A : Union[str, Any] = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 __A : List[Any] = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(F"""{ugly_numbers(2_00) = }""")
77
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : Tuple = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json''' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase : int = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = '''mask2former''' UpperCamelCase : Any = ['''swin'''] UpperCamelCase : Union[str, Any] = {'''hidden_size''': '''hidden_dim'''} def __init__( self , _A = None , _A = 256 , _A = 256 , _A = 256 , _A = 1024 , _A = "relu" , _A = 6 , _A = 10 , _A = 8 , _A = 0.0 , _A = 2048 , _A = False , _A = False , _A = 4 , _A = 255 , _A = 100 , _A = 0.1 , _A = 2.0 , _A = 5.0 , _A = 5.0 , _A = 12544 , _A = 3.0 , _A = 0.7_5 , _A = 0.0_2 , _A = 1.0 , _A = True , _A = [4, 8, 16, 32] , _A = None , **_A , ): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) __A : Optional[int] = CONFIG_MAPPING['swin']( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=_A , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(_A , _A ): __A : Dict = backbone_config.pop('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[str] = config_class.from_dict(_A ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) __A : Optional[int] = backbone_config __A : Optional[Any] = feature_size __A : Any = mask_feature_size __A : Optional[Any] = hidden_dim __A : Union[str, Any] = encoder_feedforward_dim __A : Optional[Any] = activation_function __A : List[Any] = encoder_layers __A : Union[str, Any] = decoder_layers __A : Dict = num_attention_heads __A : Tuple = dropout __A : Dict = dim_feedforward __A : Tuple = pre_norm __A : Dict = enforce_input_projection __A : Optional[int] = common_stride __A : Optional[Any] = ignore_value __A : str = num_queries __A : List[Any] = no_object_weight __A : List[str] = class_weight __A : List[Any] = mask_weight __A : List[Any] = dice_weight __A : Tuple = train_num_points __A : Optional[Any] = oversample_ratio __A : Union[str, Any] = importance_sample_ratio __A : Union[str, Any] = init_std __A : int = init_xavier_std __A : Union[str, Any] = use_auxiliary_loss __A : Union[str, Any] = feature_strides __A : List[Any] = output_auxiliary_logits __A : Optional[Any] = decoder_layers super().__init__(**_A ) @classmethod def UpperCAmelCase_ ( cls , _A , **_A ): return cls( backbone_config=_A , **_A , ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = copy.deepcopy(self.__dict__ ) __A : List[Any] = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output
77
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def _SCREAMING_SNAKE_CASE ( a=None ) -> str: if subparsers is not None: __A : Optional[int] = subparsers.add_parser('test' ) else: __A : int = argparse.ArgumentParser('Accelerate test command' ) parser.add_argument( '--config_file' , default=a , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=a ) return parser def _SCREAMING_SNAKE_CASE ( a ) -> Union[str, Any]: __A : str = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['test_utils', 'scripts', 'test_script.py'] ) if args.config_file is None: __A : List[str] = script_name else: __A : Tuple = F"""--config_file={args.config_file} {script_name}""" __A : int = ['accelerate-launch'] + test_args.split() __A : Dict = execute_subprocess_async(a , env=os.environ.copy() ) if result.returncode == 0: print('Test is a success! You are ready for your distributed training!' ) def _SCREAMING_SNAKE_CASE ( ) -> int: __A : List[Any] = test_command_parser() __A : Optional[Any] = parser.parse_args() test_command(a ) if __name__ == "__main__": main()
77
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : str = '''conditional_detr''' UpperCamelCase : int = ['''past_key_values'''] UpperCamelCase : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , _A=True , _A=None , _A=3 , _A=300 , _A=6 , _A=2048 , _A=8 , _A=6 , _A=2048 , _A=8 , _A=0.0 , _A=0.0 , _A=True , _A="relu" , _A=256 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1.0 , _A=False , _A="sine" , _A="resnet50" , _A=True , _A=False , _A=2 , _A=5 , _A=2 , _A=1 , _A=1 , _A=2 , _A=5 , _A=2 , _A=0.2_5 , **_A , ): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __A : List[str] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_A , _A ): __A : Tuple = backbone_config.get('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[Any] = config_class.from_dict(_A ) __A : Tuple = use_timm_backbone __A : List[str] = backbone_config __A : Dict = num_channels __A : int = num_queries __A : int = d_model __A : str = encoder_ffn_dim __A : List[str] = encoder_layers __A : Optional[Any] = encoder_attention_heads __A : Union[str, Any] = decoder_ffn_dim __A : List[Any] = decoder_layers __A : Optional[Any] = decoder_attention_heads __A : Any = dropout __A : Any = attention_dropout __A : int = activation_dropout __A : Optional[int] = activation_function __A : Union[str, Any] = init_std __A : Union[str, Any] = init_xavier_std __A : Optional[Any] = encoder_layerdrop __A : int = decoder_layerdrop __A : List[str] = encoder_layers __A : str = auxiliary_loss __A : Union[str, Any] = position_embedding_type __A : Optional[int] = backbone __A : List[str] = use_pretrained_backbone __A : List[Any] = dilation # Hungarian matcher __A : List[str] = class_cost __A : Optional[int] = bbox_cost __A : Dict = giou_cost # Loss coefficients __A : Optional[int] = mask_loss_coefficient __A : Union[str, Any] = dice_loss_coefficient __A : List[Any] = cls_loss_coefficient __A : Dict = bbox_loss_coefficient __A : Tuple = giou_loss_coefficient __A : Tuple = focal_alpha super().__init__(is_encoder_decoder=_A , **_A ) @property def UpperCAmelCase_ ( self ): return self.encoder_attention_heads @property def UpperCAmelCase_ ( self ): return self.d_model def UpperCAmelCase_ ( self ): __A : str = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __A : Dict = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = version.parse('''1.11''' ) @property def UpperCAmelCase_ ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def UpperCAmelCase_ ( self ): return 1e-5 @property def UpperCAmelCase_ ( self ): return 12
77
1
def _SCREAMING_SNAKE_CASE ( a , a ) -> str: __A : int = len(a ) __A : int = len(a ) __A : int = ( first_str_length if first_str_length > second_str_length else second_str_length ) __A : list = [] for char_count in range(a ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(a ) if __name__ == "__main__": print(alternative_string_arrange('''AB''', '''XYZ'''), end=''' ''')
77
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _A( nn.Module ): """simple docstring""" def __init__( self ): super().__init__() __A : List[str] = nn.Linear(3 , 4 ) __A : Optional[Any] = nn.BatchNormad(4 ) __A : List[Any] = nn.Linear(4 , 5 ) def UpperCAmelCase_ ( self , _A ): return self.lineara(self.batchnorm(self.lineara(_A ) ) ) class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Dict = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , model.state_dict() ) __A : str = os.path.join(_A , 'index.json' ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: __A : Optional[int] = os.path.join(_A , F"""{key}.dat""" ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on the fact weights are properly loaded def UpperCAmelCase_ ( self ): __A : Dict = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: __A : Tuple = torch.randn(2 , 3 , dtype=_A ) with TemporaryDirectory() as tmp_dir: __A : int = offload_weight(_A , 'weight' , _A , {} ) __A : Union[str, Any] = os.path.join(_A , 'weight.dat' ) self.assertTrue(os.path.isfile(_A ) ) self.assertDictEqual(_A , {'weight': {'shape': [2, 3], 'dtype': str(_A ).split('.' )[1]}} ) __A : List[str] = load_offloaded_weight(_A , index['weight'] ) self.assertTrue(torch.equal(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : int = ModelForTest() __A : Union[str, Any] = model.state_dict() __A : Optional[Any] = {k: v for k, v in state_dict.items() if 'linear2' not in k} __A : str = {k: v for k, v in state_dict.items() if 'linear2' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : List[str] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) __A : Union[str, Any] = {k: v for k, v in state_dict.items() if 'weight' in k} __A : List[Any] = {k: v for k, v in state_dict.items() if 'weight' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : Optional[int] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) # Duplicates are removed __A : str = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) def UpperCAmelCase_ ( self ): __A : Dict = {'a.1': 0, 'a.10': 1, 'a.2': 2} __A : str = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1': 0, 'a.2': 2} ) __A : Optional[Any] = {'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2} __A : Any = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1.a': 0, 'a.2.a': 2} )
77
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available UpperCAmelCase : List[str] = { '''configuration_ernie''': ['''ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ErnieConfig''', '''ErnieOnnxConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[Any] = [ '''ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ErnieForCausalLM''', '''ErnieForMaskedLM''', '''ErnieForMultipleChoice''', '''ErnieForNextSentencePrediction''', '''ErnieForPreTraining''', '''ErnieForQuestionAnswering''', '''ErnieForSequenceClassification''', '''ErnieForTokenClassification''', '''ErnieModel''', '''ErniePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys UpperCAmelCase : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): __A : Any = data def __iter__( self ): for element in self.data: yield element def _SCREAMING_SNAKE_CASE ( a=True ) -> Any: __A : List[Any] = Accelerator(even_batches=a ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str: if iterable: __A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) ) else: __A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) ) __A : Optional[Any] = DataLoader(a , batch_size=a ) __A : Optional[int] = accelerator.prepare(a ) return dl def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]: __A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a ) __A : Tuple = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : int = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : str = create_accelerator(even_batches=a ) verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _SCREAMING_SNAKE_CASE ( ) -> str: __A : Optional[Any] = create_accelerator(even_batches=a ) __A : str = torch.nn.Linear(1 , 1 ) __A : Optional[int] = accelerator.prepare(a ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : str = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(a ): __A : Dict = ddp_model(batch[0].float() ) __A : List[str] = output.sum() loss.backward() batch_idxs.append(a ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , a ) assert "only supported for multi-GPU" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : int = True __A : Union[str, Any] = False __A : Optional[int] = create_accelerator(even_batches=a ) __A : int = torch.nn.Linear(1 , 1 ) __A : List[Any] = accelerator.prepare(a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : List[str] = train_dl.batch_sampler.even_batches __A : Dict = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Any = True __A : List[Any] = False __A : Tuple = create_accelerator(even_batches=a ) __A : List[str] = torch.nn.Linear(1 , 1 ) __A : Optional[Any] = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('ignore' ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : Tuple = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Any = create_accelerator() __A : Union[str, Any] = torch.nn.Linear(1 , 1 ) __A : str = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): pass assert issubclass(w[-1].category , a ) assert "only supported for map-style datasets" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : str = create_accelerator() accelerator.print('Test that even_batches variable ensures uniform batches across processes' ) test_default_ensures_even_batch_sizes() accelerator.print('Run tests with even_batches disabled' ) test_can_disable_even_batches() accelerator.print('Test joining uneven inputs' ) test_can_join_uneven_inputs() accelerator.print('Test overriding even_batches when joining uneven inputs' ) test_join_can_override_even_batches() accelerator.print('Test overriding even_batches for mixed dataloader types' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('Test join with non DDP distributed raises warning' ) __A : int = accelerator.state.distributed_type __A : Tuple = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(a ) __A : str = original_state if __name__ == "__main__": main()
77
1
import torch from transformers import CamembertForMaskedLM, CamembertTokenizer def _SCREAMING_SNAKE_CASE ( a , a , a , a=5 ) -> Dict: # Adapted from https://github.com/pytorch/fairseq/blob/master/fairseq/models/roberta/hub_interface.py assert masked_input.count('<mask>' ) == 1 __A : Tuple = torch.tensor(tokenizer.encode(a , add_special_tokens=a ) ).unsqueeze(0 ) # Batch size 1 __A : List[Any] = model(a )[0] # The last hidden-state is the first element of the output tuple __A : int = (input_ids.squeeze() == tokenizer.mask_token_id).nonzero().item() __A : str = logits[0, masked_index, :] __A : int = logits.softmax(dim=0 ) __A , __A : List[Any] = prob.topk(k=a , dim=0 ) __A : Dict = ' '.join( [tokenizer.convert_ids_to_tokens(indices[i].item() ) for i in range(len(a ) )] ) __A : List[str] = tokenizer.mask_token __A : List[Any] = [] for index, predicted_token_bpe in enumerate(topk_predicted_token_bpe.split(' ' ) ): __A : Optional[int] = predicted_token_bpe.replace('\u2581' , ' ' ) if " {0}".format(a ) in masked_input: topk_filled_outputs.append( ( masked_input.replace(' {0}'.format(a ) , a ), values[index].item(), predicted_token, ) ) else: topk_filled_outputs.append( ( masked_input.replace(a , a ), values[index].item(), predicted_token, ) ) return topk_filled_outputs UpperCAmelCase : str = CamembertTokenizer.from_pretrained('''camembert-base''') UpperCAmelCase : Any = CamembertForMaskedLM.from_pretrained('''camembert-base''') model.eval() UpperCAmelCase : Tuple = '''Le camembert est <mask> :)''' print(fill_mask(masked_input, model, tokenizer, topk=3))
77
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : str = { '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''', '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''', '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''', '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''', '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''', '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''', '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''', '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''', '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''', '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''', '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''', '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = '''codegen''' UpperCamelCase : List[str] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ): __A : Any = vocab_size __A : Tuple = n_ctx __A : Union[str, Any] = n_positions __A : Optional[Any] = n_embd __A : Any = n_layer __A : Dict = n_head __A : Union[str, Any] = n_inner __A : List[Any] = rotary_dim __A : str = activation_function __A : Any = resid_pdrop __A : Tuple = embd_pdrop __A : Tuple = attn_pdrop __A : Union[str, Any] = layer_norm_epsilon __A : str = initializer_range __A : Optional[Any] = use_cache __A : Union[str, Any] = bos_token_id __A : Tuple = eos_token_id super().__init__( bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A ) class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A = "default" , _A = None , _A = False , ): super().__init__(_A , task=_A , patching_specs=_A , use_past=_A ) if not getattr(self._config , 'pad_token_id' , _A ): # TODO: how to do that better? __A : Dict = 0 @property def UpperCAmelCase_ ( self ): __A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) __A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'} else: __A : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase_ ( self ): return self._config.n_layer @property def UpperCAmelCase_ ( self ): return self._config.n_head def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Any = super(_A , self ).generate_dummy_inputs( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) # We need to order the input in the way they appears in the forward() __A : str = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __A , __A : Any = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Any = seqlen + 2 __A : List[str] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __A : Optional[Any] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] __A : Tuple = common_inputs['attention_mask'] if self.use_past: __A : str = ordered_inputs['attention_mask'].dtype __A : List[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self ): return 13
77
1
# Algorithm for the pigeonhole sorting def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : Dict = min(a ) # min() finds the minimum value __A : str = max(a ) # max() finds the maximum value __A : str = 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 __A : List[Any] = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(a , a ), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. __A : List[Any] = 0 for count in range(a ): while holes[count] > 0: holes[count] -= 1 __A : Any = count + min_val i += 1 def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Tuple = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(a ) print('Sorted order is:' , ' '.join(a ) ) if __name__ == "__main__": main()
77
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase : List[Any] = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _A , ) super().__init__(*_A , **_A )
77
1
import requests from bsa import BeautifulSoup def _SCREAMING_SNAKE_CASE ( a = "AAPL" ) -> str: __A : int = F"""https://in.finance.yahoo.com/quote/{symbol}?s={symbol}""" __A : Any = BeautifulSoup(requests.get(a ).text , 'html.parser' ) __A : Optional[int] = 'My(6px) Pos(r) smartphone_Mt(6px)' return soup.find('div' , class_=class_ ).find('span' ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(F"""Current {symbol:<4} stock price is {stock_price(symbol):>8}""")
77
import glob import os import random from string import ascii_lowercase, digits import cva UpperCAmelCase : Dict = '''''' UpperCAmelCase : Union[str, Any] = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal) def _SCREAMING_SNAKE_CASE ( ) -> None: __A , __A : List[Any] = get_dataset(a , a ) print('Processing...' ) __A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a ) for index, image in enumerate(a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __A : Optional[int] = random_chars(32 ) __A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] __A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Success {index+1}/{len(a )} with {file_name}""" ) __A : int = [] for anno in new_annos[index]: __A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(a ) with open(F"""/{file_root}.txt""" , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]: __A : int = [] __A : List[Any] = [] for label_file in glob.glob(os.path.join(a , '*.txt' ) ): __A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(a ) as in_file: __A : Tuple = in_file.readlines() __A : Dict = os.path.join(a , F"""{label_name}.jpg""" ) __A : Dict = [] for obj_list in obj_lists: __A : int = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(a ) labels.append(a ) return img_paths, labels def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]: __A : int = [] __A : Optional[Any] = [] __A : Dict = [] for idx in range(len(a ) ): __A : Dict = [] __A : Optional[Any] = img_list[idx] path_list.append(a ) __A : Union[str, Any] = anno_list[idx] __A : Optional[Any] = cva.imread(a ) if flip_type == 1: __A : Any = cva.flip(a , a ) for bbox in img_annos: __A : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __A : Union[str, Any] = cva.flip(a , a ) for bbox in img_annos: __A : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(a ) new_imgs_list.append(a ) return new_imgs_list, new_annos_lists, path_list def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __A : List[Any] = ascii_lowercase + digits return "".join(random.choice(a ) for _ in range(a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
77
1
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() UpperCAmelCase : Optional[int] = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: __A : 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 _SCREAMING_SNAKE_CASE ( a , a ) -> int: for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) __A : Optional[Any] = state_dict.pop(F"""encoder.deit.blocks.{i}.attn.qkv.weight""" ) __A : int = in_proj_weight[ : encoder_config.hidden_size, : ] __A : List[str] = in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] __A : Tuple = in_proj_weight[ -encoder_config.hidden_size :, : ] def _SCREAMING_SNAKE_CASE ( a , a , a ) -> str: __A : Union[str, Any] = dct.pop(a ) __A : Optional[int] = val def _SCREAMING_SNAKE_CASE ( a ) -> Optional[Any]: if "handwritten" in checkpoint_url: __A : Tuple = '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: __A : Dict = 'https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg' __A : Optional[int] = Image.open(requests.get(a , stream=a ).raw ).convert('RGB' ) return im @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a ) -> Union[str, Any]: __A : Optional[int] = ViTConfig(image_size=3_84 , qkv_bias=a ) __A : Optional[int] = TrOCRConfig() # size of the architecture if "base" in checkpoint_url: __A : List[Any] = 7_68 elif "large" in checkpoint_url: # use ViT-large encoder __A : List[Any] = 10_24 __A : Dict = 40_96 __A : Optional[int] = 24 __A : Optional[int] = 16 __A : Union[str, Any] = 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: __A : List[Any] = False __A : List[Any] = 'relu' __A : List[Any] = 10_24 __A : List[Any] = True __A : int = False __A : Union[str, Any] = False # load HuggingFace model __A : int = ViTModel(a , add_pooling_layer=a ) __A : Any = TrOCRForCausalLM(a ) __A : Optional[Any] = VisionEncoderDecoderModel(encoder=a , decoder=a ) model.eval() # load state_dict of original model, rename some keys __A : Optional[int] = torch.hub.load_state_dict_from_url(a , map_location='cpu' , check_hash=a )['model'] __A : List[Any] = 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(): __A : List[str] = state_dict.pop(a ) if key.startswith('decoder' ) and "output_projection" not in key: __A : str = val else: __A : Dict = val # load state dict model.load_state_dict(a ) # Check outputs on an image __A : str = ViTImageProcessor(size=encoder_config.image_size ) __A : List[Any] = RobertaTokenizer.from_pretrained('roberta-large' ) __A : List[str] = TrOCRProcessor(a , a ) __A : Optional[Any] = processor(images=prepare_img(a ) , return_tensors='pt' ).pixel_values # verify logits __A : List[Any] = torch.tensor([[model.config.decoder.decoder_start_token_id]] ) __A : str = model(pixel_values=a , decoder_input_ids=a ) __A : List[str] = outputs.logits __A : Optional[Any] = torch.Size([1, 1, 5_02_65] ) if "trocr-base-handwritten" in checkpoint_url: __A : List[str] = torch.tensor( [-1.4_502, -4.6_683, -0.5_347, -2.9_291, 9.1_435, -3.0_571, 8.9_764, 1.7_560, 8.7_358, -1.5_311] ) elif "trocr-large-handwritten" in checkpoint_url: __A : Union[str, Any] = torch.tensor( [-2.6_437, -1.3_129, -2.2_596, -5.3_455, 6.3_539, 1.7_604, 5.4_991, 1.4_702, 5.6_113, 2.0_170] ) elif "trocr-base-printed" in checkpoint_url: __A : int = torch.tensor( [-5.6_816, -5.8_388, 1.1_398, -6.9_034, 6.8_505, -2.4_393, 1.2_284, -1.0_232, -1.9_661, -3.9_210] ) elif "trocr-large-printed" in checkpoint_url: __A : List[str] = torch.tensor( [-6.0_162, -7.0_959, 4.4_155, -5.1_063, 7.0_468, -3.1_631, 2.6_466, -0.3_081, -0.8_106, -1.7_535] ) 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__": UpperCAmelCase : List[Any] = 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.''' ) UpperCAmelCase : List[Any] = parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
77
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A: """simple docstring""" def __init__( self , _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.0_2 , _A=3 , _A=4 , _A=None , ): __A : Union[str, Any] = parent __A : List[str] = batch_size __A : Optional[int] = seq_length __A : List[Any] = is_training __A : Optional[Any] = use_input_mask __A : List[Any] = use_token_type_ids __A : Optional[Any] = use_labels __A : List[str] = vocab_size __A : Optional[int] = hidden_size __A : List[Any] = num_hidden_layers __A : int = num_attention_heads __A : Dict = intermediate_size __A : Any = hidden_act __A : Union[str, Any] = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : Optional[int] = max_position_embeddings __A : Dict = type_vocab_size __A : Any = type_sequence_label_size __A : Dict = initializer_range __A : str = num_labels __A : Union[str, Any] = num_choices __A : str = scope def UpperCAmelCase_ ( self ): __A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : Optional[Any] = None if self.use_input_mask: __A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __A : Dict = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = None __A : List[Any] = None __A : List[Any] = None if self.use_labels: __A : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __A : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[str] = LlamaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A , attention_mask=_A ) __A : Any = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Dict = True __A : int = LlamaModel(_A ) model.to(_A ) model.eval() __A : str = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __A : int = model( _A , attention_mask=_A , encoder_hidden_states=_A , ) __A : List[Any] = model(_A , attention_mask=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Optional[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : int = True __A : List[Any] = True __A : List[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() # first forward pass __A : Optional[Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , ) __A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __A : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) __A : str = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __A : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : str = torch.cat([input_mask, next_mask] , dim=-1 ) __A : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['hidden_states'][0] __A : Union[str, Any] = 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 __A : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() __A : Tuple = 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 UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Tuple = config_and_inputs __A : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () UpperCamelCase : Optional[Any] = (LlamaForCausalLM,) if is_torch_available() else () UpperCamelCase : Optional[Any] = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False def UpperCAmelCase_ ( self ): __A : List[Any] = LlamaModelTester(self ) __A : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : int = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() __A : str = 3 __A : Optional[int] = input_dict['input_ids'] __A : int = input_ids.ne(1 ).to(_A ) __A : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Union[str, Any] = 3 __A : Tuple = 'single_label_classification' __A : Union[str, Any] = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[int] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Any = 3 __A : int = 'multi_label_classification' __A : int = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __A : List[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def UpperCAmelCase_ ( self ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def UpperCAmelCase_ ( self , _A ): __A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Dict = ids_tensor([1, 10] , config.vocab_size ) __A : Union[str, Any] = 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 __A : List[Any] = LlamaModel(_A ) original_model.to(_A ) original_model.eval() __A : Dict = original_model(_A ).last_hidden_state __A : int = original_model(_A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : int = {'type': scaling_type, 'factor': 1_0.0} __A : str = LlamaModel(_A ) scaled_model.to(_A ) scaled_model.eval() __A : Dict = scaled_model(_A ).last_hidden_state __A : str = 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 ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) __A : Union[str, Any] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __A : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[str] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) __A : int = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) __A : Optional[int] = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : Optional[Any] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) __A : List[Any] = model(torch.tensor(_A ) ) __A : Tuple = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # fmt: off __A : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' __A : List[str] = 'Simply put, the theory of relativity states that ' __A : Union[str, Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) __A : List[str] = tokenizer.encode(_A , return_tensors='pt' ) __A : Tuple = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=_A ) # greedy generation outputs __A : Union[str, Any] = model.generate(_A , max_new_tokens=64 , top_p=_A , temperature=1 , do_sample=_A ) __A : List[str] = tokenizer.decode(generated_ids[0] , skip_special_tokens=_A ) self.assertEqual(_A , _A )
77
1
def _SCREAMING_SNAKE_CASE ( a , a ) -> int: while a != 0: __A , __A : str = b % a, a return b def _SCREAMING_SNAKE_CASE ( a , a ) -> int: if gcd(a , a ) != 1: __A : int = F"""mod inverse of {a!r} and {m!r} does not exist""" raise ValueError(a ) __A , __A , __A : Optional[int] = 1, 0, a __A , __A , __A : Optional[int] = 0, 1, m while va != 0: __A : int = ua // va __A , __A , __A , __A , __A , __A : Optional[int] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
77
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
1
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): debug_launcher(test_script.main ) def UpperCAmelCase_ ( self ): debug_launcher(test_ops.main )
77
import numpy as np from PIL import Image def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : Union[str, Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : List[Any] = 0 __A : Optional[Any] = 0 __A : List[Any] = 0 __A : Dict = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __A : Tuple = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : List[str] = 0 __A : Union[str, Any] = 0 return updated_arr def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : List[Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : Dict = 0 __A : str = 0 __A : Tuple = 0 __A : Optional[int] = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __A : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : Dict = 0 __A : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image UpperCAmelCase : int = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
77
1
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": UpperCAmelCase : str = pd.read_csv('''sample_data.csv''', header=None) UpperCAmelCase : str = df.shape[:1][0] # If you're using some other dataset input the target column UpperCAmelCase : Any = df.iloc[:, 1:2] UpperCAmelCase : str = actual_data.values.reshape(len_data, 1) UpperCAmelCase : Any = MinMaxScaler().fit_transform(actual_data) UpperCAmelCase : Tuple = 10 UpperCAmelCase : Tuple = 5 UpperCAmelCase : Union[str, Any] = 20 UpperCAmelCase : Optional[int] = len_data - periods * look_back UpperCAmelCase : int = actual_data[:division] UpperCAmelCase : List[Any] = actual_data[division - look_back :] UpperCAmelCase , UpperCAmelCase : int = [], [] UpperCAmelCase , UpperCAmelCase : Optional[int] = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) UpperCAmelCase : Tuple = np.array(train_x) UpperCAmelCase : Any = np.array(test_x) UpperCAmelCase : Tuple = np.array([list(i.ravel()) for i in train_y]) UpperCAmelCase : List[str] = np.array([list(i.ravel()) for i in test_y]) UpperCAmelCase : List[str] = Sequential() model.add(LSTM(1_28, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(1_28, 1))) model.add(Dense(forward_days)) model.compile(loss='''mean_squared_error''', optimizer='''adam''') UpperCAmelCase : int = model.fit( x_train, y_train, epochs=1_50, verbose=1, shuffle=True, batch_size=4 ) UpperCAmelCase : List[str] = model.predict(x_test)
77
from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float: __A : Any = x_start __A : List[str] = fnc(a ) __A : Optional[Any] = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area __A : Any = (x_end - x_start) / steps + xa __A : List[str] = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __A : Any = xa __A : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( a ) -> int: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') UpperCAmelCase : Tuple = 10 while i <= 10_00_00: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
77
1
import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn.grep_linear''': '''encoder.layers.*.attention.gru_rel_pos_linear''', '''self_attn.relative_attention_bias''': '''encoder.layers.*.attention.rel_attn_embed''', '''self_attn.grep_a''': '''encoder.layers.*.attention.gru_rel_pos_const''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase : Optional[int] = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Tuple: for attribute in key.split('.' ): __A : List[str] = getattr(a , a ) if weight_type is not None: __A : Dict = getattr(a , a ).shape else: __A : List[Any] = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __A : Dict = value elif weight_type == "weight_g": __A : List[Any] = value elif weight_type == "weight_v": __A : Any = value elif weight_type == "bias": __A : int = value else: __A : int = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _SCREAMING_SNAKE_CASE ( a , a ) -> List[Any]: __A : Optional[int] = [] __A : Optional[int] = fairseq_model.state_dict() __A : Optional[int] = hf_model.feature_extractor for name, value in fairseq_dict.items(): __A : List[str] = False if "conv_layers" in name: load_conv_layer( a , a , a , a , hf_model.config.feat_extract_norm == 'group' , ) __A : Union[str, Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __A : List[Any] = True if "*" in mapped_key: __A : str = name.split(a )[0].split('.' )[-2] __A : Any = mapped_key.replace('*' , a ) if "weight_g" in name: __A : Dict = 'weight_g' elif "weight_v" in name: __A : Optional[int] = 'weight_v' elif "bias" in name and "relative_attention_bias" not in name: __A : Dict = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __A : Union[str, Any] = 'weight' else: __A : List[Any] = None set_recursively(a , a , a , a , a ) continue if not is_used: unused_weights.append(a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Optional[Any]: __A : Union[str, Any] = full_name.split('conv_layers.' )[-1] __A : int = name.split('.' ) __A : Tuple = int(items[0] ) __A : Union[str, Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __A : Tuple = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) __A : Tuple = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a ) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a=None ) -> Dict: # load the pre-trained checkpoints __A : Optional[int] = torch.load(a ) __A : str = WavLMConfigOrig(checkpoint['cfg'] ) __A : Optional[int] = WavLMOrig(a ) model.load_state_dict(checkpoint['model'] ) model.eval() if config_path is not None: __A : Tuple = WavLMConfig.from_pretrained(a ) else: __A : Any = WavLMConfig() __A : Optional[int] = WavLMModel(a ) recursively_load_weights(a , a ) hf_wavlm.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') UpperCAmelCase : Optional[Any] = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
77
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def _SCREAMING_SNAKE_CASE ( ) -> None: print('Making key files...' ) make_key_files('rsa' , 10_24 ) print('Key files generation successful.' ) def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]: print('Generating prime p...' ) __A : Optional[Any] = rabinMiller.generate_large_prime(a ) print('Generating prime q...' ) __A : Union[str, Any] = rabinMiller.generate_large_prime(a ) __A : Tuple = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...' ) while True: __A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1: break print('Calculating d that is mod inverse of e...' ) __A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) ) __A : Dict = (n, e) __A : Dict = (n, d) return (public_key, private_key) def _SCREAMING_SNAKE_CASE ( a , a ) -> None: if os.path.exists(F"""{name}_pubkey.txt""" ) or os.path.exists(F"""{name}_privkey.txt""" ): print('\nWARNING:' ) print( F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n""" 'Use a different name or delete these files and re-run this program.' ) sys.exit() __A , __A : Optional[int] = generate_key(a ) print(F"""\nWriting public key to file {name}_pubkey.txt...""" ) with open(F"""{name}_pubkey.txt""" , 'w' ) as out_file: out_file.write(F"""{key_size},{public_key[0]},{public_key[1]}""" ) print(F"""Writing private key to file {name}_privkey.txt...""" ) with open(F"""{name}_privkey.txt""" , 'w' ) as out_file: out_file.write(F"""{key_size},{private_key[0]},{private_key[1]}""" ) if __name__ == "__main__": main()
77
1
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCAmelCase : List[str] = {'''tokenization_wav2vec2_phoneme''': ['''Wav2Vec2PhonemeCTCTokenizer''']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ProphetNetTokenizer UpperCamelCase : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() __A : Any = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = 'UNwant\u00E9d,running' __A : List[str] = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class(self.vocab_file ) __A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase_ ( self ): __A : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCAmelCase_ ( self ): __A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __A : Optional[int] = {} for i, token in enumerate(_A ): __A : Tuple = i __A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __A : str = tokenizer(_A , padding=_A , return_tensors='pt' ) self.assertIsInstance(_A , _A ) __A : List[str] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A ) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A ) __A : str = tokenizer.build_inputs_with_special_tokens(_A ) __A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
77
1
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _SCREAMING_SNAKE_CASE ( a = 8 ) -> str: __A : Union[str, Any] = ascii_letters + digits + punctuation return "".join(secrets.choice(a ) for _ in range(a ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(a ) __A : Union[str, Any] = i // 3 __A : Optional[int] = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) __A : Tuple = ( chars_incl + random(a , quotient + remainder ) + random(a , a ) + random(a , a ) ) __A : Dict = list(a ) shuffle(a ) return "".join(a ) # random is a generalised function for letters, characters and numbers def _SCREAMING_SNAKE_CASE ( a , a ) -> str: return "".join(secrets.choice(a ) for _ in range(a ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Tuple: pass # Put your code here... def _SCREAMING_SNAKE_CASE ( a , a ) -> Tuple: pass # Put your code here... def _SCREAMING_SNAKE_CASE ( a , a ) -> List[str]: pass # Put your code here... def _SCREAMING_SNAKE_CASE ( a , a = 8 ) -> bool: if len(a ) < min_length: # Your Password must be at least 8 characters long return False __A : Optional[Any] = any(char in ascii_uppercase for char in password ) __A : Optional[Any] = any(char in ascii_lowercase for char in password ) __A : List[Any] = any(char in digits for char in password ) __A : List[Any] = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Optional[Any] = int(input('Please indicate the max length of your password: ' ).strip() ) __A : str = input( 'Please indicate the characters that must be in your password: ' ).strip() print('Password generated:' , password_generator(a ) ) print( 'Alternative Password generated:' , alternative_password_generator(a , a ) , ) print('[If you are thinking of using this passsword, You better save it.]' ) if __name__ == "__main__": main()
77
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Optional[int] = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } UpperCAmelCase : List[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = BertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : Any = getattr(_A , normalizer_state.pop('type' ) ) __A : Union[str, Any] = do_lower_case __A : Optional[int] = strip_accents __A : List[Any] = tokenize_chinese_chars __A : int = normalizer_class(**_A ) __A : Union[str, Any] = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : Tuple = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[Any] = [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : int = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
1
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class _A: """simple docstring""" 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.0_2 , _A=3 , _A=4 , _A=None , ): __A : Tuple = parent __A : Optional[Any] = batch_size __A : int = seq_length __A : Dict = is_training __A : List[str] = use_input_mask __A : List[Any] = use_token_type_ids __A : List[Any] = use_labels __A : Optional[Any] = vocab_size __A : int = hidden_size __A : List[Any] = num_hidden_layers __A : Optional[Any] = num_attention_heads __A : Tuple = intermediate_size __A : Optional[Any] = hidden_act __A : Any = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : Union[str, Any] = max_position_embeddings __A : Tuple = type_vocab_size __A : List[Any] = type_sequence_label_size __A : Any = initializer_range __A : Any = num_labels __A : Optional[Any] = num_choices __A : Any = scope def UpperCAmelCase_ ( self ): __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : List[str] = None if self.use_input_mask: __A : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __A : Tuple = None if self.use_token_type_ids: __A : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = None __A : Union[str, Any] = None __A : str = None if self.use_labels: __A : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : str = ids_tensor([self.batch_size] , self.num_choices ) __A : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return BioGptConfig( 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 , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : int = BioGptModel(config=_A ) model.to(_A ) model.eval() __A : Optional[Any] = model(_A , attention_mask=_A ) __A : Tuple = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Any = BioGptForCausalLM(config=_A ) model.to(_A ) model.eval() __A : Union[str, Any] = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , *_A ): __A : Any = BioGptModel(config=_A ) model.to(_A ) model.eval() # create attention mask __A : Optional[int] = torch.ones(input_ids.shape , dtype=torch.long , device=_A ) __A : Optional[int] = self.seq_length // 2 __A : List[Any] = 0 # first forward pass __A , __A : Optional[int] = model(_A , attention_mask=_A ).to_tuple() # create hypothetical next token and extent to next_input_ids __A : int = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __A : Dict = ids_tensor((1,) , _A ).item() + 1 __A : List[Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __A : int = random_other_next_tokens # append to next input_ids and attn_mask __A : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : int = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=_A )] , dim=1 , ) # get two different outputs __A : Optional[Any] = model(_A , attention_mask=_A )['last_hidden_state'] __A : Any = model(_A , past_key_values=_A , attention_mask=_A )['last_hidden_state'] # select random slice __A : Union[str, Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : int = output_from_no_past[:, -1, random_slice_idx].detach() __A : Dict = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_A , _A , atol=1e-3 ) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , *_A ): __A : str = BioGptModel(config=_A ).to(_A ).eval() __A : Optional[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=_A ) # first forward pass __A : Optional[Any] = model(_A , attention_mask=_A , use_cache=_A ) __A , __A : List[Any] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __A : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) __A : Tuple = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __A : Union[str, Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : Any = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __A : Union[str, Any] = model(_A , attention_mask=_A )['last_hidden_state'] __A : Any = model(_A , attention_mask=_A , past_key_values=_A )[ 'last_hidden_state' ] # select random slice __A : List[str] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : Dict = output_from_no_past[:, -3:, random_slice_idx].detach() __A : List[Any] = 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 UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , *_A , _A=False ): __A : int = BioGptForCausalLM(_A ) model.to(_A ) if gradient_checkpointing: model.gradient_checkpointing_enable() __A : List[Any] = model(_A , labels=_A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ ( self , _A , *_A ): __A : List[str] = BioGptModel(_A ) __A : Optional[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.0_0_1 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.0_1 ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , *_A ): __A : List[str] = self.num_labels __A : List[Any] = BioGptForTokenClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , token_type_ids=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Any = config_and_inputs __A : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) UpperCamelCase : Union[str, Any] = (BioGptForCausalLM,) if is_torch_available() else () UpperCamelCase : List[Any] = ( { '''feature-extraction''': BioGptModel, '''text-classification''': BioGptForSequenceClassification, '''text-generation''': BioGptForCausalLM, '''token-classification''': BioGptForTokenClassification, '''zero-shot''': BioGptForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : Any = False def UpperCAmelCase_ ( self ): __A : Optional[int] = BioGptModelTester(self ) __A : Tuple = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Any = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : int = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*_A ) def UpperCAmelCase_ ( self ): __A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*_A , gradient_checkpointing=_A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*_A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*_A ) def UpperCAmelCase_ ( self ): __A : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*_A ) @slow def UpperCAmelCase_ ( self ): __A : List[str] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(_A ) __A : Tuple = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) __A : Dict = 'left' # Define PAD Token = EOS Token = 50256 __A : int = tokenizer.eos_token __A : Any = model.config.eos_token_id # use different length sentences to test batching __A : Optional[Any] = [ 'Hello, my dog is a little', 'Today, I', ] __A : int = tokenizer(_A , return_tensors='pt' , padding=_A ) __A : Dict = inputs['input_ids'].to(_A ) __A : Tuple = model.generate( input_ids=_A , attention_mask=inputs['attention_mask'].to(_A ) , ) __A : int = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(_A ) __A : Optional[int] = model.generate(input_ids=_A ) __A : Any = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() __A : Optional[int] = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(_A ) __A : Optional[int] = model.generate(input_ids=_A , max_length=model.config.max_length - num_paddings ) __A : Any = tokenizer.batch_decode(_A , skip_special_tokens=_A ) __A : str = tokenizer.decode(output_non_padded[0] , skip_special_tokens=_A ) __A : List[str] = tokenizer.decode(output_padded[0] , skip_special_tokens=_A ) __A : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(_A , _A ) self.assertListEqual(_A , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ ( self ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A : List[str] = BioGptModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def UpperCAmelCase_ ( self ): __A , __A : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Optional[int] = 3 __A : List[Any] = input_dict['input_ids'] __A : Optional[int] = input_ids.ne(1 ).to(_A ) __A : Optional[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[int] = BioGptForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[str] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : List[str] = self.model_tester.prepare_config_and_inputs_for_common() __A : Optional[Any] = 3 __A : List[Any] = 'multi_label_classification' __A : Union[str, Any] = input_dict['input_ids'] __A : int = input_ids.ne(1 ).to(_A ) __A : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __A : Dict = BioGptForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Dict = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ ( self ): __A : int = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) __A : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) __A : List[str] = model(_A )[0] __A : Tuple = 42384 __A : int = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , _A ) __A : Union[str, Any] = torch.tensor( [[[-9.5_2_3_6, -9.8_9_1_8, 1_0.4_5_5_7], [-1_1.0_4_6_9, -9.6_4_2_3, 8.1_0_2_2], [-8.8_6_6_4, -7.8_8_2_6, 5.5_3_2_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _A , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): __A : List[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) __A : List[str] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(_A ) torch.manual_seed(0 ) __A : Any = tokenizer('COVID-19 is' , return_tensors='pt' ).to(_A ) __A : Dict = model.generate( **_A , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=_A , ) __A : Optional[Any] = tokenizer.decode(output_ids[0] , skip_special_tokens=_A ) __A : Dict = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(_A , _A )
77
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): debug_launcher(test_script.main ) def UpperCAmelCase_ ( self ): debug_launcher(test_ops.main )
77
1
from __future__ import annotations import time UpperCAmelCase : Optional[int] = list[tuple[int, int]] UpperCAmelCase : str = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] UpperCAmelCase : Any = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class _A: """simple docstring""" def __init__( self , _A , _A , _A , _A , _A ): __A : Union[str, Any] = pos_x __A : List[Any] = pos_y __A : Tuple = (pos_y, pos_x) __A : Union[str, Any] = goal_x __A : Optional[Any] = goal_y __A : Any = parent class _A: """simple docstring""" def __init__( self , _A , _A ): __A : Union[str, Any] = Node(start[1] , start[0] , goal[1] , goal[0] , _A ) __A : Optional[Any] = Node(goal[1] , goal[0] , goal[1] , goal[0] , _A ) __A : List[Any] = [self.start] __A : List[str] = False def UpperCAmelCase_ ( self ): while self.node_queue: __A : Union[str, Any] = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: __A : Union[str, Any] = True return self.retrace_path(_A ) __A : Optional[int] = self.get_successors(_A ) for node in successors: self.node_queue.append(_A ) if not self.reached: return [self.start.pos] return None def UpperCAmelCase_ ( self , _A ): __A : Any = [] for action in delta: __A : str = parent.pos_x + action[1] __A : List[Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_A ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(_A , _A , self.target.pos_y , self.target.pos_x , _A ) ) return successors def UpperCAmelCase_ ( self , _A ): __A : Any = node __A : Union[str, Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) __A : str = current_node.parent path.reverse() return path class _A: """simple docstring""" def __init__( self , _A , _A ): __A : Union[str, Any] = BreadthFirstSearch(_A , _A ) __A : Dict = BreadthFirstSearch(_A , _A ) __A : Optional[Any] = False def UpperCAmelCase_ ( self ): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __A : str = self.fwd_bfs.node_queue.pop(0 ) __A : Optional[Any] = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: __A : List[str] = True return self.retrace_bidirectional_path( _A , _A ) __A : Any = current_bwd_node __A : Optional[int] = current_fwd_node __A : List[Any] = { self.fwd_bfs: self.fwd_bfs.get_successors(_A ), self.bwd_bfs: self.bwd_bfs.get_successors(_A ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(_A ) if not self.reached: return [self.fwd_bfs.start.pos] return None def UpperCAmelCase_ ( self , _A , _A ): __A : Optional[int] = self.fwd_bfs.retrace_path(_A ) __A : List[str] = self.bwd_bfs.retrace_path(_A ) bwd_path.pop() bwd_path.reverse() __A : Dict = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() UpperCAmelCase : List[Any] = (0, 0) UpperCAmelCase : Dict = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) UpperCAmelCase : Optional[Any] = time.time() UpperCAmelCase : int = BreadthFirstSearch(init, goal) UpperCAmelCase : int = bfs.search() UpperCAmelCase : Union[str, Any] = time.time() - start_bfs_time print('''Unidirectional BFS computation time : ''', bfs_time) UpperCAmelCase : Dict = time.time() UpperCAmelCase : str = BidirectionalBreadthFirstSearch(init, goal) UpperCAmelCase : Optional[int] = bd_bfs.search() UpperCAmelCase : List[str] = time.time() - start_bd_bfs_time print('''Bidirectional BFS computation time : ''', bd_bfs_time)
77
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Tuple = tempfile.mkdtemp() # fmt: off __A : Union[str, Any] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Dict = dict(zip(_A , range(len(_A ) ) ) ) __A : int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : Optional[Any] = {'unk_token': '<unk>'} __A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : Union[str, Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : List[str] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[str] = self.get_tokenizer() __A : Dict = self.get_rust_tokenizer() __A : Optional[Any] = self.get_image_processor() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Any = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : int = self.get_image_processor(do_normalize=_A ) __A : int = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : List[Any] = self.prepare_image_inputs() __A : Any = image_processor(_A , return_tensors='np' ) __A : Tuple = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_image_processor() __A : int = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = 'lower newer' __A : Any = processor(text=_A , return_tensors='np' ) __A : Dict = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Tuple = 'lower newer' __A : Union[str, Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[int] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Any = ['cat', 'nasa badge'] __A : List[Any] = processor(text=_A ) __A : Dict = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : int = [['cat', 'nasa badge'], ['person']] __A : str = processor(text=_A ) __A : int = 16 __A : Optional[int] = len(_A ) __A : int = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : int = 'google/owlvit-base-patch32' __A : List[str] = OwlViTProcessor.from_pretrained(_A ) __A : Tuple = ['cat', 'nasa badge'] __A : Dict = processor(text=_A ) __A : Tuple = 16 __A : str = inputs['input_ids'] __A : str = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Dict = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = self.prepare_image_inputs() __A : Tuple = self.prepare_image_inputs() __A : Any = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Union[str, Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
77
1
def _SCREAMING_SNAKE_CASE ( a , a ) -> str: __A : List[str] = '' for word_or_phrase in separated: if not isinstance(a , a ): raise Exception('join() accepts only strings to be joined' ) joined += word_or_phrase + separator return joined.strip(a ) if __name__ == "__main__": from doctest import testmod testmod()
77
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase : Union[str, Any] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Tuple: for attribute in key.split('.' ): __A : Dict = getattr(a , a ) if weight_type is not None: __A : Any = getattr(a , a ).shape else: __A : Any = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __A : Union[str, Any] = value elif weight_type == "weight_g": __A : Dict = value elif weight_type == "weight_v": __A : Optional[int] = value elif weight_type == "bias": __A : int = value elif weight_type == "running_mean": __A : Union[str, Any] = value elif weight_type == "running_var": __A : Union[str, Any] = value elif weight_type == "num_batches_tracked": __A : Any = value elif weight_type == "inv_freq": __A : Optional[Any] = value else: __A : int = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]: __A : Any = [] __A : Optional[int] = fairseq_model.state_dict() __A : Union[str, Any] = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __A : int = False if "conv_layers" in name: load_conv_layer( a , a , a , a , hf_model.config.feat_extract_norm == 'group' , ) __A : Optional[int] = True else: for key, mapped_key in MAPPING.items(): __A : Any = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __A : Optional[Any] = True if "*" in mapped_key: __A : str = name.split(a )[0].split('.' )[-2] __A : int = mapped_key.replace('*' , a ) if "pos_bias_u" in name: __A : Optional[int] = None elif "pos_bias_v" in name: __A : Dict = None elif "weight_g" in name: __A : Optional[Any] = 'weight_g' elif "weight_v" in name: __A : Dict = 'weight_v' elif "bias" in name: __A : Tuple = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __A : int = 'weight' elif "running_mean" in name: __A : str = 'running_mean' elif "inv_freq" in name: __A : List[Any] = 'inv_freq' elif "running_var" in name: __A : Union[str, Any] = 'running_var' elif "num_batches_tracked" in name: __A : Optional[Any] = 'num_batches_tracked' else: __A : List[str] = None set_recursively(a , a , a , a , a ) continue if not is_used: unused_weights.append(a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Any: __A : str = full_name.split('conv_layers.' )[-1] __A : str = name.split('.' ) __A : Dict = int(items[0] ) __A : Any = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) __A : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) __A : List[str] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a ) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a=None , a=None , a=True ) -> Any: if config_path is not None: __A : Tuple = WavaVecaConformerConfig.from_pretrained(a , hidden_act='swish' ) else: __A : Optional[Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: __A : Dict = 'rotary' if is_finetuned: if dict_path: __A : Dict = Dictionary.load(a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __A : int = target_dict.pad_index __A : List[Any] = target_dict.bos_index __A : Any = target_dict.eos_index __A : Dict = len(target_dict.symbols ) __A : Optional[Any] = os.path.join(a , 'vocab.json' ) if not os.path.isdir(a ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(a ) ) return os.makedirs(a , exist_ok=a ) __A : List[str] = target_dict.indices # fairseq has the <pad> and <s> switched __A : int = 0 __A : Optional[Any] = 1 with open(a , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(a , a ) __A : Optional[Any] = WavaVecaCTCTokenizer( a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=a , ) __A : Tuple = True if config.feat_extract_norm == 'layer' else False __A : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=a , return_attention_mask=a , ) __A : Optional[int] = WavaVecaProcessor(feature_extractor=a , tokenizer=a ) processor.save_pretrained(a ) __A : List[Any] = WavaVecaConformerForCTC(a ) else: __A : List[Any] = WavaVecaConformerForPreTraining(a ) if is_finetuned: __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: __A : Optional[Any] = argparse.Namespace(task='audio_pretraining' ) __A : str = fairseq.tasks.setup_task(a ) __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=a ) __A : Tuple = model[0].eval() recursively_load_weights(a , a , not is_finetuned ) hf_wavavec.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) UpperCAmelCase : List[str] = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
77
1
from ..utils import DummyObject, requires_backends class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Any = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[int] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[int] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : str = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Any = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : int = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) def _SCREAMING_SNAKE_CASE ( *a , **a ) -> List[str]: requires_backends(a , ['torch'] ) def _SCREAMING_SNAKE_CASE ( *a , **a ) -> Optional[Any]: requires_backends(a , ['torch'] ) def _SCREAMING_SNAKE_CASE ( *a , **a ) -> Optional[Any]: requires_backends(a , ['torch'] ) def _SCREAMING_SNAKE_CASE ( *a , **a ) -> Optional[int]: requires_backends(a , ['torch'] ) def _SCREAMING_SNAKE_CASE ( *a , **a ) -> Dict: requires_backends(a , ['torch'] ) def _SCREAMING_SNAKE_CASE ( *a , **a ) -> Optional[int]: requires_backends(a , ['torch'] ) def _SCREAMING_SNAKE_CASE ( *a , **a ) -> Tuple: requires_backends(a , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : int = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[int] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Dict = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : str = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : List[Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[int] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : str = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : int = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[int] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : str = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : List[Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Any = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : List[Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : List[Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Any = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : str = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Any = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[int] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : str = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : int = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) class _A( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : Optional[int] = ['''torch'''] def __init__( self , *_A , **_A ): requires_backends(self , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] ) @classmethod def UpperCAmelCase_ ( cls , *_A , **_A ): requires_backends(cls , ['torch'] )
77
from abc import ABC, abstractmethod from argparse import ArgumentParser class _A( snake_case__ ): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( _A ): raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self ): raise NotImplementedError()
77
1
import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[Any] = ['''input_ids''', '''attention_mask'''] def __init__( self , _A="</s>" , _A="<unk>" , _A="<pad>" , _A=125 , _A=None , **_A , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __A : Any = [F"""<extra_id_{i}>""" for i in range(_A )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __A : str = len(set(filter(lambda _A : bool('extra_id' in str(_A ) ) , _A ) ) ) if extra_tokens != extra_ids: raise ValueError( F"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" ' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the' ' extra_ids tokens' ) __A : Optional[int] = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else pad_token __A : int = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else eos_token __A : str = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else unk_token super().__init__( eos_token=_A , unk_token=_A , pad_token=_A , extra_ids=_A , additional_special_tokens=_A , **_A , ) __A : List[Any] = extra_ids __A : List[Any] = 2**8 # utf is 8 bits # define special tokens dict __A : Dict[int, str] = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } __A : Optional[int] = len(self.special_tokens_encoder ) __A : Tuple = len(_A ) for i, token in enumerate(_A ): __A : Any = self.vocab_size + i - n __A : Dict[str, int] = {v: k for k, v in self.special_tokens_encoder.items()} @property def UpperCAmelCase_ ( self ): return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def UpperCAmelCase_ ( self , _A , _A = None , _A = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_A )) + [1] return ([0] * len(_A )) + [1] + ([0] * len(_A )) + [1] def UpperCAmelCase_ ( self , _A ): if len(_A ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated""" ' eos tokens being added.' ) return token_ids else: return token_ids + [self.eos_token_id] def UpperCAmelCase_ ( self , _A , _A = None ): __A : Tuple = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def UpperCAmelCase_ ( self , _A , _A = None ): __A : Tuple = self._add_eos_if_not_present(_A ) if token_ids_a is None: return token_ids_a else: __A : int = self._add_eos_if_not_present(_A ) return token_ids_a + token_ids_a def UpperCAmelCase_ ( self , _A ): __A : Optional[int] = [chr(_A ) for i in text.encode('utf-8' )] return tokens def UpperCAmelCase_ ( self , _A ): if token in self.special_tokens_encoder: __A : Optional[int] = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: __A : Optional[Any] = self.added_tokens_encoder[token] elif len(_A ) != 1: __A : Any = self.unk_token_id else: __A : str = ord(_A ) + self._num_special_tokens return token_id def UpperCAmelCase_ ( self , _A ): if index in self.special_tokens_decoder: __A : Any = self.special_tokens_decoder[index] else: __A : Dict = chr(index - self._num_special_tokens ) return token def UpperCAmelCase_ ( self , _A ): __A : List[str] = b'' for token in tokens: if token in self.special_tokens_decoder: __A : List[Any] = self.special_tokens_decoder[token].encode('utf-8' ) elif token in self.added_tokens_decoder: __A : Tuple = self.special_tokens_decoder[token].encode('utf-8' ) elif token in self.special_tokens_encoder: __A : Optional[int] = token.encode('utf-8' ) elif token in self.added_tokens_encoder: __A : Optional[Any] = token.encode('utf-8' ) else: __A : Tuple = bytes([ord(_A )] ) bstring += tok_string __A : int = bstring.decode('utf-8' , errors='ignore' ) return string def UpperCAmelCase_ ( self , _A , _A = None ): return ()
77
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
1
import pytest UpperCAmelCase : int = '''__dummy_dataset1__''' UpperCAmelCase : Union[str, Any] = ''' import json import os import datasets REPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/" URLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"} class __DummyDataset1__(datasets.GeneratorBasedBuilder): def _info(self): features = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string")), "ner_tags": datasets.Sequence( datasets.features.ClassLabel( names=[ "O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", ] ) ), "langs": datasets.Sequence(datasets.Value("string")), "spans": datasets.Sequence(datasets.Value("string")), } ) return datasets.DatasetInfo(features=features) def _split_generators(self, dl_manager): dl_path = dl_manager.download(URLS) return [ datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}), datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}), ] def _generate_examples(self, filepath): with open(filepath, "r", encoding="utf-8") as f: for i, line in enumerate(f): yield i, json.loads(line) ''' @pytest.fixture def _SCREAMING_SNAKE_CASE ( ) -> Dict: return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def _SCREAMING_SNAKE_CASE ( ) -> List[str]: return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def _SCREAMING_SNAKE_CASE ( a , a , a ) -> str: __A : Optional[Any] = dataset_loading_script_name __A : int = tmp_path / 'datasets' / script_name script_dir.mkdir(parents=a ) __A : Union[str, Any] = script_dir / F"""{script_name}.py""" with open(a , 'w' ) as f: f.write(a ) return str(a )
77
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = ShapEPipeline UpperCamelCase : str = ['''prompt'''] UpperCamelCase : Tuple = ['''prompt'''] UpperCamelCase : Optional[int] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] UpperCamelCase : int = False @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self ): return 8 @property def UpperCAmelCase_ ( self ): __A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_A ) @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : int = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __A : Optional[Any] = PriorTransformer(**_A ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : List[str] = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __A : List[Any] = ShapERenderer(**_A ) return model def UpperCAmelCase_ ( self ): __A : List[str] = self.dummy_prior __A : Optional[int] = self.dummy_text_encoder __A : List[Any] = self.dummy_tokenizer __A : str = self.dummy_renderer __A : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=_A , clip_sample=_A , clip_sample_range=1.0 , ) __A : Any = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): if str(_A ).startswith('mps' ): __A : List[Any] = torch.manual_seed(_A ) else: __A : Dict = torch.Generator(device=_A ).manual_seed(_A ) __A : int = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def UpperCAmelCase_ ( self ): __A : Tuple = 'cpu' __A : Any = self.get_dummy_components() __A : Tuple = self.pipeline_class(**_A ) __A : List[str] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Tuple = pipe(**self.get_dummy_inputs(_A ) ) __A : int = output.images[0] __A : str = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __A : Any = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCAmelCase_ ( self ): __A : List[str] = torch_device == 'cpu' __A : Any = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_A , relax_max_difference=_A , ) def UpperCAmelCase_ ( self ): __A : Any = self.get_dummy_components() __A : Any = self.pipeline_class(**_A ) __A : Dict = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Any = 1 __A : Dict = 2 __A : Tuple = self.get_dummy_inputs(_A ) for key in inputs.keys(): if key in self.batch_params: __A : Optional[int] = batch_size * [inputs[key]] __A : Optional[int] = pipe(**_A , num_images_per_prompt=_A )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __A : Dict = ShapEPipeline.from_pretrained('openai/shap-e' ) __A : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : str = torch.Generator(device=_A ).manual_seed(0 ) __A : Tuple = pipe( 'a shark' , generator=_A , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_A , _A )
77
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : List[Any] = { '''facebook/convnextv2-tiny-1k-224''': '''https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json''', } class _A( snake_case__ , snake_case__ ): """simple docstring""" UpperCamelCase : List[Any] = '''convnextv2''' def __init__( self , _A=3 , _A=4 , _A=4 , _A=None , _A=None , _A="gelu" , _A=0.0_2 , _A=1e-1_2 , _A=0.0 , _A=224 , _A=None , _A=None , **_A , ): super().__init__(**_A ) __A : List[str] = num_channels __A : Optional[Any] = patch_size __A : Any = num_stages __A : str = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __A : Optional[Any] = [3, 3, 9, 3] if depths is None else depths __A : int = hidden_act __A : Union[str, Any] = initializer_range __A : List[str] = layer_norm_eps __A : str = drop_path_rate __A : Union[str, Any] = image_size __A : Tuple = ['stem'] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] __A , __A : int = get_aligned_output_features_output_indices( out_features=_A , out_indices=_A , stage_names=self.stage_names )
77
from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if len(a ) != 2 or len(a[0] ) != 2 or len(a ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __A : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> str: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a ) -> tuple[list, list, list, list]: if len(a ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __A : str = len(a ) __A : List[Any] = matrix_length // 2 __A : List[str] = [[a[i][j] for j in range(a , a )] for i in range(a )] __A : Dict = [ [a[i][j] for j in range(a , a )] for i in range(a , a ) ] __A : int = [[a[i][j] for j in range(a )] for i in range(a )] __A : Any = [[a[i][j] for j in range(a )] for i in range(a , a )] return top_left, top_right, bot_left, bot_right def _SCREAMING_SNAKE_CASE ( a ) -> tuple[int, int]: return len(a ), len(matrix[0] ) def _SCREAMING_SNAKE_CASE ( a ) -> None: print('\n'.join(str(a ) for line in matrix ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a ) == (2, 2): return default_matrix_multiplication(a , a ) __A , __A , __A , __A : str = split_matrix(a ) __A , __A , __A , __A : List[Any] = split_matrix(a ) __A : Any = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Tuple = actual_strassen(matrix_addition(a , a ) , a ) __A : List[str] = actual_strassen(matrix_addition(a , a ) , a ) __A : Optional[int] = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Any = actual_strassen(matrix_addition(a , a ) , matrix_addition(a , a ) ) __A : Any = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = matrix_addition(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) __A : Union[str, Any] = matrix_addition(a , a ) __A : str = matrix_addition(a , a ) __A : Dict = matrix_subtraction(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) # construct the new matrix from our 4 quadrants __A : List[Any] = [] for i in range(len(a ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(a ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a )[1] != matrix_dimensions(a )[0]: __A : Dict = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"""Matrix A: {matrixa}\n""" F"""Matrix B: {matrixa}""" ) raise Exception(a ) __A : int = matrix_dimensions(a ) __A : Any = matrix_dimensions(a ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __A : List[Any] = max(*a , *a ) __A : Optional[Any] = int(math.pow(2 , math.ceil(math.loga(a ) ) ) ) __A : Union[str, Any] = matrixa __A : Optional[int] = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __A : str = actual_strassen(a , a ) # Removing the additional zeros for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] UpperCAmelCase : Optional[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
77
1
from typing import Any class _A: """simple docstring""" def __init__( self , _A ): __A : str = data __A : Union[str, Any] = None class _A: """simple docstring""" def __init__( self ): __A : Dict = None def UpperCAmelCase_ ( self ): __A : Optional[int] = self.head while temp is not None: print(temp.data , end=' ' ) __A : Optional[Any] = temp.next print() def UpperCAmelCase_ ( self , _A ): __A : Any = Node(_A ) __A : str = self.head __A : Optional[int] = new_node def UpperCAmelCase_ ( self , _A , _A ): if node_data_a == node_data_a: return else: __A : List[str] = self.head while node_a is not None and node_a.data != node_data_a: __A : str = node_a.next __A : List[Any] = self.head while node_a is not None and node_a.data != node_data_a: __A : List[Any] = node_a.next if node_a is None or node_a is None: return __A , __A : Optional[int] = node_a.data, node_a.data if __name__ == "__main__": UpperCAmelCase : Any = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('''After swapping''') ll.print_list()
77
def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : List[str] = [] __A : Tuple = [] __A : Union[str, Any] = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, } # Priority of each operator __A : List[str] = len(a ) if (len(a ) > 7) else 7 # Print table header for output print( 'Symbol'.center(8 ) , 'Stack'.center(a ) , 'Postfix'.center(a ) , sep=' | ' , ) print('-' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(a ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(a ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(a ) == 0: stack.append(a ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(a ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(a ) # push x to stack print( x.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format while len(a ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ' '.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format return "".join(a ) # return Postfix as str def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : List[Any] = list(infix[::-1] ) # reverse the infix equation for i in range(len(a ) ): if infix[i] == "(": __A : List[str] = ')' # change "(" to ")" elif infix[i] == ")": __A : Any = '(' # change ")" to "(" return (infix_2_postfix(''.join(a ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": UpperCAmelCase : List[str] = input('''\nEnter an Infix Equation = ''') # Input an Infix equation UpperCAmelCase : Union[str, Any] = ''''''.join(Infix.split()) # Remove spaces from the input print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
77
1
UpperCAmelCase : str = '''Alexander Joslin''' import operator as op from .stack import Stack def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : Tuple = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} __A : Stack[int] = Stack() __A : Stack[str] = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(a ) ) elif i in operators: # RULE 2 operator_stack.push(a ) elif i == ")": # RULE 4 __A : Any = operator_stack.peek() operator_stack.pop() __A : List[str] = operand_stack.peek() operand_stack.pop() __A : Tuple = operand_stack.peek() operand_stack.pop() __A : Any = operators[opr](a , a ) operand_stack.push(a ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": UpperCAmelCase : int = '''(5 + ((4 * 2) * (2 + 3)))''' # answer = 45 print(F"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
77
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : Tuple = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json''' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase : int = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = '''mask2former''' UpperCamelCase : Any = ['''swin'''] UpperCamelCase : Union[str, Any] = {'''hidden_size''': '''hidden_dim'''} def __init__( self , _A = None , _A = 256 , _A = 256 , _A = 256 , _A = 1024 , _A = "relu" , _A = 6 , _A = 10 , _A = 8 , _A = 0.0 , _A = 2048 , _A = False , _A = False , _A = 4 , _A = 255 , _A = 100 , _A = 0.1 , _A = 2.0 , _A = 5.0 , _A = 5.0 , _A = 12544 , _A = 3.0 , _A = 0.7_5 , _A = 0.0_2 , _A = 1.0 , _A = True , _A = [4, 8, 16, 32] , _A = None , **_A , ): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) __A : Optional[int] = CONFIG_MAPPING['swin']( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=_A , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(_A , _A ): __A : Dict = backbone_config.pop('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[str] = config_class.from_dict(_A ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) __A : Optional[int] = backbone_config __A : Optional[Any] = feature_size __A : Any = mask_feature_size __A : Optional[Any] = hidden_dim __A : Union[str, Any] = encoder_feedforward_dim __A : Optional[Any] = activation_function __A : List[Any] = encoder_layers __A : Union[str, Any] = decoder_layers __A : Dict = num_attention_heads __A : Tuple = dropout __A : Dict = dim_feedforward __A : Tuple = pre_norm __A : Dict = enforce_input_projection __A : Optional[int] = common_stride __A : Optional[Any] = ignore_value __A : str = num_queries __A : List[Any] = no_object_weight __A : List[str] = class_weight __A : List[Any] = mask_weight __A : List[Any] = dice_weight __A : Tuple = train_num_points __A : Optional[Any] = oversample_ratio __A : Union[str, Any] = importance_sample_ratio __A : Union[str, Any] = init_std __A : int = init_xavier_std __A : Union[str, Any] = use_auxiliary_loss __A : Union[str, Any] = feature_strides __A : List[Any] = output_auxiliary_logits __A : Optional[Any] = decoder_layers super().__init__(**_A ) @classmethod def UpperCAmelCase_ ( cls , _A , **_A ): return cls( backbone_config=_A , **_A , ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = copy.deepcopy(self.__dict__ ) __A : List[Any] = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output
77
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=13 , _A=3 , _A=224 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , ): __A : int = size if size is not None else {'height': 18, 'width': 18} __A : int = parent __A : int = batch_size __A : Tuple = num_channels __A : List[Any] = image_size __A : str = min_resolution __A : Optional[Any] = max_resolution __A : str = do_resize __A : Any = size __A : Any = do_normalize __A : Dict = image_mean __A : Optional[int] = image_std def UpperCAmelCase_ ( self ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : str = ViTImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : str = EfficientFormerImageProcessorTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_proc_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'image_mean' ) ) self.assertTrue(hasattr(_A , 'image_std' ) ) self.assertTrue(hasattr(_A , 'do_normalize' ) ) self.assertTrue(hasattr(_A , 'do_resize' ) ) self.assertTrue(hasattr(_A , 'size' ) ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processor __A : int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : Optional[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : Tuple = image_processor(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched __A : int = image_processor(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processor __A : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : Union[str, Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : List[str] = image_processor(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched __A : Union[str, Any] = image_processor(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processor __A : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Optional[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Union[str, Any] = image_processor(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched __A : List[str] = image_processor(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , )
77
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : str = '''conditional_detr''' UpperCamelCase : int = ['''past_key_values'''] UpperCamelCase : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , _A=True , _A=None , _A=3 , _A=300 , _A=6 , _A=2048 , _A=8 , _A=6 , _A=2048 , _A=8 , _A=0.0 , _A=0.0 , _A=True , _A="relu" , _A=256 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1.0 , _A=False , _A="sine" , _A="resnet50" , _A=True , _A=False , _A=2 , _A=5 , _A=2 , _A=1 , _A=1 , _A=2 , _A=5 , _A=2 , _A=0.2_5 , **_A , ): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __A : List[str] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_A , _A ): __A : Tuple = backbone_config.get('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[Any] = config_class.from_dict(_A ) __A : Tuple = use_timm_backbone __A : List[str] = backbone_config __A : Dict = num_channels __A : int = num_queries __A : int = d_model __A : str = encoder_ffn_dim __A : List[str] = encoder_layers __A : Optional[Any] = encoder_attention_heads __A : Union[str, Any] = decoder_ffn_dim __A : List[Any] = decoder_layers __A : Optional[Any] = decoder_attention_heads __A : Any = dropout __A : Any = attention_dropout __A : int = activation_dropout __A : Optional[int] = activation_function __A : Union[str, Any] = init_std __A : Union[str, Any] = init_xavier_std __A : Optional[Any] = encoder_layerdrop __A : int = decoder_layerdrop __A : List[str] = encoder_layers __A : str = auxiliary_loss __A : Union[str, Any] = position_embedding_type __A : Optional[int] = backbone __A : List[str] = use_pretrained_backbone __A : List[Any] = dilation # Hungarian matcher __A : List[str] = class_cost __A : Optional[int] = bbox_cost __A : Dict = giou_cost # Loss coefficients __A : Optional[int] = mask_loss_coefficient __A : Union[str, Any] = dice_loss_coefficient __A : List[Any] = cls_loss_coefficient __A : Dict = bbox_loss_coefficient __A : Tuple = giou_loss_coefficient __A : Tuple = focal_alpha super().__init__(is_encoder_decoder=_A , **_A ) @property def UpperCAmelCase_ ( self ): return self.encoder_attention_heads @property def UpperCAmelCase_ ( self ): return self.d_model def UpperCAmelCase_ ( self ): __A : str = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __A : Dict = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = version.parse('''1.11''' ) @property def UpperCAmelCase_ ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def UpperCAmelCase_ ( self ): return 1e-5 @property def UpperCAmelCase_ ( self ): return 12
77
1
import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging UpperCAmelCase : int = logging.get_logger(__name__) UpperCAmelCase : str = { '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/config.json''', # See all BART models at https://huggingface.co/models?filter=bart } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = '''bart''' UpperCamelCase : Dict = ['''past_key_values'''] UpperCamelCase : List[str] = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self , _A=50265 , _A=1024 , _A=12 , _A=4096 , _A=16 , _A=12 , _A=4096 , _A=16 , _A=0.0 , _A=0.0 , _A="gelu" , _A=1024 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=0.0 , _A=False , _A=True , _A=3 , _A=1 , _A=0 , _A=2 , _A=True , _A=2 , _A=2 , **_A , ): __A : Optional[Any] = vocab_size __A : Optional[int] = max_position_embeddings __A : List[Any] = d_model __A : int = encoder_ffn_dim __A : Tuple = encoder_layers __A : List[str] = encoder_attention_heads __A : int = decoder_ffn_dim __A : str = decoder_layers __A : Any = decoder_attention_heads __A : Tuple = dropout __A : List[str] = attention_dropout __A : Optional[Any] = activation_dropout __A : Optional[int] = activation_function __A : str = init_std __A : List[Any] = encoder_layerdrop __A : int = decoder_layerdrop __A : Dict = classifier_dropout __A : Optional[int] = use_cache __A : str = encoder_layers __A : int = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( num_labels=_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , is_encoder_decoder=_A , decoder_start_token_id=_A , forced_eos_token_id=_A , **_A , ) # ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , _A ): __A : Tuple = self.bos_token_id warnings.warn( F"""Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. """ 'The config can simply be saved and uploaded again to be fixed.' ) class _A( snake_case__ ): """simple docstring""" @property def UpperCAmelCase_ ( self ): if self.task in ["default", "seq2seq-lm"]: __A : Union[str, Any] = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: __A : int = {0: 'batch'} __A : List[str] = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __A : Optional[Any] = {0: 'batch', 1: 'decoder_sequence'} __A : List[str] = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) elif self.task == "causal-lm": # TODO: figure this case out. __A : List[Any] = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: __A , __A : Optional[Any] = self.num_layers for i in range(_A ): __A : Tuple = {0: 'batch', 2: 'past_sequence + sequence'} __A : Tuple = {0: 'batch', 2: 'past_sequence + sequence'} else: __A : Optional[Any] = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}), ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}), ] ) return common_inputs @property def UpperCAmelCase_ ( self ): if self.task in ["default", "seq2seq-lm"]: __A : Optional[Any] = super().outputs else: __A : Dict = super(_A , self ).outputs if self.use_past: __A , __A : Any = self.num_layers for i in range(_A ): __A : Optional[int] = {0: 'batch', 2: 'past_sequence + sequence'} __A : Any = {0: 'batch', 2: 'past_sequence + sequence'} return common_outputs def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : List[str] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _A , _A , _A , _A , _A ) # Generate decoder inputs __A : Optional[int] = seq_length if not self.use_past else 1 __A : Optional[int] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _A , _A , _A , _A , _A ) __A : List[Any] = {F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()} __A : Optional[Any] = dict(**_A , **_A ) 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 : Optional[int] = common_inputs['input_ids'].shape __A : Any = common_inputs['decoder_input_ids'].shape[1] __A , __A : str = self.num_attention_heads __A : Union[str, Any] = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __A : Optional[Any] = decoder_seq_length + 3 __A : List[Any] = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __A : Optional[Any] = torch.cat( [common_inputs['decoder_attention_mask'], torch.ones(_A , _A )] , dim=1 ) __A : Any = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered __A , __A : Dict = self.num_layers __A : int = min(_A , _A ) __A : Union[str, Any] = max(_A , _A ) - min_num_layers __A : Tuple = 'encoder' if num_encoder_layers > num_decoder_layers else 'decoder' for _ in range(_A ): common_inputs["past_key_values"].append( ( torch.zeros(_A ), torch.zeros(_A ), torch.zeros(_A ), torch.zeros(_A ), ) ) # TODO: test this. __A : List[str] = encoder_shape if remaining_side_name == 'encoder' else decoder_shape for _ in range(_A , _A ): common_inputs["past_key_values"].append((torch.zeros(_A ), torch.zeros(_A )) ) return common_inputs def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Union[str, Any] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _A , _A , _A , _A , _A ) 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 : int = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Dict = seqlen + 2 __A , __A : str = self.num_layers __A , __A : str = self.num_attention_heads __A : Dict = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __A : Any = common_inputs['attention_mask'].dtype __A : Optional[int] = torch.cat( [common_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) __A : Optional[Any] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(_A ) ] return common_inputs def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): # Copied from OnnxConfig.generate_dummy_inputs # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __A : List[Any] = compute_effective_axis_dimension( _A , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __A : List[str] = tokenizer.num_special_tokens_to_add(_A ) __A : Union[str, Any] = compute_effective_axis_dimension( _A , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=_A ) # Generate dummy inputs according to compute batch and sequence __A : Any = [' '.join([tokenizer.unk_token] ) * seq_length] * batch_size __A : Dict = dict(tokenizer(_A , return_tensors=_A ) ) return common_inputs def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): if self.task in ["default", "seq2seq-lm"]: __A : Tuple = self._generate_dummy_inputs_for_default_and_seqaseq_lm( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) elif self.task == "causal-lm": __A : Tuple = self._generate_dummy_inputs_for_causal_lm( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) else: __A : Optional[int] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) return common_inputs def UpperCAmelCase_ ( self , _A , _A , _A , _A ): if self.task in ["default", "seq2seq-lm"]: __A : Dict = super()._flatten_past_key_values_(_A , _A , _A , _A ) else: __A : Optional[Any] = super(_A , self )._flatten_past_key_values_( _A , _A , _A , _A )
77
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _A( nn.Module ): """simple docstring""" def __init__( self ): super().__init__() __A : List[str] = nn.Linear(3 , 4 ) __A : Optional[Any] = nn.BatchNormad(4 ) __A : List[Any] = nn.Linear(4 , 5 ) def UpperCAmelCase_ ( self , _A ): return self.lineara(self.batchnorm(self.lineara(_A ) ) ) class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Dict = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , model.state_dict() ) __A : str = os.path.join(_A , 'index.json' ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: __A : Optional[int] = os.path.join(_A , F"""{key}.dat""" ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on the fact weights are properly loaded def UpperCAmelCase_ ( self ): __A : Dict = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: __A : Tuple = torch.randn(2 , 3 , dtype=_A ) with TemporaryDirectory() as tmp_dir: __A : int = offload_weight(_A , 'weight' , _A , {} ) __A : Union[str, Any] = os.path.join(_A , 'weight.dat' ) self.assertTrue(os.path.isfile(_A ) ) self.assertDictEqual(_A , {'weight': {'shape': [2, 3], 'dtype': str(_A ).split('.' )[1]}} ) __A : List[str] = load_offloaded_weight(_A , index['weight'] ) self.assertTrue(torch.equal(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : int = ModelForTest() __A : Union[str, Any] = model.state_dict() __A : Optional[Any] = {k: v for k, v in state_dict.items() if 'linear2' not in k} __A : str = {k: v for k, v in state_dict.items() if 'linear2' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : List[str] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) __A : Union[str, Any] = {k: v for k, v in state_dict.items() if 'weight' in k} __A : List[Any] = {k: v for k, v in state_dict.items() if 'weight' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : Optional[int] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) # Duplicates are removed __A : str = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) def UpperCAmelCase_ ( self ): __A : Dict = {'a.1': 0, 'a.10': 1, 'a.2': 2} __A : str = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1': 0, 'a.2': 2} ) __A : Optional[Any] = {'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2} __A : Any = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1.a': 0, 'a.2.a': 2} )
77
1
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput UpperCAmelCase : List[str] = logging.get_logger(__name__) # pylint: disable=invalid-name def _SCREAMING_SNAKE_CASE ( a ) -> Dict: warnings.warn( 'The preprocess method is deprecated and will be removed in a future version. Please' ' use VaeImageProcessor.preprocess instead' , a , ) if isinstance(a , torch.Tensor ): return image elif isinstance(a , PIL.Image.Image ): __A : Dict = [image] if isinstance(image[0] , PIL.Image.Image ): __A , __A : str = image[0].size __A , __A : str = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 __A : Dict = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) )[None, :] for i in image] __A : Tuple = np.concatenate(a , axis=0 ) __A : str = np.array(a ).astype(np.floataa ) / 255.0 __A : Optional[int] = image.transpose(0 , 3 , 1 , 2 ) __A : Optional[Any] = 2.0 * image - 1.0 __A : List[Any] = torch.from_numpy(a ) elif isinstance(image[0] , torch.Tensor ): __A : Tuple = torch.cat(a , dim=0 ) return image def _SCREAMING_SNAKE_CASE ( a ) -> Any: if isinstance(a , torch.Tensor ): return mask elif isinstance(a , PIL.Image.Image ): __A : str = [mask] if isinstance(mask[0] , PIL.Image.Image ): __A , __A : int = mask[0].size __A , __A : Any = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __A : List[Any] = [np.array(m.convert('L' ).resize((w, h) , resample=PIL_INTERPOLATION['nearest'] ) )[None, :] for m in mask] __A : Dict = np.concatenate(a , axis=0 ) __A : Optional[Any] = mask.astype(np.floataa ) / 255.0 __A : Tuple = 0 __A : Optional[Any] = 1 __A : Any = torch.from_numpy(a ) elif isinstance(mask[0] , torch.Tensor ): __A : Optional[int] = torch.cat(a , dim=0 ) return mask class _A( snake_case__ ): """simple docstring""" UpperCamelCase : UNetaDModel UpperCamelCase : RePaintScheduler def __init__( self , _A , _A ): super().__init__() self.register_modules(unet=_A , scheduler=_A ) @torch.no_grad() def __call__( self , _A , _A , _A = 250 , _A = 0.0 , _A = 10 , _A = 10 , _A = None , _A = "pil" , _A = True , ): __A : Tuple = image __A : Tuple = _preprocess_image(_A ) __A : Tuple = original_image.to(device=self.device , dtype=self.unet.dtype ) __A : List[Any] = _preprocess_mask(_A ) __A : Optional[int] = mask_image.to(device=self.device , dtype=self.unet.dtype ) __A : Optional[Any] = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(_A , _A ) and len(_A ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(_A )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) __A : Optional[int] = original_image.shape __A : Dict = randn_tensor(_A , generator=_A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(_A , _A , _A , self.device ) __A : Tuple = eta __A : Any = self.scheduler.timesteps[0] + 1 __A : Optional[Any] = generator[0] if isinstance(_A , _A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual __A : Tuple = self.unet(_A , _A ).sample # compute previous image: x_t -> x_t-1 __A : List[Any] = self.scheduler.step(_A , _A , _A , _A , _A , _A ).prev_sample else: # compute the reverse: x_t-1 -> x_t __A : Union[str, Any] = self.scheduler.undo_step(_A , _A , _A ) __A : Any = t __A : Union[str, Any] = (image / 2 + 0.5).clamp(0 , 1 ) __A : List[str] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __A : Tuple = self.numpy_to_pil(_A ) if not return_dict: return (image,) return ImagePipelineOutput(images=_A )
77
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): __A : Any = data def __iter__( self ): for element in self.data: yield element def _SCREAMING_SNAKE_CASE ( a=True ) -> Any: __A : List[Any] = Accelerator(even_batches=a ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str: if iterable: __A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) ) else: __A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) ) __A : Optional[Any] = DataLoader(a , batch_size=a ) __A : Optional[int] = accelerator.prepare(a ) return dl def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]: __A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a ) __A : Tuple = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : int = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : str = create_accelerator(even_batches=a ) verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _SCREAMING_SNAKE_CASE ( ) -> str: __A : Optional[Any] = create_accelerator(even_batches=a ) __A : str = torch.nn.Linear(1 , 1 ) __A : Optional[int] = accelerator.prepare(a ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : str = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(a ): __A : Dict = ddp_model(batch[0].float() ) __A : List[str] = output.sum() loss.backward() batch_idxs.append(a ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , a ) assert "only supported for multi-GPU" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : int = True __A : Union[str, Any] = False __A : Optional[int] = create_accelerator(even_batches=a ) __A : int = torch.nn.Linear(1 , 1 ) __A : List[Any] = accelerator.prepare(a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : List[str] = train_dl.batch_sampler.even_batches __A : Dict = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Any = True __A : List[Any] = False __A : Tuple = create_accelerator(even_batches=a ) __A : List[str] = torch.nn.Linear(1 , 1 ) __A : Optional[Any] = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('ignore' ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : Tuple = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Any = create_accelerator() __A : Union[str, Any] = torch.nn.Linear(1 , 1 ) __A : str = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): pass assert issubclass(w[-1].category , a ) assert "only supported for map-style datasets" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : str = create_accelerator() accelerator.print('Test that even_batches variable ensures uniform batches across processes' ) test_default_ensures_even_batch_sizes() accelerator.print('Run tests with even_batches disabled' ) test_can_disable_even_batches() accelerator.print('Test joining uneven inputs' ) test_can_join_uneven_inputs() accelerator.print('Test overriding even_batches when joining uneven inputs' ) test_join_can_override_even_batches() accelerator.print('Test overriding even_batches for mixed dataloader types' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('Test join with non DDP distributed raises warning' ) __A : int = accelerator.state.distributed_type __A : Tuple = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(a ) __A : str = original_state if __name__ == "__main__": main()
77
1
from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class _A( nn.Module ): """simple docstring""" def __init__( self , _A = 16 , _A = 88 , _A = None , _A = 1 , _A = 0.0 , _A = 32 , _A = None , _A = False , _A = None , _A = None , _A = "geglu" , _A = None , ): super().__init__() __A : Any = nn.ModuleList( [ TransformeraDModel( num_attention_heads=_A , attention_head_dim=_A , in_channels=_A , num_layers=_A , dropout=_A , norm_num_groups=_A , cross_attention_dim=_A , attention_bias=_A , sample_size=_A , num_vector_embeds=_A , activation_fn=_A , num_embeds_ada_norm=_A , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference __A : List[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` __A : Any = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` __A : Dict = [1, 0] def UpperCAmelCase_ ( self , _A , _A , _A=None , _A=None , _A=None , _A = True , ): __A : List[str] = hidden_states __A : Union[str, Any] = [] __A : Union[str, Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens __A : Union[str, Any] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] __A : str = self.transformer_index_for_condition[i] __A : Optional[Any] = self.transformers[transformer_index]( _A , encoder_hidden_states=_A , timestep=_A , cross_attention_kwargs=_A , return_dict=_A , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] __A : List[Any] = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) __A : Optional[Any] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=_A )
77
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : str = { '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''', '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''', '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''', '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''', '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''', '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''', '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''', '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''', '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''', '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''', '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''', '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = '''codegen''' UpperCamelCase : List[str] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ): __A : Any = vocab_size __A : Tuple = n_ctx __A : Union[str, Any] = n_positions __A : Optional[Any] = n_embd __A : Any = n_layer __A : Dict = n_head __A : Union[str, Any] = n_inner __A : List[Any] = rotary_dim __A : str = activation_function __A : Any = resid_pdrop __A : Tuple = embd_pdrop __A : Tuple = attn_pdrop __A : Union[str, Any] = layer_norm_epsilon __A : str = initializer_range __A : Optional[Any] = use_cache __A : Union[str, Any] = bos_token_id __A : Tuple = eos_token_id super().__init__( bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A ) class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A = "default" , _A = None , _A = False , ): super().__init__(_A , task=_A , patching_specs=_A , use_past=_A ) if not getattr(self._config , 'pad_token_id' , _A ): # TODO: how to do that better? __A : Dict = 0 @property def UpperCAmelCase_ ( self ): __A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) __A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'} else: __A : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase_ ( self ): return self._config.n_layer @property def UpperCAmelCase_ ( self ): return self._config.n_head def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Any = super(_A , self ).generate_dummy_inputs( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) # We need to order the input in the way they appears in the forward() __A : str = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __A , __A : Any = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Any = seqlen + 2 __A : List[str] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __A : Optional[Any] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] __A : Tuple = common_inputs['attention_mask'] if self.use_past: __A : str = ordered_inputs['attention_mask'].dtype __A : List[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self ): return 13
77
1
import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Dict = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) UpperCAmelCase : Union[str, Any] = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _A: """simple docstring""" UpperCamelCase : str = field( default=snake_case__ , metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(snake_case__ )} ) UpperCamelCase : str = field( default=snake_case__ , metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''} ) UpperCamelCase : int = field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCamelCase : int = field( default=128 , metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''} , ) UpperCamelCase : int = field( default=64 , metadata={ '''help''': ( '''The maximum number of tokens for the question. Questions longer than this will ''' '''be truncated to this length.''' ) } , ) UpperCamelCase : int = field( default=30 , metadata={ '''help''': ( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ) } , ) UpperCamelCase : bool = field( default=snake_case__ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) UpperCamelCase : bool = field( default=snake_case__ , metadata={'''help''': '''If true, the SQuAD examples contain some that do not have an answer.'''} ) UpperCamelCase : float = field( default=0.0 , metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''} ) UpperCamelCase : int = field( default=20 , metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''} ) UpperCamelCase : int = field( default=0 , metadata={ '''help''': ( '''language id of input for language-specific xlm models (see''' ''' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)''' ) } , ) UpperCamelCase : int = field(default=1 , metadata={'''help''': '''multiple threads for converting example to features'''} ) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : int = '''train''' UpperCamelCase : str = '''dev''' class _A( snake_case__ ): """simple docstring""" UpperCamelCase : SquadDataTrainingArguments UpperCamelCase : List[SquadFeatures] UpperCamelCase : Split UpperCamelCase : bool def __init__( self , _A , _A , _A = None , _A = Split.train , _A = False , _A = None , _A = "pt" , ): __A : List[str] = args __A : str = is_language_sensitive __A : Dict = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(_A , _A ): try: __A : List[str] = Split[mode] except KeyError: raise KeyError('mode is not a valid split name' ) __A : Union[str, Any] = mode # Load data features from cache or dataset file __A : str = 'v2' if args.version_2_with_negative else 'v1' __A : Union[str, Any] = os.path.join( cache_dir if cache_dir is not None else args.data_dir , F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}""" , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __A : List[str] = cached_features_file + '.lock' with FileLock(_A ): if os.path.exists(_A ) and not args.overwrite_cache: __A : Union[str, Any] = time.time() __A : Any = torch.load(_A ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. __A : Any = self.old_features['features'] __A : Optional[Any] = self.old_features.get('dataset' , _A ) __A : Any = self.old_features.get('examples' , _A ) logger.info( F"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( F"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in""" ' future run' ) else: if mode == Split.dev: __A : Optional[int] = self.processor.get_dev_examples(args.data_dir ) else: __A : Optional[int] = self.processor.get_train_examples(args.data_dir ) __A , __A : str = squad_convert_examples_to_features( examples=self.examples , tokenizer=_A , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=_A , ) __A : str = time.time() torch.save( {'features': self.features, 'dataset': self.dataset, 'examples': self.examples} , _A , ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""" ) def __len__( self ): return len(self.features ) def __getitem__( self , _A ): # Convert to Tensors and build dataset __A : List[str] = self.features[i] __A : Tuple = torch.tensor(feature.input_ids , dtype=torch.long ) __A : Union[str, Any] = torch.tensor(feature.attention_mask , dtype=torch.long ) __A : Dict = torch.tensor(feature.token_type_ids , dtype=torch.long ) __A : int = torch.tensor(feature.cls_index , dtype=torch.long ) __A : Any = torch.tensor(feature.p_mask , dtype=torch.float ) __A : Union[str, Any] = torch.tensor(feature.is_impossible , dtype=torch.float ) __A : Optional[int] = { 'input_ids': input_ids, 'attention_mask': attention_mask, 'token_type_ids': token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({'cls_index': cls_index, 'p_mask': p_mask} ) if self.args.version_2_with_negative: inputs.update({'is_impossible': is_impossible} ) if self.is_language_sensitive: inputs.update({'langs': (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: __A : List[Any] = torch.tensor(feature.start_position , dtype=torch.long ) __A : int = torch.tensor(feature.end_position , dtype=torch.long ) inputs.update({'start_positions': start_positions, 'end_positions': end_positions} ) return inputs
77
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase : List[Any] = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _A , ) super().__init__(*_A , **_A )
77
1
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
import glob import os import random from string import ascii_lowercase, digits import cva UpperCAmelCase : Dict = '''''' UpperCAmelCase : Union[str, Any] = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal) def _SCREAMING_SNAKE_CASE ( ) -> None: __A , __A : List[Any] = get_dataset(a , a ) print('Processing...' ) __A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a ) for index, image in enumerate(a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __A : Optional[int] = random_chars(32 ) __A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] __A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Success {index+1}/{len(a )} with {file_name}""" ) __A : int = [] for anno in new_annos[index]: __A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(a ) with open(F"""/{file_root}.txt""" , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]: __A : int = [] __A : List[Any] = [] for label_file in glob.glob(os.path.join(a , '*.txt' ) ): __A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(a ) as in_file: __A : Tuple = in_file.readlines() __A : Dict = os.path.join(a , F"""{label_name}.jpg""" ) __A : Dict = [] for obj_list in obj_lists: __A : int = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(a ) labels.append(a ) return img_paths, labels def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]: __A : int = [] __A : Optional[Any] = [] __A : Dict = [] for idx in range(len(a ) ): __A : Dict = [] __A : Optional[Any] = img_list[idx] path_list.append(a ) __A : Union[str, Any] = anno_list[idx] __A : Optional[Any] = cva.imread(a ) if flip_type == 1: __A : Any = cva.flip(a , a ) for bbox in img_annos: __A : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __A : Union[str, Any] = cva.flip(a , a ) for bbox in img_annos: __A : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(a ) new_imgs_list.append(a ) return new_imgs_list, new_annos_lists, path_list def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __A : List[Any] = ascii_lowercase + digits return "".join(random.choice(a ) for _ in range(a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
77
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[Any] = logging.get_logger(__name__) class _A( snake_case__ , snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = '''maskformer-swin''' UpperCamelCase : str = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , _A=224 , _A=4 , _A=3 , _A=96 , _A=[2, 2, 6, 2] , _A=[3, 6, 12, 24] , _A=7 , _A=4.0 , _A=True , _A=0.0 , _A=0.0 , _A=0.1 , _A="gelu" , _A=False , _A=0.0_2 , _A=1e-5 , _A=None , _A=None , **_A , ): super().__init__(**_A ) __A : List[str] = image_size __A : Tuple = patch_size __A : List[str] = num_channels __A : str = embed_dim __A : str = depths __A : Dict = len(_A ) __A : str = num_heads __A : Tuple = window_size __A : List[str] = mlp_ratio __A : Dict = qkv_bias __A : Optional[int] = hidden_dropout_prob __A : Tuple = attention_probs_dropout_prob __A : Optional[int] = drop_path_rate __A : Any = hidden_act __A : str = use_absolute_embeddings __A : str = layer_norm_eps __A : Tuple = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __A : Union[str, Any] = int(embed_dim * 2 ** (len(_A ) - 1) ) __A : Union[str, Any] = ['stem'] + [F"""stage{idx}""" for idx in range(1 , len(_A ) + 1 )] __A , __A : str = get_aligned_output_features_output_indices( out_features=_A , out_indices=_A , stage_names=self.stage_names )
77
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A: """simple docstring""" def __init__( self , _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.0_2 , _A=3 , _A=4 , _A=None , ): __A : Union[str, Any] = parent __A : List[str] = batch_size __A : Optional[int] = seq_length __A : List[Any] = is_training __A : Optional[Any] = use_input_mask __A : List[Any] = use_token_type_ids __A : Optional[Any] = use_labels __A : List[str] = vocab_size __A : Optional[int] = hidden_size __A : List[Any] = num_hidden_layers __A : int = num_attention_heads __A : Dict = intermediate_size __A : Any = hidden_act __A : Union[str, Any] = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : Optional[int] = max_position_embeddings __A : Dict = type_vocab_size __A : Any = type_sequence_label_size __A : Dict = initializer_range __A : str = num_labels __A : Union[str, Any] = num_choices __A : str = scope def UpperCAmelCase_ ( self ): __A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : Optional[Any] = None if self.use_input_mask: __A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __A : Dict = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = None __A : List[Any] = None __A : List[Any] = None if self.use_labels: __A : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __A : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[str] = LlamaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A , attention_mask=_A ) __A : Any = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Dict = True __A : int = LlamaModel(_A ) model.to(_A ) model.eval() __A : str = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __A : int = model( _A , attention_mask=_A , encoder_hidden_states=_A , ) __A : List[Any] = model(_A , attention_mask=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Optional[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : int = True __A : List[Any] = True __A : List[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() # first forward pass __A : Optional[Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , ) __A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __A : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) __A : str = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __A : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : str = torch.cat([input_mask, next_mask] , dim=-1 ) __A : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['hidden_states'][0] __A : Union[str, Any] = 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 __A : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() __A : Tuple = 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 UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Tuple = config_and_inputs __A : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () UpperCamelCase : Optional[Any] = (LlamaForCausalLM,) if is_torch_available() else () UpperCamelCase : Optional[Any] = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False def UpperCAmelCase_ ( self ): __A : List[Any] = LlamaModelTester(self ) __A : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : int = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() __A : str = 3 __A : Optional[int] = input_dict['input_ids'] __A : int = input_ids.ne(1 ).to(_A ) __A : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Union[str, Any] = 3 __A : Tuple = 'single_label_classification' __A : Union[str, Any] = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[int] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Any = 3 __A : int = 'multi_label_classification' __A : int = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __A : List[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def UpperCAmelCase_ ( self ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def UpperCAmelCase_ ( self , _A ): __A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Dict = ids_tensor([1, 10] , config.vocab_size ) __A : Union[str, Any] = 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 __A : List[Any] = LlamaModel(_A ) original_model.to(_A ) original_model.eval() __A : Dict = original_model(_A ).last_hidden_state __A : int = original_model(_A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : int = {'type': scaling_type, 'factor': 1_0.0} __A : str = LlamaModel(_A ) scaled_model.to(_A ) scaled_model.eval() __A : Dict = scaled_model(_A ).last_hidden_state __A : str = 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 ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) __A : Union[str, Any] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __A : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[str] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) __A : int = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) __A : Optional[int] = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : Optional[Any] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) __A : List[Any] = model(torch.tensor(_A ) ) __A : Tuple = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # fmt: off __A : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' __A : List[str] = 'Simply put, the theory of relativity states that ' __A : Union[str, Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) __A : List[str] = tokenizer.encode(_A , return_tensors='pt' ) __A : Tuple = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=_A ) # greedy generation outputs __A : Union[str, Any] = model.generate(_A , max_new_tokens=64 , top_p=_A , temperature=1 , do_sample=_A ) __A : List[str] = tokenizer.decode(generated_ids[0] , skip_special_tokens=_A ) self.assertEqual(_A , _A )
77
1
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: UpperCAmelCase : Optional[Any] = None UpperCAmelCase : Tuple = logging.get_logger(__name__) UpperCAmelCase : Union[str, Any] = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''facebook/nllb-200-distilled-600M''': ( '''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''facebook/nllb-200-distilled-600M''': ( '''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : int = { '''facebook/nllb-large-en-ro''': 10_24, '''facebook/nllb-200-distilled-600M''': 10_24, } # fmt: off UpperCAmelCase : Any = ['''ace_Arab''', '''ace_Latn''', '''acm_Arab''', '''acq_Arab''', '''aeb_Arab''', '''afr_Latn''', '''ajp_Arab''', '''aka_Latn''', '''amh_Ethi''', '''apc_Arab''', '''arb_Arab''', '''ars_Arab''', '''ary_Arab''', '''arz_Arab''', '''asm_Beng''', '''ast_Latn''', '''awa_Deva''', '''ayr_Latn''', '''azb_Arab''', '''azj_Latn''', '''bak_Cyrl''', '''bam_Latn''', '''ban_Latn''', '''bel_Cyrl''', '''bem_Latn''', '''ben_Beng''', '''bho_Deva''', '''bjn_Arab''', '''bjn_Latn''', '''bod_Tibt''', '''bos_Latn''', '''bug_Latn''', '''bul_Cyrl''', '''cat_Latn''', '''ceb_Latn''', '''ces_Latn''', '''cjk_Latn''', '''ckb_Arab''', '''crh_Latn''', '''cym_Latn''', '''dan_Latn''', '''deu_Latn''', '''dik_Latn''', '''dyu_Latn''', '''dzo_Tibt''', '''ell_Grek''', '''eng_Latn''', '''epo_Latn''', '''est_Latn''', '''eus_Latn''', '''ewe_Latn''', '''fao_Latn''', '''pes_Arab''', '''fij_Latn''', '''fin_Latn''', '''fon_Latn''', '''fra_Latn''', '''fur_Latn''', '''fuv_Latn''', '''gla_Latn''', '''gle_Latn''', '''glg_Latn''', '''grn_Latn''', '''guj_Gujr''', '''hat_Latn''', '''hau_Latn''', '''heb_Hebr''', '''hin_Deva''', '''hne_Deva''', '''hrv_Latn''', '''hun_Latn''', '''hye_Armn''', '''ibo_Latn''', '''ilo_Latn''', '''ind_Latn''', '''isl_Latn''', '''ita_Latn''', '''jav_Latn''', '''jpn_Jpan''', '''kab_Latn''', '''kac_Latn''', '''kam_Latn''', '''kan_Knda''', '''kas_Arab''', '''kas_Deva''', '''kat_Geor''', '''knc_Arab''', '''knc_Latn''', '''kaz_Cyrl''', '''kbp_Latn''', '''kea_Latn''', '''khm_Khmr''', '''kik_Latn''', '''kin_Latn''', '''kir_Cyrl''', '''kmb_Latn''', '''kon_Latn''', '''kor_Hang''', '''kmr_Latn''', '''lao_Laoo''', '''lvs_Latn''', '''lij_Latn''', '''lim_Latn''', '''lin_Latn''', '''lit_Latn''', '''lmo_Latn''', '''ltg_Latn''', '''ltz_Latn''', '''lua_Latn''', '''lug_Latn''', '''luo_Latn''', '''lus_Latn''', '''mag_Deva''', '''mai_Deva''', '''mal_Mlym''', '''mar_Deva''', '''min_Latn''', '''mkd_Cyrl''', '''plt_Latn''', '''mlt_Latn''', '''mni_Beng''', '''khk_Cyrl''', '''mos_Latn''', '''mri_Latn''', '''zsm_Latn''', '''mya_Mymr''', '''nld_Latn''', '''nno_Latn''', '''nob_Latn''', '''npi_Deva''', '''nso_Latn''', '''nus_Latn''', '''nya_Latn''', '''oci_Latn''', '''gaz_Latn''', '''ory_Orya''', '''pag_Latn''', '''pan_Guru''', '''pap_Latn''', '''pol_Latn''', '''por_Latn''', '''prs_Arab''', '''pbt_Arab''', '''quy_Latn''', '''ron_Latn''', '''run_Latn''', '''rus_Cyrl''', '''sag_Latn''', '''san_Deva''', '''sat_Beng''', '''scn_Latn''', '''shn_Mymr''', '''sin_Sinh''', '''slk_Latn''', '''slv_Latn''', '''smo_Latn''', '''sna_Latn''', '''snd_Arab''', '''som_Latn''', '''sot_Latn''', '''spa_Latn''', '''als_Latn''', '''srd_Latn''', '''srp_Cyrl''', '''ssw_Latn''', '''sun_Latn''', '''swe_Latn''', '''swh_Latn''', '''szl_Latn''', '''tam_Taml''', '''tat_Cyrl''', '''tel_Telu''', '''tgk_Cyrl''', '''tgl_Latn''', '''tha_Thai''', '''tir_Ethi''', '''taq_Latn''', '''taq_Tfng''', '''tpi_Latn''', '''tsn_Latn''', '''tso_Latn''', '''tuk_Latn''', '''tum_Latn''', '''tur_Latn''', '''twi_Latn''', '''tzm_Tfng''', '''uig_Arab''', '''ukr_Cyrl''', '''umb_Latn''', '''urd_Arab''', '''uzn_Latn''', '''vec_Latn''', '''vie_Latn''', '''war_Latn''', '''wol_Latn''', '''xho_Latn''', '''ydd_Hebr''', '''yor_Latn''', '''yue_Hant''', '''zho_Hans''', '''zho_Hant''', '''zul_Latn'''] class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Dict = VOCAB_FILES_NAMES UpperCamelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : List[str] = ['''input_ids''', '''attention_mask'''] UpperCamelCase : Optional[int] = NllbTokenizer UpperCamelCase : List[int] = [] UpperCamelCase : List[int] = [] def __init__( self , _A=None , _A=None , _A="<s>" , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A=None , _A=None , _A=None , _A=False , **_A , ): # Mask token behave like a normal word, i.e. include the space before it __A : Optional[int] = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else mask_token __A : Dict = legacy_behaviour super().__init__( vocab_file=_A , tokenizer_file=_A , bos_token=_A , eos_token=_A , sep_token=_A , cls_token=_A , unk_token=_A , pad_token=_A , mask_token=_A , src_lang=_A , tgt_lang=_A , additional_special_tokens=_A , legacy_behaviour=_A , **_A , ) __A : List[Any] = vocab_file __A : Dict = False if not self.vocab_file else True __A : List[str] = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'additional_special_tokens': _additional_special_tokens} ) __A : str = { lang_code: self.convert_tokens_to_ids(_A ) for lang_code in FAIRSEQ_LANGUAGE_CODES } __A : int = src_lang if src_lang is not None else 'eng_Latn' __A : str = self.convert_tokens_to_ids(self._src_lang ) __A : Any = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def UpperCAmelCase_ ( self ): return self._src_lang @src_lang.setter def UpperCAmelCase_ ( self , _A ): __A : int = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def UpperCAmelCase_ ( self , _A , _A = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def UpperCAmelCase_ ( self , _A , _A = None ): __A : List[str] = [self.sep_token_id] __A : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCAmelCase_ ( self , _A , _A , _A , _A , **_A ): if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' ) __A : Tuple = src_lang __A : Optional[int] = self(_A , add_special_tokens=_A , return_tensors=_A , **_A ) __A : List[str] = self.convert_tokens_to_ids(_A ) __A : Optional[int] = tgt_lang_id return inputs def UpperCAmelCase_ ( self , _A , _A = "eng_Latn" , _A = None , _A = "fra_Latn" , **_A , ): __A : str = src_lang __A : Optional[Any] = tgt_lang return super().prepare_seqaseq_batch(_A , _A , **_A ) def UpperCAmelCase_ ( self ): return self.set_src_lang_special_tokens(self.src_lang ) def UpperCAmelCase_ ( self ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def UpperCAmelCase_ ( self , _A ): __A : str = self.convert_tokens_to_ids(_A ) if self.legacy_behaviour: __A : List[Any] = [] __A : Union[str, Any] = [self.eos_token_id, self.cur_lang_code] else: __A : Optional[int] = [self.cur_lang_code] __A : Tuple = [self.eos_token_id] __A : Union[str, Any] = self.convert_ids_to_tokens(self.prefix_tokens ) __A : Optional[Any] = self.convert_ids_to_tokens(self.suffix_tokens ) __A : Optional[int] = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str , pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def UpperCAmelCase_ ( self , _A ): __A : Union[str, Any] = self.convert_tokens_to_ids(_A ) if self.legacy_behaviour: __A : List[Any] = [] __A : Union[str, Any] = [self.eos_token_id, self.cur_lang_code] else: __A : List[str] = [self.cur_lang_code] __A : int = [self.eos_token_id] __A : Any = self.convert_ids_to_tokens(self.prefix_tokens ) __A : Optional[int] = self.convert_ids_to_tokens(self.suffix_tokens ) __A : List[Any] = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str , pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def UpperCAmelCase_ ( self , _A , _A = None ): if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(_A ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory.""" ) return __A : int = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ): copyfile(self.vocab_file , _A ) return (out_vocab_file,)
77
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input UpperCAmelCase : Tuple = '''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : Optional[Any] = _ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: __A : Tuple = get_sagemaker_input() else: __A : Optional[Any] = get_cluster_input() return config def _SCREAMING_SNAKE_CASE ( a=None ) -> Tuple: if subparsers is not None: __A : Optional[Any] = subparsers.add_parser('config' , description=a ) else: __A : Optional[int] = argparse.ArgumentParser('Accelerate config command' , description=a ) parser.add_argument( '--config_file' , default=a , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=a ) return parser def _SCREAMING_SNAKE_CASE ( a ) -> Optional[int]: __A : Dict = get_user_input() if args.config_file is not None: __A : Dict = args.config_file else: if not os.path.isdir(a ): os.makedirs(a ) __A : Tuple = default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(a ) else: config.to_yaml_file(a ) print(F"""accelerate configuration saved at {config_file}""" ) def _SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: __A : str = config_command_parser() __A : int = parser.parse_args() config_command(a ) if __name__ == "__main__": main()
77
import numpy as np from PIL import Image def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : Union[str, Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : List[Any] = 0 __A : Optional[Any] = 0 __A : List[Any] = 0 __A : Dict = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __A : Tuple = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : List[str] = 0 __A : Union[str, Any] = 0 return updated_arr def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : List[Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : Dict = 0 __A : str = 0 __A : Tuple = 0 __A : Optional[int] = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __A : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : Dict = 0 __A : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image UpperCAmelCase : int = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
77
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : int = { '''configuration_time_series_transformer''': [ '''TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TimeSeriesTransformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TimeSeriesTransformerForPrediction''', '''TimeSeriesTransformerModel''', '''TimeSeriesTransformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys UpperCAmelCase : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float: __A : Any = x_start __A : List[str] = fnc(a ) __A : Optional[Any] = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area __A : Any = (x_end - x_start) / steps + xa __A : List[str] = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __A : Any = xa __A : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( a ) -> int: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') UpperCAmelCase : Tuple = 10 while i <= 10_00_00: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
77
1
import glob import os import random from string import ascii_lowercase, digits import cva UpperCAmelCase : Dict = '''''' UpperCAmelCase : Union[str, Any] = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal) def _SCREAMING_SNAKE_CASE ( ) -> None: __A , __A : List[Any] = get_dataset(a , a ) print('Processing...' ) __A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a ) for index, image in enumerate(a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __A : Optional[int] = random_chars(32 ) __A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] __A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Success {index+1}/{len(a )} with {file_name}""" ) __A : int = [] for anno in new_annos[index]: __A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(a ) with open(F"""/{file_root}.txt""" , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]: __A : int = [] __A : List[Any] = [] for label_file in glob.glob(os.path.join(a , '*.txt' ) ): __A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(a ) as in_file: __A : Tuple = in_file.readlines() __A : Dict = os.path.join(a , F"""{label_name}.jpg""" ) __A : Dict = [] for obj_list in obj_lists: __A : int = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(a ) labels.append(a ) return img_paths, labels def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]: __A : int = [] __A : Optional[Any] = [] __A : Dict = [] for idx in range(len(a ) ): __A : Dict = [] __A : Optional[Any] = img_list[idx] path_list.append(a ) __A : Union[str, Any] = anno_list[idx] __A : Optional[Any] = cva.imread(a ) if flip_type == 1: __A : Any = cva.flip(a , a ) for bbox in img_annos: __A : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __A : Union[str, Any] = cva.flip(a , a ) for bbox in img_annos: __A : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(a ) new_imgs_list.append(a ) return new_imgs_list, new_annos_lists, path_list def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __A : List[Any] = ascii_lowercase + digits return "".join(random.choice(a ) for _ in range(a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
77
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def _SCREAMING_SNAKE_CASE ( ) -> None: print('Making key files...' ) make_key_files('rsa' , 10_24 ) print('Key files generation successful.' ) def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]: print('Generating prime p...' ) __A : Optional[Any] = rabinMiller.generate_large_prime(a ) print('Generating prime q...' ) __A : Union[str, Any] = rabinMiller.generate_large_prime(a ) __A : Tuple = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...' ) while True: __A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1: break print('Calculating d that is mod inverse of e...' ) __A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) ) __A : Dict = (n, e) __A : Dict = (n, d) return (public_key, private_key) def _SCREAMING_SNAKE_CASE ( a , a ) -> None: if os.path.exists(F"""{name}_pubkey.txt""" ) or os.path.exists(F"""{name}_privkey.txt""" ): print('\nWARNING:' ) print( F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n""" 'Use a different name or delete these files and re-run this program.' ) sys.exit() __A , __A : Optional[int] = generate_key(a ) print(F"""\nWriting public key to file {name}_pubkey.txt...""" ) with open(F"""{name}_pubkey.txt""" , 'w' ) as out_file: out_file.write(F"""{key_size},{public_key[0]},{public_key[1]}""" ) print(F"""Writing private key to file {name}_privkey.txt...""" ) with open(F"""{name}_privkey.txt""" , 'w' ) as out_file: out_file.write(F"""{key_size},{private_key[0]},{private_key[1]}""" ) if __name__ == "__main__": main()
77
1
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[str] = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right UpperCAmelCase : str = 25_00_04 UpperCAmelCase : int = 25_00_20 @require_sentencepiece @require_tokenizers class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = MBartTokenizer UpperCamelCase : List[str] = MBartTokenizerFast UpperCamelCase : Dict = True UpperCamelCase : Any = True def UpperCAmelCase_ ( self ): super().setUp() # We have a SentencePiece fixture for testing __A : Optional[int] = MBartTokenizer(_A , keep_accents=_A ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = MBartTokenizer(_A , keep_accents=_A ) __A : List[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(_A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_A ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __A : Optional[int] = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __A : str = tokenizer.convert_tokens_to_ids(_A ) self.assertListEqual( _A , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) __A : Dict = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def UpperCAmelCase_ ( self ): if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return __A : Optional[int] = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __A : List[Any] = self.rust_tokenizer_class.from_pretrained(_A , **_A ) __A : str = self.tokenizer_class.from_pretrained(_A , **_A ) __A : List[Any] = tempfile.mkdtemp() __A : Dict = tokenizer_r.save_pretrained(_A ) __A : Tuple = tokenizer_p.save_pretrained(_A ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) __A : Optional[Any] = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(_A , _A ) # Checks everything loads correctly in the same way __A : Tuple = tokenizer_r.from_pretrained(_A ) __A : List[Any] = tokenizer_p.from_pretrained(_A ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_A , _A ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(_A ) # Save tokenizer rust, legacy_format=True __A : Optional[Any] = tempfile.mkdtemp() __A : Tuple = tokenizer_r.save_pretrained(_A , legacy_format=_A ) __A : Union[str, Any] = tokenizer_p.save_pretrained(_A ) # Checks it save with the same files self.assertSequenceEqual(_A , _A ) # Checks everything loads correctly in the same way __A : int = tokenizer_r.from_pretrained(_A ) __A : str = tokenizer_p.from_pretrained(_A ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_A , _A ) ) shutil.rmtree(_A ) # Save tokenizer rust, legacy_format=False __A : List[str] = tempfile.mkdtemp() __A : Optional[Any] = tokenizer_r.save_pretrained(_A , legacy_format=_A ) __A : Dict = tokenizer_p.save_pretrained(_A ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __A : List[str] = tokenizer_r.from_pretrained(_A ) __A : List[Any] = tokenizer_p.from_pretrained(_A ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_A , _A ) ) shutil.rmtree(_A ) @require_torch @require_sentencepiece @require_tokenizers class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : str = '''facebook/mbart-large-en-ro''' UpperCamelCase : List[str] = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] UpperCamelCase : Tuple = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] UpperCamelCase : Dict = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE] @classmethod def UpperCAmelCase_ ( cls ): __A : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) __A : Union[str, Any] = 1 return cls def UpperCAmelCase_ ( self ): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 250020 ) def UpperCAmelCase_ ( self ): __A : List[str] = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , _A ) def UpperCAmelCase_ ( self ): self.assertIn(_A , self.tokenizer.all_special_ids ) __A : Tuple = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] __A : int = self.tokenizer.decode(_A , skip_special_tokens=_A ) __A : List[str] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_A ) self.assertEqual(_A , _A ) self.assertNotIn(self.tokenizer.eos_token , _A ) def UpperCAmelCase_ ( self ): __A : Any = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , _A ) __A : Optional[Any] = 10 __A : int = self.tokenizer(_A , max_length=_A , truncation=_A ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , _A ) self.assertEqual(len(_A ) , _A ) def UpperCAmelCase_ ( self ): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [250026, 250001] ) def UpperCAmelCase_ ( self ): __A : List[str] = tempfile.mkdtemp() __A : Tuple = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(_A ) __A : Any = MBartTokenizer.from_pretrained(_A ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , _A ) @require_torch def UpperCAmelCase_ ( self ): __A : Optional[int] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=_A , return_tensors='pt' ) __A : Union[str, Any] = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=_A , truncation=_A , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) __A : Tuple = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(_A , _A ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) __A : List[str] = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , _A ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def UpperCAmelCase_ ( self ): __A : List[str] = self.tokenizer(self.src_text , padding=_A , truncation=_A , max_length=3 , return_tensors='pt' ) __A : Optional[Any] = self.tokenizer( text_target=self.tgt_text , padding=_A , truncation=_A , max_length=10 , return_tensors='pt' ) __A : int = targets['input_ids'] __A : Optional[Any] = shift_tokens_right(_A , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(_A ) , { # A, test, EOS, en_XX 'input_ids': [[62, 3034, 2, 250004]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 250001, } , )
77
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ProphetNetTokenizer UpperCamelCase : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() __A : Any = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = 'UNwant\u00E9d,running' __A : List[str] = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class(self.vocab_file ) __A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase_ ( self ): __A : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCAmelCase_ ( self ): __A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __A : Optional[int] = {} for i, token in enumerate(_A ): __A : Tuple = i __A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __A : str = tokenizer(_A , padding=_A , return_tensors='pt' ) self.assertIsInstance(_A , _A ) __A : List[str] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A ) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A ) __A : str = tokenizer.build_inputs_with_special_tokens(_A ) __A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
77
1
def _SCREAMING_SNAKE_CASE ( a , a ) -> int: return number | (1 << position) def _SCREAMING_SNAKE_CASE ( a , a ) -> int: return number & ~(1 << position) def _SCREAMING_SNAKE_CASE ( a , a ) -> int: return number ^ (1 << position) def _SCREAMING_SNAKE_CASE ( a , a ) -> bool: return ((number >> position) & 1) == 1 def _SCREAMING_SNAKE_CASE ( a , a ) -> int: return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
77
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Optional[int] = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } UpperCAmelCase : List[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = BertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : Any = getattr(_A , normalizer_state.pop('type' ) ) __A : Union[str, Any] = do_lower_case __A : Optional[int] = strip_accents __A : List[Any] = tokenize_chinese_chars __A : int = normalizer_class(**_A ) __A : Union[str, Any] = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : Tuple = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[Any] = [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : int = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
1
import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase : Tuple = logging.get_logger(__name__) UpperCAmelCase : List[str] = '''https://openaipublic.azureedge.net/jukebox/models/''' UpperCAmelCase : str = { '''jukebox-1b-lyrics''': [ '''5b/vqvae.pth.tar''', '''5b/prior_level_0.pth.tar''', '''5b/prior_level_1.pth.tar''', '''1b_lyrics/prior_level_2.pth.tar''', ], '''jukebox-5b-lyrics''': [ '''5b/vqvae.pth.tar''', '''5b/prior_level_0.pth.tar''', '''5b/prior_level_1.pth.tar''', '''5b_lyrics/prior_level_2.pth.tar''', ], } def _SCREAMING_SNAKE_CASE ( a ) -> int: if key.endswith('.model.1.bias' ) and len(key.split('.' ) ) > 10: __A : List[Any] = key.replace('.model.1.bias' , '.conv1d_1.bias' ) elif key.endswith('.model.1.weight' ) and len(key.split('.' ) ) > 10: __A : Union[str, Any] = key.replace('.model.1.weight' , '.conv1d_1.weight' ) elif key.endswith('.model.3.bias' ) and len(key.split('.' ) ) > 10: __A : Union[str, Any] = key.replace('.model.3.bias' , '.conv1d_2.bias' ) elif key.endswith('.model.3.weight' ) and len(key.split('.' ) ) > 10: __A : List[Any] = key.replace('.model.3.weight' , '.conv1d_2.weight' ) if "conditioner_blocks.0." in key: __A : Optional[Any] = key.replace('conditioner_blocks.0' , 'conditioner_blocks' ) if "prime_prior" in key: __A : Optional[Any] = key.replace('prime_prior' , 'encoder' ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: __A : Optional[Any] = key.replace('.emb.' , '.' ) if key.endswith('k' ): # replace vqvae.X.k with vqvae.X.codebook return key.replace('.k' , '.codebook' ) if "y_emb." in key: return key.replace('y_emb.' , 'metadata_embedding.' ) if "x_emb.emb." in key: __A : Optional[int] = key.replace('0.x_emb.emb' , 'embed_tokens' ) if "prime_state_ln" in key: return key.replace('prime_state_ln' , 'encoder.final_layer_norm' ) if ".ln" in key: return key.replace('.ln' , '.layer_norm' ) if "_ln" in key: return key.replace('_ln' , '_layer_norm' ) if "prime_state_proj" in key: return key.replace('prime_state_proj' , 'encoder.proj_in' ) if "prime_x_out" in key: return key.replace('prime_x_out' , 'encoder.lm_head' ) if "prior.x_out" in key: return key.replace('x_out' , 'fc_proj_out' ) if "x_emb" in key: return key.replace('x_emb' , 'embed_tokens' ) return key def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Any: __A : Optional[Any] = {} import re __A : List[str] = re.compile(r'encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)' ) __A : Union[str, Any] = re.compile( r'encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) __A : List[Any] = re.compile(r'encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)' ) __A : Optional[Any] = re.compile(r'decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)' ) __A : Optional[int] = re.compile( r'decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) __A : List[str] = re.compile(r'decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)' ) __A : str = re.compile(r'conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)' ) __A : Union[str, Any] = re.compile( r'conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) __A : Optional[int] = re.compile(r'conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)' ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(a ): __A : Dict = re_encoder_block_conv_in.match(a ) __A : Dict = regex_match.groups() __A : Tuple = int(groups[2] ) * 2 + int(groups[3] ) __A : Union[str, Any] = F"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" __A : Optional[Any] = re_encoder_block_conv_in.sub(a , a ) elif re_encoder_block_resnet.fullmatch(a ): __A : int = re_encoder_block_resnet.match(a ) __A : Union[str, Any] = regex_match.groups() __A : Dict = int(groups[2] ) * 2 + int(groups[3] ) __A : str = {'1': 1, '3': 2}[groups[-2]] __A : Tuple = F"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" __A : int = F"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" __A : Tuple = prefix + resnet_block __A : str = re_encoder_block_resnet.sub(a , a ) elif re_encoder_block_proj_out.fullmatch(a ): __A : List[Any] = re_encoder_block_proj_out.match(a ) __A : Tuple = regex_match.groups() __A : List[Any] = F"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" __A : List[str] = re_encoder_block_proj_out.sub(a , a ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(a ): __A : Tuple = re_decoder_block_conv_out.match(a ) __A : Dict = regex_match.groups() __A : Optional[Any] = int(groups[2] ) * 2 + int(groups[3] ) - 2 __A : Tuple = F"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" __A : int = re_decoder_block_conv_out.sub(a , a ) elif re_decoder_block_resnet.fullmatch(a ): __A : Any = re_decoder_block_resnet.match(a ) __A : Union[str, Any] = regex_match.groups() __A : str = int(groups[2] ) * 2 + int(groups[3] ) - 2 __A : int = {'1': 1, '3': 2}[groups[-2]] __A : Any = F"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" __A : int = F"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" __A : Union[str, Any] = prefix + resnet_block __A : str = re_decoder_block_resnet.sub(a , a ) elif re_decoder_block_proj_in.fullmatch(a ): __A : List[Any] = re_decoder_block_proj_in.match(a ) __A : Dict = regex_match.groups() __A : Optional[int] = F"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" __A : Any = re_decoder_block_proj_in.sub(a , a ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(a ): __A : Optional[Any] = re_prior_cond_conv_out.match(a ) __A : Tuple = regex_match.groups() __A : str = int(groups[1] ) * 2 + int(groups[2] ) - 2 __A : Tuple = F"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" __A : str = re_prior_cond_conv_out.sub(a , a ) elif re_prior_cond_resnet.fullmatch(a ): __A : Optional[int] = re_prior_cond_resnet.match(a ) __A : Optional[Any] = regex_match.groups() __A : Tuple = int(groups[1] ) * 2 + int(groups[2] ) - 2 __A : Dict = {'1': 1, '3': 2}[groups[-2]] __A : Dict = F"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" __A : Tuple = F"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" __A : List[Any] = prefix + resnet_block __A : str = re_prior_cond_resnet.sub(a , a ) elif re_prior_cond_proj_in.fullmatch(a ): __A : Optional[int] = re_prior_cond_proj_in.match(a ) __A : Union[str, Any] = regex_match.groups() __A : int = F"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" __A : int = re_prior_cond_proj_in.sub(a , a ) # keep original key else: __A : Dict = original_key __A : Any = replace_key(a ) if F"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(F"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[F"""{key_prefix}.{key}"""].shape: __A : Dict = model_state_dict[F"""{key_prefix}.{key}"""] print(F"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) __A : List[Any] = original_key __A : List[str] = original_key __A : Union[str, Any] = value return new_dict @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a=None , a=None ) -> Any: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(F"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): __A : Any = requests.get(F"""{PREFIX}{file}""" , allow_redirects=a ) os.makedirs(F"""{pytorch_dump_folder_path}/""" , exist_ok=a ) open(F"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , 'wb' ).write(r.content ) __A : Tuple = MODEL_MAPPING[model_name.split('/' )[-1]] __A : Any = JukeboxConfig.from_pretrained(a ) __A : Optional[Any] = JukeboxModel(a ) __A : str = [] __A : str = {} for i, dict_name in enumerate(a ): __A : List[Any] = torch.load(F"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )['model'] __A : Union[str, Any] = {} for k in old_dic.keys(): if k.endswith('.b' ): __A : Optional[int] = old_dic[k] elif k.endswith('.w' ): __A : List[str] = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: __A : List[str] = old_dic[k] else: __A : Dict = old_dic[k] __A : List[str] = 'vqvae' if i == 0 else F"""priors.{3 - i}""" __A : Optional[Any] = fix_jukebox_keys(a , model.state_dict() , a , a ) weight_dict.append(a ) __A : Dict = weight_dict.pop(0 ) model.vqvae.load_state_dict(a ) for i in range(len(a ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(a ).mkdir(exist_ok=a ) with open(F"""{pytorch_dump_folder_path}/mapping.json""" , 'w' ) as txtfile: json.dump(a , a ) print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(a ) return weight_dict if __name__ == "__main__": UpperCAmelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''jukebox-5b-lyrics''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''jukebox-5b-lyrics-converted''', type=str, help='''Path to the output PyTorch model directory.''', ) UpperCAmelCase : Dict = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
77
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): debug_launcher(test_script.main ) def UpperCAmelCase_ ( self ): debug_launcher(test_ops.main )
77
1
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : Tuple = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(a , a ) def _SCREAMING_SNAKE_CASE ( a ) -> Any: __A , __A : Optional[int] = emb.weight.shape __A : Union[str, Any] = nn.Linear(a , a , bias=a ) __A : Optional[Any] = emb.weight.data return lin_layer def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : Tuple = torch.load(a , map_location='cpu' ) __A : str = mam_aaa['args'] or mam_aaa['cfg']['model'] __A : str = mam_aaa['model'] remove_ignore_keys_(a ) __A : Tuple = state_dict['encoder.embed_tokens.weight'].shape[0] __A : int = MaMaaaConfig( vocab_size=a , max_position_embeddings=10_24 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) __A : Any = state_dict['decoder.embed_tokens.weight'] __A : Dict = MaMaaaForConditionalGeneration(a ) model.model.load_state_dict(a , strict=a ) __A : Optional[int] = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument('''fairseq_path''', type=str, help='''path to a model.pt on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') UpperCAmelCase : List[str] = parser.parse_args() UpperCAmelCase : Optional[int] = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
77
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Tuple = tempfile.mkdtemp() # fmt: off __A : Union[str, Any] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Dict = dict(zip(_A , range(len(_A ) ) ) ) __A : int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : Optional[Any] = {'unk_token': '<unk>'} __A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : Union[str, Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : List[str] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[str] = self.get_tokenizer() __A : Dict = self.get_rust_tokenizer() __A : Optional[Any] = self.get_image_processor() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Any = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : int = self.get_image_processor(do_normalize=_A ) __A : int = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : List[Any] = self.prepare_image_inputs() __A : Any = image_processor(_A , return_tensors='np' ) __A : Tuple = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_image_processor() __A : int = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = 'lower newer' __A : Any = processor(text=_A , return_tensors='np' ) __A : Dict = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Tuple = 'lower newer' __A : Union[str, Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[int] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Any = ['cat', 'nasa badge'] __A : List[Any] = processor(text=_A ) __A : Dict = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : int = [['cat', 'nasa badge'], ['person']] __A : str = processor(text=_A ) __A : int = 16 __A : Optional[int] = len(_A ) __A : int = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : int = 'google/owlvit-base-patch32' __A : List[str] = OwlViTProcessor.from_pretrained(_A ) __A : Tuple = ['cat', 'nasa badge'] __A : Dict = processor(text=_A ) __A : Tuple = 16 __A : str = inputs['input_ids'] __A : str = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Dict = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = self.prepare_image_inputs() __A : Tuple = self.prepare_image_inputs() __A : Any = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Union[str, Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
77
1
# This code is adapted from OpenAI's release # https://github.com/openai/human-eval/blob/master/human_eval/execution.py import contextlib import faulthandler import io import multiprocessing import os import platform import signal import tempfile def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Dict: __A : Tuple = multiprocessing.Manager() __A : int = manager.list() __A : Dict = multiprocessing.Process(target=a , args=(check_program, result, timeout) ) p.start() p.join(timeout=timeout + 1 ) if p.is_alive(): p.kill() if not result: result.append('timed out' ) return { "task_id": task_id, "passed": result[0] == "passed", "result": result[0], "completion_id": completion_id, } def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Dict: with create_tempdir(): # These system calls are needed when cleaning up tempdir. import os import shutil __A : Any = shutil.rmtree __A : Tuple = os.rmdir __A : Tuple = os.chdir # Disable functionalities that can make destructive changes to the test. reliability_guard() # Run program. try: __A : Tuple = {} with swallow_io(): with time_limit(a ): exec(a , a ) result.append('passed' ) except TimeoutException: result.append('timed out' ) except BaseException as e: result.append(F"""failed: {e}""" ) # Needed for cleaning up. __A : Dict = rmtree __A : str = rmdir __A : Optional[int] = chdir @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( a ) -> Union[str, Any]: def signal_handler(a , a ): raise TimeoutException('Timed out!' ) signal.setitimer(signal.ITIMER_REAL , a ) signal.signal(signal.SIGALRM , a ) try: yield finally: signal.setitimer(signal.ITIMER_REAL , 0 ) @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> Any: __A : Any = WriteOnlyStringIO() with contextlib.redirect_stdout(a ): with contextlib.redirect_stderr(a ): with redirect_stdin(a ): yield @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( ) -> str: with tempfile.TemporaryDirectory() as dirname: with chdir(a ): yield dirname class _A( snake_case__ ): """simple docstring""" pass class _A( io.StringIO ): """simple docstring""" def UpperCAmelCase_ ( self , *_A , **_A ): raise OSError def UpperCAmelCase_ ( self , *_A , **_A ): raise OSError def UpperCAmelCase_ ( self , *_A , **_A ): raise OSError def UpperCAmelCase_ ( self , *_A , **_A ): return False class _A( contextlib._RedirectStream ): # type: ignore """simple docstring""" UpperCamelCase : Any = '''stdin''' @contextlib.contextmanager def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: if root == ".": yield return __A : str = os.getcwd() os.chdir(a ) try: yield except BaseException as exc: raise exc finally: os.chdir(a ) def _SCREAMING_SNAKE_CASE ( a=None ) -> List[Any]: if maximum_memory_bytes is not None: import resource resource.setrlimit(resource.RLIMIT_AS , (maximum_memory_bytes, maximum_memory_bytes) ) resource.setrlimit(resource.RLIMIT_DATA , (maximum_memory_bytes, maximum_memory_bytes) ) if not platform.uname().system == "Darwin": resource.setrlimit(resource.RLIMIT_STACK , (maximum_memory_bytes, maximum_memory_bytes) ) faulthandler.disable() import builtins __A : List[Any] = None __A : Tuple = None import os __A : int = '1' __A : List[str] = None __A : Union[str, Any] = None __A : Dict = None __A : str = None __A : str = None __A : Optional[int] = None __A : Dict = None __A : int = None __A : Tuple = None __A : Optional[Any] = None __A : Optional[int] = None __A : int = None __A : str = None __A : Tuple = None __A : List[Any] = None __A : Union[str, Any] = None __A : List[str] = None __A : Optional[Any] = None __A : Union[str, Any] = None __A : Union[str, Any] = None __A : Any = None __A : Union[str, Any] = None __A : List[str] = None __A : Union[str, Any] = None __A : List[Any] = None __A : Optional[int] = None __A : Union[str, Any] = None import shutil __A : str = None __A : Dict = None __A : List[str] = None import subprocess __A : Any = None # type: ignore __A : Optional[Any] = None import sys __A : int = None __A : Any = None __A : Any = None __A : Union[str, Any] = None __A : Tuple = None
77
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase : Union[str, Any] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Tuple: for attribute in key.split('.' ): __A : Dict = getattr(a , a ) if weight_type is not None: __A : Any = getattr(a , a ).shape else: __A : Any = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __A : Union[str, Any] = value elif weight_type == "weight_g": __A : Dict = value elif weight_type == "weight_v": __A : Optional[int] = value elif weight_type == "bias": __A : int = value elif weight_type == "running_mean": __A : Union[str, Any] = value elif weight_type == "running_var": __A : Union[str, Any] = value elif weight_type == "num_batches_tracked": __A : Any = value elif weight_type == "inv_freq": __A : Optional[Any] = value else: __A : int = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]: __A : Any = [] __A : Optional[int] = fairseq_model.state_dict() __A : Union[str, Any] = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __A : int = False if "conv_layers" in name: load_conv_layer( a , a , a , a , hf_model.config.feat_extract_norm == 'group' , ) __A : Optional[int] = True else: for key, mapped_key in MAPPING.items(): __A : Any = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __A : Optional[Any] = True if "*" in mapped_key: __A : str = name.split(a )[0].split('.' )[-2] __A : int = mapped_key.replace('*' , a ) if "pos_bias_u" in name: __A : Optional[int] = None elif "pos_bias_v" in name: __A : Dict = None elif "weight_g" in name: __A : Optional[Any] = 'weight_g' elif "weight_v" in name: __A : Dict = 'weight_v' elif "bias" in name: __A : Tuple = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __A : int = 'weight' elif "running_mean" in name: __A : str = 'running_mean' elif "inv_freq" in name: __A : List[Any] = 'inv_freq' elif "running_var" in name: __A : Union[str, Any] = 'running_var' elif "num_batches_tracked" in name: __A : Optional[Any] = 'num_batches_tracked' else: __A : List[str] = None set_recursively(a , a , a , a , a ) continue if not is_used: unused_weights.append(a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Any: __A : str = full_name.split('conv_layers.' )[-1] __A : str = name.split('.' ) __A : Dict = int(items[0] ) __A : Any = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) __A : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) __A : List[str] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a ) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a=None , a=None , a=True ) -> Any: if config_path is not None: __A : Tuple = WavaVecaConformerConfig.from_pretrained(a , hidden_act='swish' ) else: __A : Optional[Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: __A : Dict = 'rotary' if is_finetuned: if dict_path: __A : Dict = Dictionary.load(a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __A : int = target_dict.pad_index __A : List[Any] = target_dict.bos_index __A : Any = target_dict.eos_index __A : Dict = len(target_dict.symbols ) __A : Optional[Any] = os.path.join(a , 'vocab.json' ) if not os.path.isdir(a ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(a ) ) return os.makedirs(a , exist_ok=a ) __A : List[str] = target_dict.indices # fairseq has the <pad> and <s> switched __A : int = 0 __A : Optional[Any] = 1 with open(a , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(a , a ) __A : Optional[Any] = WavaVecaCTCTokenizer( a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=a , ) __A : Tuple = True if config.feat_extract_norm == 'layer' else False __A : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=a , return_attention_mask=a , ) __A : Optional[int] = WavaVecaProcessor(feature_extractor=a , tokenizer=a ) processor.save_pretrained(a ) __A : List[Any] = WavaVecaConformerForCTC(a ) else: __A : List[Any] = WavaVecaConformerForPreTraining(a ) if is_finetuned: __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: __A : Optional[Any] = argparse.Namespace(task='audio_pretraining' ) __A : str = fairseq.tasks.setup_task(a ) __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=a ) __A : Tuple = model[0].eval() recursively_load_weights(a , a , not is_finetuned ) hf_wavavec.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) UpperCAmelCase : List[str] = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
77
1
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Optional[int]: # noqa: E741 while r - l > 1: __A : int = (l + r) // 2 if v[m] >= key: __A : str = m else: __A : Tuple = m # noqa: E741 return r def _SCREAMING_SNAKE_CASE ( a ) -> int: if len(a ) == 0: return 0 __A : Optional[int] = [0] * len(a ) __A : Optional[Any] = 1 __A : Optional[Any] = v[0] for i in range(1 , len(a ) ): if v[i] < tail[0]: __A : List[Any] = v[i] elif v[i] > tail[length - 1]: __A : Union[str, Any] = v[i] length += 1 else: __A : Union[str, Any] = v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
77
from abc import ABC, abstractmethod from argparse import ArgumentParser class _A( snake_case__ ): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( _A ): raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self ): raise NotImplementedError()
77
1
from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float: __A : Any = x_start __A : List[str] = fnc(a ) __A : Optional[Any] = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area __A : Any = (x_end - x_start) / steps + xa __A : List[str] = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __A : Any = xa __A : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( a ) -> int: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') UpperCAmelCase : Tuple = 10 while i <= 10_00_00: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
77
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
1
import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Optional[int] = { '''bart''': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), '''bert''': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''bert-base-cased-finetuned-mrpc''': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''dpr''': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), '''gpt2''': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''xlnet''': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''xlm''': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''xlm-roberta''': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''transfo-xl''': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''openai-gpt''': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''roberta''': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''layoutlm''': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), '''roberta-large-mnli''': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''camembert''': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''flaubert''': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''distilbert''': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''distilbert-base-distilled-squad''': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''lxmert''': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''lxmert-visual-feature-encoder''': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''ctrl''': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''albert''': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''t5''': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''electra''': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), '''wav2vec2''': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def _SCREAMING_SNAKE_CASE ( a , a , a , a , a=False , a=True ) -> List[Any]: if model_type not in MODEL_CLASSES: raise ValueError(F"""Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.""" ) __A , __A , __A , __A : List[str] = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __A : List[str] = cached_file(a , a , force_download=not use_cached_models ) __A : Tuple = config_class.from_json_file(a ) __A : Dict = True __A : Optional[Any] = True print(F"""Building TensorFlow model from configuration: {config}""" ) __A : str = model_class(a ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __A : Dict = cached_file( a , a , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __A : Optional[int] = load_pytorch_checkpoint_in_tfa_model(a , a ) if compare_with_pt_model: __A : Tuple = tf_model(tf_model.dummy_inputs , training=a ) # build the network __A : List[Any] = torch.load(a , map_location='cpu' ) __A : Optional[int] = pt_model_class.from_pretrained( pretrained_model_name_or_path=a , config=a , state_dict=a ) with torch.no_grad(): __A : Any = pt_model(**pt_model.dummy_inputs ) __A : int = pto[0].numpy() __A : List[Any] = tfo[0].numpy() __A : Optional[int] = np.amax(np.abs(np_pt - np_tf ) ) print(F"""Max absolute difference between models outputs {diff}""" ) assert diff <= 2e-2, F"""Error, model absolute difference is >2e-2: {diff}""" # Save pytorch-model print(F"""Save TensorFlow model to {tf_dump_path}""" ) tf_model.save_weights(a , save_format='h5' ) def _SCREAMING_SNAKE_CASE ( a , a , a=None , a=None , a=False , a=False , a=False , a=False , ) -> Optional[int]: if args_model_type is None: __A : Union[str, Any] = list(MODEL_CLASSES.keys() ) else: __A : List[Any] = [args_model_type] for j, model_type in enumerate(a , start=1 ): print('=' * 1_00 ) print(F""" Converting model type {j}/{len(a )}: {model_type}""" ) print('=' * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F"""Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.""" ) __A , __A , __A , __A , __A : Tuple = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __A : Union[str, Any] = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __A : List[str] = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a , a ) , start=1 ): print('-' * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F""" Skipping finetuned checkpoint {model_shortcut_name}""" ) continue __A : int = model_shortcut_name elif only_convert_finetuned_models: print(F""" Skipping not finetuned checkpoint {model_shortcut_name}""" ) continue print( F""" Converting checkpoint {i}/{len(a )}: {model_shortcut_name} - model_type {model_type}""" ) print('-' * 1_00 ) if config_shortcut_name in aws_config_map: __A : List[Any] = cached_file(a , a , force_download=not use_cached_models ) else: __A : Any = config_shortcut_name if model_shortcut_name in aws_model_maps: __A : Tuple = cached_file(a , a , force_download=not use_cached_models ) else: __A : List[str] = model_shortcut_name if os.path.isfile(a ): __A : int = 'converted_model' convert_pt_checkpoint_to_tf( model_type=a , pytorch_checkpoint_path=a , config_file=a , tf_dump_path=os.path.join(a , model_shortcut_name + '-tf_model.h5' ) , compare_with_pt_model=a , ) if remove_cached_files: os.remove(a ) os.remove(a ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_dump_path''', default=None, type=str, required=True, help='''Path to the output Tensorflow dump file.''' ) parser.add_argument( '''--model_type''', default=None, type=str, help=( F"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ '''convert all the models from AWS.''' ), ) parser.add_argument( '''--pytorch_checkpoint_path''', default=None, type=str, help=( '''Path to the PyTorch checkpoint path or shortcut name to download from AWS. ''' '''If not given, will download and convert all the checkpoints from AWS.''' ), ) parser.add_argument( '''--config_file''', default=None, type=str, help=( '''The config json file corresponding to the pre-trained model. \n''' '''This specifies the model architecture. If not given and ''' '''--pytorch_checkpoint_path is not given or is a shortcut name ''' '''use the configuration associated to the shortcut name on the AWS''' ), ) parser.add_argument( '''--compare_with_pt_model''', action='''store_true''', help='''Compare Tensorflow and PyTorch model predictions.''' ) parser.add_argument( '''--use_cached_models''', action='''store_true''', help='''Use cached models if possible instead of updating to latest checkpoint versions.''', ) parser.add_argument( '''--remove_cached_files''', action='''store_true''', help='''Remove pytorch models after conversion (save memory when converting in batches).''', ) parser.add_argument('''--only_convert_finetuned_models''', action='''store_true''', help='''Only convert finetuned models.''') UpperCAmelCase : Dict = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
77
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = ShapEPipeline UpperCamelCase : str = ['''prompt'''] UpperCamelCase : Tuple = ['''prompt'''] UpperCamelCase : Optional[int] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] UpperCamelCase : int = False @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self ): return 8 @property def UpperCAmelCase_ ( self ): __A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_A ) @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : int = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __A : Optional[Any] = PriorTransformer(**_A ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : List[str] = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __A : List[Any] = ShapERenderer(**_A ) return model def UpperCAmelCase_ ( self ): __A : List[str] = self.dummy_prior __A : Optional[int] = self.dummy_text_encoder __A : List[Any] = self.dummy_tokenizer __A : str = self.dummy_renderer __A : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=_A , clip_sample=_A , clip_sample_range=1.0 , ) __A : Any = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): if str(_A ).startswith('mps' ): __A : List[Any] = torch.manual_seed(_A ) else: __A : Dict = torch.Generator(device=_A ).manual_seed(_A ) __A : int = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def UpperCAmelCase_ ( self ): __A : Tuple = 'cpu' __A : Any = self.get_dummy_components() __A : Tuple = self.pipeline_class(**_A ) __A : List[str] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Tuple = pipe(**self.get_dummy_inputs(_A ) ) __A : int = output.images[0] __A : str = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __A : Any = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCAmelCase_ ( self ): __A : List[str] = torch_device == 'cpu' __A : Any = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_A , relax_max_difference=_A , ) def UpperCAmelCase_ ( self ): __A : Any = self.get_dummy_components() __A : Any = self.pipeline_class(**_A ) __A : Dict = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Any = 1 __A : Dict = 2 __A : Tuple = self.get_dummy_inputs(_A ) for key in inputs.keys(): if key in self.batch_params: __A : Optional[int] = batch_size * [inputs[key]] __A : Optional[int] = pipe(**_A , num_images_per_prompt=_A )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __A : Dict = ShapEPipeline.from_pretrained('openai/shap-e' ) __A : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : str = torch.Generator(device=_A ).manual_seed(0 ) __A : Tuple = pipe( 'a shark' , generator=_A , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_A , _A )
77
1
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 ): """simple docstring""" def __init__( self , _A ): __A : Union[str, Any] = parent def UpperCAmelCase_ ( self ): return {} def _SCREAMING_SNAKE_CASE ( ) -> Any: __A : List[str] = '<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>' __A : Optional[Any] = '\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( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = MarkupLMFeatureExtractor if is_bsa_available() else None def UpperCAmelCase_ ( self ): __A : List[Any] = MarkupLMFeatureExtractionTester(self ) @property def UpperCAmelCase_ ( self ): return self.feature_extract_tester.prepare_feat_extract_dict() def UpperCAmelCase_ ( self ): # Initialize feature_extractor __A : Dict = self.feature_extraction_class() # Test not batched input __A : Dict = get_html_strings()[0] __A : int = feature_extractor(_A ) # fmt: off __A : Any = [['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']] __A : Optional[int] = [['/html/head/title', '/html/body/a', '/html/body/h1', '/html/body/h2', '/html/body/p', '/html/body/p/p/b[1]', '/html/body/p/p/b[2]/i', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/b', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/p']] # fmt: on self.assertEqual(encoding.nodes , _A ) self.assertEqual(encoding.xpaths , _A ) # Test batched __A : Optional[Any] = get_html_strings() __A : Union[str, Any] = feature_extractor(_A ) # fmt: off __A : Union[str, Any] = expected_nodes + [['My First Heading', 'My first paragraph.']] __A : 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 , _A ) self.assertEqual(encoding.xpaths , _A )
77
from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if len(a ) != 2 or len(a[0] ) != 2 or len(a ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __A : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> str: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a ) -> tuple[list, list, list, list]: if len(a ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __A : str = len(a ) __A : List[Any] = matrix_length // 2 __A : List[str] = [[a[i][j] for j in range(a , a )] for i in range(a )] __A : Dict = [ [a[i][j] for j in range(a , a )] for i in range(a , a ) ] __A : int = [[a[i][j] for j in range(a )] for i in range(a )] __A : Any = [[a[i][j] for j in range(a )] for i in range(a , a )] return top_left, top_right, bot_left, bot_right def _SCREAMING_SNAKE_CASE ( a ) -> tuple[int, int]: return len(a ), len(matrix[0] ) def _SCREAMING_SNAKE_CASE ( a ) -> None: print('\n'.join(str(a ) for line in matrix ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a ) == (2, 2): return default_matrix_multiplication(a , a ) __A , __A , __A , __A : str = split_matrix(a ) __A , __A , __A , __A : List[Any] = split_matrix(a ) __A : Any = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Tuple = actual_strassen(matrix_addition(a , a ) , a ) __A : List[str] = actual_strassen(matrix_addition(a , a ) , a ) __A : Optional[int] = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Any = actual_strassen(matrix_addition(a , a ) , matrix_addition(a , a ) ) __A : Any = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = matrix_addition(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) __A : Union[str, Any] = matrix_addition(a , a ) __A : str = matrix_addition(a , a ) __A : Dict = matrix_subtraction(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) # construct the new matrix from our 4 quadrants __A : List[Any] = [] for i in range(len(a ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(a ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a )[1] != matrix_dimensions(a )[0]: __A : Dict = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"""Matrix A: {matrixa}\n""" F"""Matrix B: {matrixa}""" ) raise Exception(a ) __A : int = matrix_dimensions(a ) __A : Any = matrix_dimensions(a ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __A : List[Any] = max(*a , *a ) __A : Optional[Any] = int(math.pow(2 , math.ceil(math.loga(a ) ) ) ) __A : Union[str, Any] = matrixa __A : Optional[int] = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __A : str = actual_strassen(a , a ) # Removing the additional zeros for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] UpperCAmelCase : Optional[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
77
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: UpperCAmelCase : Optional[int] = None UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : str = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Tuple = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/tokenizer.json''', }, } UpperCAmelCase : Any = { '''camembert-base''': 5_12, } UpperCAmelCase : Optional[Any] = '''▁''' class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Any = ['''input_ids''', '''attention_mask'''] UpperCamelCase : Any = CamembertTokenizer def __init__( self , _A=None , _A=None , _A="<s>" , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A=["<s>NOTUSED", "</s>NOTUSED"] , **_A , ): # Mask token behave like a normal word, i.e. include the space before it __A : Tuple = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else mask_token super().__init__( _A , tokenizer_file=_A , bos_token=_A , eos_token=_A , sep_token=_A , cls_token=_A , unk_token=_A , pad_token=_A , mask_token=_A , additional_special_tokens=_A , **_A , ) __A : Dict = vocab_file __A : Any = False if not self.vocab_file else True def UpperCAmelCase_ ( self , _A , _A = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A : List[str] = [self.cls_token_id] __A : Dict = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[int] = [self.sep_token_id] __A : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCAmelCase_ ( self , _A , _A = None ): if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(_A ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __A : List[str] = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ): copyfile(self.vocab_file , _A ) return (out_vocab_file,)
77
def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : List[str] = [] __A : Tuple = [] __A : Union[str, Any] = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, } # Priority of each operator __A : List[str] = len(a ) if (len(a ) > 7) else 7 # Print table header for output print( 'Symbol'.center(8 ) , 'Stack'.center(a ) , 'Postfix'.center(a ) , sep=' | ' , ) print('-' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(a ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(a ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(a ) == 0: stack.append(a ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(a ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(a ) # push x to stack print( x.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format while len(a ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ' '.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format return "".join(a ) # return Postfix as str def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : List[Any] = list(infix[::-1] ) # reverse the infix equation for i in range(len(a ) ): if infix[i] == "(": __A : List[str] = ')' # change "(" to ")" elif infix[i] == ")": __A : Any = '(' # change ")" to "(" return (infix_2_postfix(''.join(a ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": UpperCAmelCase : List[str] = input('''\nEnter an Infix Equation = ''') # Input an Infix equation UpperCAmelCase : Union[str, Any] = ''''''.join(Infix.split()) # Remove spaces from the input print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
77
1
import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCAmelCase : Dict = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.14.0''', '''To fix: pip install -r examples/pytorch/audio-classification/requirements.txt''') def _SCREAMING_SNAKE_CASE ( a , a , a = 1_60_00 ) -> Any: __A : Optional[int] = int(round(sample_rate * max_length ) ) if len(a ) <= sample_length: return wav __A : Any = randint(0 , len(a ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class _A: """simple docstring""" UpperCamelCase : Optional[str] = field(default=snake_case__ , metadata={'''help''': '''Name of a dataset from the datasets package'''} ) UpperCamelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) UpperCamelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''A file containing the training audio paths and labels.'''} ) UpperCamelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''A file containing the validation audio paths and labels.'''} ) UpperCamelCase : str = field( default='''train''' , metadata={ '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\'''' } , ) UpperCamelCase : str = field( default='''validation''' , metadata={ '''help''': ( '''The name of the training data set split to use (via the datasets library). Defaults to \'validation\'''' ) } , ) UpperCamelCase : str = field( default='''audio''' , metadata={'''help''': '''The name of the dataset column containing the audio data. Defaults to \'audio\''''} , ) UpperCamelCase : str = field( default='''label''' , metadata={'''help''': '''The name of the dataset column containing the labels. Defaults to \'label\''''} ) UpperCamelCase : Optional[int] = field( default=snake_case__ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) UpperCamelCase : Optional[int] = field( default=snake_case__ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) UpperCamelCase : float = field( default=20 , metadata={'''help''': '''Audio clips will be randomly cut to this length during training if the value is set.'''} , ) @dataclass class _A: """simple docstring""" UpperCamelCase : str = field( default='''facebook/wav2vec2-base''' , metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCamelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from the Hub'''} ) UpperCamelCase : str = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) UpperCamelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''Name or path of preprocessor config.'''} ) UpperCamelCase : bool = field( default=snake_case__ , metadata={'''help''': '''Whether to freeze the feature encoder layers of the model.'''} ) UpperCamelCase : bool = field( default=snake_case__ , metadata={'''help''': '''Whether to generate an attention mask in the feature extractor.'''} ) UpperCamelCase : bool = field( default=snake_case__ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) UpperCamelCase : Optional[bool] = field( default=snake_case__ , metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''} ) UpperCamelCase : bool = field( default=snake_case__ , metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''} , ) def UpperCAmelCase_ ( self ): if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( 'The argument `--freeze_feature_extractor` is deprecated and ' 'will be removed in a future version. Use `--freeze_feature_encoder`' 'instead. Setting `freeze_feature_encoder==True`.' , _A , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( 'The argument `--freeze_feature_extractor` is deprecated and ' 'should not be used in combination with `--freeze_feature_encoder`.' 'Only make use of `--freeze_feature_encoder`.' ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __A : Optional[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __A , __A , __A : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __A , __A , __A : int = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_audio_classification' , a , a ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __A : List[Any] = training_args.get_process_log_level() logger.setLevel(a ) transformers.utils.logging.set_verbosity(a ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} """ + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. __A : Optional[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __A : List[str] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ 'Use --overwrite_output_dir to train from scratch.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Initialize our dataset and prepare it for the audio classification task. __A : int = DatasetDict() __A : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) __A : Dict = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F"""--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. """ 'Make sure to set `--audio_column_name` to the correct audio column - one of ' F"""{", ".join(raw_datasets["train"].column_names )}.""" ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F"""--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. """ 'Make sure to set `--label_column_name` to the correct text column - one of ' F"""{", ".join(raw_datasets["train"].column_names )}.""" ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy __A : Optional[int] = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. __A : Union[str, Any] = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) __A : Optional[Any] = feature_extractor.model_input_names[0] def train_transforms(a ): __A : Any = [] for audio in batch[data_args.audio_column_name]: __A : Optional[Any] = random_subsample( audio['array'] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(a ) __A : Any = feature_extractor(a , sampling_rate=feature_extractor.sampling_rate ) __A : Union[str, Any] = {model_input_name: inputs.get(a )} __A : List[Any] = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(a ): __A : Dict = [audio['array'] for audio in batch[data_args.audio_column_name]] __A : Dict = feature_extractor(a , sampling_rate=feature_extractor.sampling_rate ) __A : List[Any] = {model_input_name: inputs.get(a )} __A : Tuple = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. __A : str = raw_datasets['train'].features[data_args.label_column_name].names __A , __A : int = {}, {} for i, label in enumerate(a ): __A : str = str(a ) __A : Any = label # Load the accuracy metric from the datasets package __A : str = evaluate.load('accuracy' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(a ): __A : Optional[int] = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=a , references=eval_pred.label_ids ) __A : Union[str, Any] = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(a ) , labelaid=a , idalabel=a , finetuning_task='audio-classification' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __A : Tuple = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=a , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: __A : int = ( raw_datasets['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(a , output_all_columns=a ) if training_args.do_eval: if data_args.max_eval_samples is not None: __A : List[Any] = ( raw_datasets['eval'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(a , output_all_columns=a ) # Initialize our trainer __A : str = Trainer( model=a , args=a , train_dataset=raw_datasets['train'] if training_args.do_train else None , eval_dataset=raw_datasets['eval'] if training_args.do_eval else None , compute_metrics=a , tokenizer=a , ) # Training if training_args.do_train: __A : Dict = None if training_args.resume_from_checkpoint is not None: __A : Union[str, Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: __A : Any = last_checkpoint __A : Tuple = trainer.train(resume_from_checkpoint=a ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: __A : str = trainer.evaluate() trainer.log_metrics('eval' , a ) trainer.save_metrics('eval' , a ) # Write model card and (optionally) push to hub __A : Optional[Any] = { 'finetuned_from': model_args.model_name_or_path, 'tasks': 'audio-classification', 'dataset': data_args.dataset_name, 'tags': ['audio-classification'], } if training_args.push_to_hub: trainer.push_to_hub(**a ) else: trainer.create_model_card(**a ) if __name__ == "__main__": main()
77
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : Tuple = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json''' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase : int = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = '''mask2former''' UpperCamelCase : Any = ['''swin'''] UpperCamelCase : Union[str, Any] = {'''hidden_size''': '''hidden_dim'''} def __init__( self , _A = None , _A = 256 , _A = 256 , _A = 256 , _A = 1024 , _A = "relu" , _A = 6 , _A = 10 , _A = 8 , _A = 0.0 , _A = 2048 , _A = False , _A = False , _A = 4 , _A = 255 , _A = 100 , _A = 0.1 , _A = 2.0 , _A = 5.0 , _A = 5.0 , _A = 12544 , _A = 3.0 , _A = 0.7_5 , _A = 0.0_2 , _A = 1.0 , _A = True , _A = [4, 8, 16, 32] , _A = None , **_A , ): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) __A : Optional[int] = CONFIG_MAPPING['swin']( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=_A , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(_A , _A ): __A : Dict = backbone_config.pop('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[str] = config_class.from_dict(_A ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) __A : Optional[int] = backbone_config __A : Optional[Any] = feature_size __A : Any = mask_feature_size __A : Optional[Any] = hidden_dim __A : Union[str, Any] = encoder_feedforward_dim __A : Optional[Any] = activation_function __A : List[Any] = encoder_layers __A : Union[str, Any] = decoder_layers __A : Dict = num_attention_heads __A : Tuple = dropout __A : Dict = dim_feedforward __A : Tuple = pre_norm __A : Dict = enforce_input_projection __A : Optional[int] = common_stride __A : Optional[Any] = ignore_value __A : str = num_queries __A : List[Any] = no_object_weight __A : List[str] = class_weight __A : List[Any] = mask_weight __A : List[Any] = dice_weight __A : Tuple = train_num_points __A : Optional[Any] = oversample_ratio __A : Union[str, Any] = importance_sample_ratio __A : Union[str, Any] = init_std __A : int = init_xavier_std __A : Union[str, Any] = use_auxiliary_loss __A : Union[str, Any] = feature_strides __A : List[Any] = output_auxiliary_logits __A : Optional[Any] = decoder_layers super().__init__(**_A ) @classmethod def UpperCAmelCase_ ( cls , _A , **_A ): return cls( backbone_config=_A , **_A , ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = copy.deepcopy(self.__dict__ ) __A : List[Any] = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output
77
1
import sys def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : List[Any] = len(a ) __A : int = [[0 for x in range(a )] for x in range(a )] __A : Any = [[0 for x in range(a )] for x in range(a )] for chain_length in range(2 , a ): for a in range(1 , n - chain_length + 1 ): __A : Tuple = a + chain_length - 1 __A : Union[str, Any] = sys.maxsize for c in range(a , a ): __A : Optional[int] = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: __A : List[str] = cost __A : Union[str, Any] = c return matrix, sol def _SCREAMING_SNAKE_CASE ( a , a , a ) -> List[Any]: if i == j: print('A' + str(a ) , end=' ' ) else: print('(' , end=' ' ) print_optiomal_solution(a , a , optimal_solution[i][j] ) print_optiomal_solution(a , optimal_solution[i][j] + 1 , a ) print(')' , end=' ' ) def _SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: __A : Tuple = [30, 35, 15, 5, 10, 20, 25] __A : Any = len(a ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 __A , __A : Dict = matrix_chain_order(a ) print('No. of Operation required: ' + str(matrix[1][n - 1] ) ) print_optiomal_solution(a , 1 , n - 1 ) if __name__ == "__main__": main()
77
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : str = '''conditional_detr''' UpperCamelCase : int = ['''past_key_values'''] UpperCamelCase : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , _A=True , _A=None , _A=3 , _A=300 , _A=6 , _A=2048 , _A=8 , _A=6 , _A=2048 , _A=8 , _A=0.0 , _A=0.0 , _A=True , _A="relu" , _A=256 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1.0 , _A=False , _A="sine" , _A="resnet50" , _A=True , _A=False , _A=2 , _A=5 , _A=2 , _A=1 , _A=1 , _A=2 , _A=5 , _A=2 , _A=0.2_5 , **_A , ): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __A : List[str] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_A , _A ): __A : Tuple = backbone_config.get('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[Any] = config_class.from_dict(_A ) __A : Tuple = use_timm_backbone __A : List[str] = backbone_config __A : Dict = num_channels __A : int = num_queries __A : int = d_model __A : str = encoder_ffn_dim __A : List[str] = encoder_layers __A : Optional[Any] = encoder_attention_heads __A : Union[str, Any] = decoder_ffn_dim __A : List[Any] = decoder_layers __A : Optional[Any] = decoder_attention_heads __A : Any = dropout __A : Any = attention_dropout __A : int = activation_dropout __A : Optional[int] = activation_function __A : Union[str, Any] = init_std __A : Union[str, Any] = init_xavier_std __A : Optional[Any] = encoder_layerdrop __A : int = decoder_layerdrop __A : List[str] = encoder_layers __A : str = auxiliary_loss __A : Union[str, Any] = position_embedding_type __A : Optional[int] = backbone __A : List[str] = use_pretrained_backbone __A : List[Any] = dilation # Hungarian matcher __A : List[str] = class_cost __A : Optional[int] = bbox_cost __A : Dict = giou_cost # Loss coefficients __A : Optional[int] = mask_loss_coefficient __A : Union[str, Any] = dice_loss_coefficient __A : List[Any] = cls_loss_coefficient __A : Dict = bbox_loss_coefficient __A : Tuple = giou_loss_coefficient __A : Tuple = focal_alpha super().__init__(is_encoder_decoder=_A , **_A ) @property def UpperCAmelCase_ ( self ): return self.encoder_attention_heads @property def UpperCAmelCase_ ( self ): return self.d_model def UpperCAmelCase_ ( self ): __A : str = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __A : Dict = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = version.parse('''1.11''' ) @property def UpperCAmelCase_ ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def UpperCAmelCase_ ( self ): return 1e-5 @property def UpperCAmelCase_ ( self ): return 12
77
1
import math def _SCREAMING_SNAKE_CASE ( a = 1_00 ) -> int: __A : Union[str, Any] = sum(i * i for i in range(1 , n + 1 ) ) __A : Optional[int] = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(F"""{solution() = }""")
77
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _A( nn.Module ): """simple docstring""" def __init__( self ): super().__init__() __A : List[str] = nn.Linear(3 , 4 ) __A : Optional[Any] = nn.BatchNormad(4 ) __A : List[Any] = nn.Linear(4 , 5 ) def UpperCAmelCase_ ( self , _A ): return self.lineara(self.batchnorm(self.lineara(_A ) ) ) class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Dict = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , model.state_dict() ) __A : str = os.path.join(_A , 'index.json' ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: __A : Optional[int] = os.path.join(_A , F"""{key}.dat""" ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on the fact weights are properly loaded def UpperCAmelCase_ ( self ): __A : Dict = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: __A : Tuple = torch.randn(2 , 3 , dtype=_A ) with TemporaryDirectory() as tmp_dir: __A : int = offload_weight(_A , 'weight' , _A , {} ) __A : Union[str, Any] = os.path.join(_A , 'weight.dat' ) self.assertTrue(os.path.isfile(_A ) ) self.assertDictEqual(_A , {'weight': {'shape': [2, 3], 'dtype': str(_A ).split('.' )[1]}} ) __A : List[str] = load_offloaded_weight(_A , index['weight'] ) self.assertTrue(torch.equal(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : int = ModelForTest() __A : Union[str, Any] = model.state_dict() __A : Optional[Any] = {k: v for k, v in state_dict.items() if 'linear2' not in k} __A : str = {k: v for k, v in state_dict.items() if 'linear2' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : List[str] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) __A : Union[str, Any] = {k: v for k, v in state_dict.items() if 'weight' in k} __A : List[Any] = {k: v for k, v in state_dict.items() if 'weight' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : Optional[int] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) # Duplicates are removed __A : str = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) def UpperCAmelCase_ ( self ): __A : Dict = {'a.1': 0, 'a.10': 1, 'a.2': 2} __A : str = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1': 0, 'a.2': 2} ) __A : Optional[Any] = {'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2} __A : Any = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1.a': 0, 'a.2.a': 2} )
77
1
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 UpperCAmelCase : Dict = get_tests_dir('''fixtures''') class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # A mock response for an HTTP head request to emulate server down __A : List[str] = mock.Mock() __A : Optional[Any] = 500 __A : Union[str, Any] = {} __A : Any = HTTPError __A : int = {} # Download this model to make sure it's in the cache. __A : Any = ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request' , return_value=_A ) as mock_head: __A : int = ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit' ) # This check we did call the fake head request mock_head.assert_called() def UpperCAmelCase_ ( self ): # This test is for deprecated behavior and can be removed in v5 __A : Dict = ViTImageProcessor.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json' ) def UpperCAmelCase_ ( self ): with self.assertRaises(_A ): # config is in subfolder, the following should not work without specifying the subfolder __A : Any = AutoImageProcessor.from_pretrained('hf-internal-testing/stable-diffusion-all-variants' ) __A : Optional[Any] = AutoImageProcessor.from_pretrained( 'hf-internal-testing/stable-diffusion-all-variants' , subfolder='feature_extractor' ) self.assertIsNotNone(_A ) @is_staging_test class _A( unittest.TestCase ): """simple docstring""" @classmethod def UpperCAmelCase_ ( cls ): __A : Optional[Any] = TOKEN HfFolder.save_token(_A ) @classmethod def UpperCAmelCase_ ( cls ): try: delete_repo(token=cls._token , repo_id='test-image-processor' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-image-processor-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-image-processor' ) except HTTPError: pass def UpperCAmelCase_ ( self ): __A : Dict = ViTImageProcessor.from_pretrained(_A ) image_processor.push_to_hub('test-image-processor' , use_auth_token=self._token ) __A : str = ViTImageProcessor.from_pretrained(F"""{USER}/test-image-processor""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(_A , getattr(_A , _A ) ) # Reset repo delete_repo(token=self._token , repo_id='test-image-processor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( _A , repo_id='test-image-processor' , push_to_hub=_A , use_auth_token=self._token ) __A : int = ViTImageProcessor.from_pretrained(F"""{USER}/test-image-processor""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(_A , getattr(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : Tuple = ViTImageProcessor.from_pretrained(_A ) image_processor.push_to_hub('valid_org/test-image-processor' , use_auth_token=self._token ) __A : str = ViTImageProcessor.from_pretrained('valid_org/test-image-processor' ) for k, v in image_processor.__dict__.items(): self.assertEqual(_A , getattr(_A , _A ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-image-processor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( _A , repo_id='valid_org/test-image-processor-org' , push_to_hub=_A , use_auth_token=self._token ) __A : List[Any] = ViTImageProcessor.from_pretrained('valid_org/test-image-processor-org' ) for k, v in image_processor.__dict__.items(): self.assertEqual(_A , getattr(_A , _A ) ) def UpperCAmelCase_ ( self ): CustomImageProcessor.register_for_auto_class() __A : Tuple = CustomImageProcessor.from_pretrained(_A ) image_processor.push_to_hub('test-dynamic-image-processor' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {'AutoImageProcessor': 'custom_image_processing.CustomImageProcessor'} , ) __A : Optional[int] = AutoImageProcessor.from_pretrained( F"""{USER}/test-dynamic-image-processor""" , trust_remote_code=_A ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , 'CustomImageProcessor' )
77
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): __A : Any = data def __iter__( self ): for element in self.data: yield element def _SCREAMING_SNAKE_CASE ( a=True ) -> Any: __A : List[Any] = Accelerator(even_batches=a ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str: if iterable: __A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) ) else: __A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) ) __A : Optional[Any] = DataLoader(a , batch_size=a ) __A : Optional[int] = accelerator.prepare(a ) return dl def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]: __A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a ) __A : Tuple = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : int = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : str = create_accelerator(even_batches=a ) verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _SCREAMING_SNAKE_CASE ( ) -> str: __A : Optional[Any] = create_accelerator(even_batches=a ) __A : str = torch.nn.Linear(1 , 1 ) __A : Optional[int] = accelerator.prepare(a ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : str = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(a ): __A : Dict = ddp_model(batch[0].float() ) __A : List[str] = output.sum() loss.backward() batch_idxs.append(a ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , a ) assert "only supported for multi-GPU" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : int = True __A : Union[str, Any] = False __A : Optional[int] = create_accelerator(even_batches=a ) __A : int = torch.nn.Linear(1 , 1 ) __A : List[Any] = accelerator.prepare(a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : List[str] = train_dl.batch_sampler.even_batches __A : Dict = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Any = True __A : List[Any] = False __A : Tuple = create_accelerator(even_batches=a ) __A : List[str] = torch.nn.Linear(1 , 1 ) __A : Optional[Any] = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('ignore' ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : Tuple = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Any = create_accelerator() __A : Union[str, Any] = torch.nn.Linear(1 , 1 ) __A : str = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): pass assert issubclass(w[-1].category , a ) assert "only supported for map-style datasets" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : str = create_accelerator() accelerator.print('Test that even_batches variable ensures uniform batches across processes' ) test_default_ensures_even_batch_sizes() accelerator.print('Run tests with even_batches disabled' ) test_can_disable_even_batches() accelerator.print('Test joining uneven inputs' ) test_can_join_uneven_inputs() accelerator.print('Test overriding even_batches when joining uneven inputs' ) test_join_can_override_even_batches() accelerator.print('Test overriding even_batches for mixed dataloader types' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('Test join with non DDP distributed raises warning' ) __A : int = accelerator.state.distributed_type __A : Tuple = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(a ) __A : str = original_state if __name__ == "__main__": main()
77
1
from __future__ import annotations UpperCAmelCase : int = [] def _SCREAMING_SNAKE_CASE ( a , a , a ) -> bool: for i in range(len(a ) ): if board[row][i] == 1: return False for i in range(len(a ) ): if board[i][column] == 1: return False for i, j in zip(range(a , -1 , -1 ) , range(a , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(a , -1 , -1 ) , range(a , len(a ) ) ): if board[i][j] == 1: return False return True def _SCREAMING_SNAKE_CASE ( a , a ) -> bool: if row >= len(a ): solution.append(a ) printboard(a ) print() return True for i in range(len(a ) ): if is_safe(a , a , a ): __A : Dict = 1 solve(a , row + 1 ) __A : List[Any] = 0 return False def _SCREAMING_SNAKE_CASE ( a ) -> None: for i in range(len(a ) ): for j in range(len(a ) ): if board[i][j] == 1: print('Q' , end=' ' ) else: print('.' , end=' ' ) print() # n=int(input("The no. of queens")) UpperCAmelCase : List[Any] = 8 UpperCAmelCase : Optional[int] = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('''The total no. of solutions are :''', len(solution))
77
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : str = { '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''', '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''', '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''', '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''', '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''', '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''', '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''', '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''', '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''', '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''', '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''', '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = '''codegen''' UpperCamelCase : List[str] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ): __A : Any = vocab_size __A : Tuple = n_ctx __A : Union[str, Any] = n_positions __A : Optional[Any] = n_embd __A : Any = n_layer __A : Dict = n_head __A : Union[str, Any] = n_inner __A : List[Any] = rotary_dim __A : str = activation_function __A : Any = resid_pdrop __A : Tuple = embd_pdrop __A : Tuple = attn_pdrop __A : Union[str, Any] = layer_norm_epsilon __A : str = initializer_range __A : Optional[Any] = use_cache __A : Union[str, Any] = bos_token_id __A : Tuple = eos_token_id super().__init__( bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A ) class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A = "default" , _A = None , _A = False , ): super().__init__(_A , task=_A , patching_specs=_A , use_past=_A ) if not getattr(self._config , 'pad_token_id' , _A ): # TODO: how to do that better? __A : Dict = 0 @property def UpperCAmelCase_ ( self ): __A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) __A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'} else: __A : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase_ ( self ): return self._config.n_layer @property def UpperCAmelCase_ ( self ): return self._config.n_head def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Any = super(_A , self ).generate_dummy_inputs( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) # We need to order the input in the way they appears in the forward() __A : str = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __A , __A : Any = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Any = seqlen + 2 __A : List[str] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __A : Optional[Any] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] __A : Tuple = common_inputs['attention_mask'] if self.use_past: __A : str = ordered_inputs['attention_mask'].dtype __A : List[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self ): return 13
77
1
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaInpaintPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[Any] = KandinskyVaaInpaintPipeline UpperCamelCase : Union[str, Any] = ['''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image'''] UpperCamelCase : Optional[int] = [ '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image''', ] UpperCamelCase : Dict = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCamelCase : Optional[Any] = False @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return self.time_input_dim @property def UpperCAmelCase_ ( self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self ): return 100 @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : str = { 'in_channels': 9, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'image', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } __A : Optional[int] = UNetaDConditionModel(**_A ) return model @property def UpperCAmelCase_ ( self ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = VQModel(**self.dummy_movq_kwargs ) return model def UpperCAmelCase_ ( self ): __A : str = self.dummy_unet __A : Dict = self.dummy_movq __A : Any = DDIMScheduler( num_train_timesteps=1000 , beta_schedule='linear' , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , clip_sample=_A , set_alpha_to_one=_A , steps_offset=1 , prediction_type='epsilon' , thresholding=_A , ) __A : int = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): __A : int = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_A ) ).to(_A ) __A : Optional[int] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _A ) # create init_image __A : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(_A ) ).to(_A ) __A : Any = image.cpu().permute(0 , 2 , 3 , 1 )[0] __A : List[Any] = Image.fromarray(np.uinta(_A ) ).convert('RGB' ).resize((256, 256) ) # create mask __A : Any = np.ones((64, 64) , dtype=np.floataa ) __A : Union[str, Any] = 0 if str(_A ).startswith('mps' ): __A : int = torch.manual_seed(_A ) else: __A : str = torch.Generator(device=_A ).manual_seed(_A ) __A : Dict = { 'image': init_image, 'mask_image': mask, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 64, 'width': 64, 'num_inference_steps': 2, 'guidance_scale': 4.0, 'output_type': 'np', } return inputs def UpperCAmelCase_ ( self ): __A : Union[str, Any] = 'cpu' __A : List[Any] = self.get_dummy_components() __A : Union[str, Any] = self.pipeline_class(**_A ) __A : Optional[int] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Dict = pipe(**self.get_dummy_inputs(_A ) ) __A : List[str] = output.images __A : Any = pipe( **self.get_dummy_inputs(_A ) , return_dict=_A , )[0] __A : Any = image[0, -3:, -3:, -1] __A : Dict = image_from_tuple[0, -3:, -3:, -1] print(F"""image.shape {image.shape}""" ) assert image.shape == (1, 64, 64, 3) __A : Any = np.array( [0.5_0_7_7_5_9_0_3, 0.4_9_5_2_7_1_9_5, 0.4_8_8_2_4_5_4_3, 0.5_0_1_9_2_2_3_7, 0.4_8_6_4_4_9_0_6, 0.4_9_3_7_3_8_1_4, 0.4_7_8_0_5_9_8, 0.4_7_2_3_4_8_2_7, 0.4_8_3_2_7_8_4_8] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" def UpperCAmelCase_ ( self ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_inpaint_cat_with_hat_fp16.npy' ) __A : Any = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) __A : List[str] = np.ones((768, 768) , dtype=np.floataa ) __A : Optional[int] = 0 __A : int = 'a hat' __A : List[str] = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(_A ) __A : Any = KandinskyVaaInpaintPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-decoder-inpaint' , torch_dtype=torch.floataa ) __A : Optional[int] = pipeline.to(_A ) pipeline.set_progress_bar_config(disable=_A ) __A : List[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) __A , __A : Union[str, Any] = pipe_prior( _A , generator=_A , num_inference_steps=5 , negative_prompt='' , ).to_tuple() __A : Any = pipeline( image=_A , mask_image=_A , image_embeds=_A , negative_image_embeds=_A , generator=_A , num_inference_steps=100 , height=768 , width=768 , output_type='np' , ) __A : Optional[int] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_A , _A )
77
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase : List[Any] = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _A , ) super().__init__(*_A , **_A )
77
1
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = inspect.getfile(accelerate.test_utils ) UpperCamelCase : List[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) UpperCamelCase : List[str] = ['''accelerate''', '''launch'''] UpperCamelCase : Optional[Any] = Path.home() / '''.cache/huggingface/accelerate''' UpperCamelCase : Tuple = '''default_config.yaml''' UpperCamelCase : Optional[Any] = config_folder / config_file UpperCamelCase : Any = config_folder / '''_default_config.yaml''' UpperCamelCase : Optional[Any] = Path('''tests/test_configs''' ) @classmethod def UpperCAmelCase_ ( cls ): if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def UpperCAmelCase_ ( cls ): if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def UpperCAmelCase_ ( self ): for config in sorted(self.test_config_path.glob('**/*.yaml' ) ): with self.subTest(config_file=_A ): execute_subprocess_async( self.base_cmd + ['--config_file', str(_A ), self.test_file_path] , env=os.environ.copy() ) def UpperCAmelCase_ ( self ): execute_subprocess_async(['accelerate', 'test'] , env=os.environ.copy() ) class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = '''test-tpu''' UpperCamelCase : List[Any] = '''us-central1-a''' UpperCamelCase : List[str] = '''ls''' UpperCamelCase : Any = ['''accelerate''', '''tpu-config'''] UpperCamelCase : str = '''cd /usr/share''' UpperCamelCase : Union[str, Any] = '''tests/test_samples/test_command_file.sh''' UpperCamelCase : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def UpperCAmelCase_ ( self ): __A : Any = run_command( self.cmd + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] , return_stdout=_A , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , ) def UpperCAmelCase_ ( self ): __A : Optional[int] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] , return_stdout=_A , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , ) def UpperCAmelCase_ ( self ): __A : Tuple = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] , return_stdout=_A ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , ) def UpperCAmelCase_ ( self ): __A : List[str] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] , return_stdout=_A , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , ) def UpperCAmelCase_ ( self ): __A : Tuple = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--command', 'echo "Hello World"', '--debug', ] , return_stdout=_A , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , _A , ) def UpperCAmelCase_ ( self ): __A : Optional[int] = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] , return_stdout=_A , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command_file', self.command_file, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] , return_stdout=_A , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , ) def UpperCAmelCase_ ( self ): __A : Dict = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] , return_stdout=_A , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , ) def UpperCAmelCase_ ( self ): __A : Any = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--accelerate_version', '12.0.0', '--debug', ] , return_stdout=_A , ) self.assertIn( F"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
77
import glob import os import random from string import ascii_lowercase, digits import cva UpperCAmelCase : Dict = '''''' UpperCAmelCase : Union[str, Any] = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal) def _SCREAMING_SNAKE_CASE ( ) -> None: __A , __A : List[Any] = get_dataset(a , a ) print('Processing...' ) __A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a ) for index, image in enumerate(a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __A : Optional[int] = random_chars(32 ) __A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] __A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Success {index+1}/{len(a )} with {file_name}""" ) __A : int = [] for anno in new_annos[index]: __A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(a ) with open(F"""/{file_root}.txt""" , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]: __A : int = [] __A : List[Any] = [] for label_file in glob.glob(os.path.join(a , '*.txt' ) ): __A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(a ) as in_file: __A : Tuple = in_file.readlines() __A : Dict = os.path.join(a , F"""{label_name}.jpg""" ) __A : Dict = [] for obj_list in obj_lists: __A : int = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(a ) labels.append(a ) return img_paths, labels def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]: __A : int = [] __A : Optional[Any] = [] __A : Dict = [] for idx in range(len(a ) ): __A : Dict = [] __A : Optional[Any] = img_list[idx] path_list.append(a ) __A : Union[str, Any] = anno_list[idx] __A : Optional[Any] = cva.imread(a ) if flip_type == 1: __A : Any = cva.flip(a , a ) for bbox in img_annos: __A : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __A : Union[str, Any] = cva.flip(a , a ) for bbox in img_annos: __A : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(a ) new_imgs_list.append(a ) return new_imgs_list, new_annos_lists, path_list def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __A : List[Any] = ascii_lowercase + digits return "".join(random.choice(a ) for _ in range(a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
77
1
import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Union[str, Any]: # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file __A : List[Any] = TapasConfig.from_json_file(a ) # set absolute/relative position embeddings parameter __A : Tuple = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": __A : Union[str, Any] = TapasForQuestionAnswering(config=a ) elif task == "WTQ": # run_task_main.py hparams __A : Optional[int] = 4 __A : List[str] = True # hparam_utils.py hparams __A : int = 0.664_694 __A : List[Any] = 0.207_951 __A : Dict = 0.121_194 __A : str = True __A : List[str] = True __A : Optional[int] = False __A : str = 0.0_352_513 __A : int = TapasForQuestionAnswering(config=a ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams __A : List[Any] = 4 __A : List[Any] = False # hparam_utils.py hparams __A : Any = 36.4_519 __A : Optional[int] = 0.903_421 __A : Any = 222.088 __A : str = True __A : List[str] = True __A : Dict = True __A : Any = 0.763_141 __A : List[Any] = TapasForQuestionAnswering(config=a ) elif task == "TABFACT": __A : Optional[Any] = TapasForSequenceClassification(config=a ) elif task == "MLM": __A : Optional[Any] = TapasForMaskedLM(config=a ) elif task == "INTERMEDIATE_PRETRAINING": __A : Dict = TapasModel(config=a ) else: raise ValueError(F"""Task {task} not supported.""" ) print(F"""Building PyTorch model from configuration: {config}""" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(a , a , a ) # Save pytorch-model (weights and configuration) print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(a ) # Save tokenizer files print(F"""Save tokenizer files to {pytorch_dump_path}""" ) __A : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + 'vocab.txt' , model_max_length=5_12 ) tokenizer.save_pretrained(a ) print('Used relative position embeddings:' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": UpperCAmelCase : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''SQA''', type=str, help='''Model task for which to convert a checkpoint. Defaults to SQA.''' ) parser.add_argument( '''--reset_position_index_per_cell''', default=False, action='''store_true''', help='''Whether to use relative position embeddings or not. Defaults to True.''', ) parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--tapas_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained TAPAS model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) UpperCAmelCase : Dict = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
77
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A: """simple docstring""" def __init__( self , _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.0_2 , _A=3 , _A=4 , _A=None , ): __A : Union[str, Any] = parent __A : List[str] = batch_size __A : Optional[int] = seq_length __A : List[Any] = is_training __A : Optional[Any] = use_input_mask __A : List[Any] = use_token_type_ids __A : Optional[Any] = use_labels __A : List[str] = vocab_size __A : Optional[int] = hidden_size __A : List[Any] = num_hidden_layers __A : int = num_attention_heads __A : Dict = intermediate_size __A : Any = hidden_act __A : Union[str, Any] = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : Optional[int] = max_position_embeddings __A : Dict = type_vocab_size __A : Any = type_sequence_label_size __A : Dict = initializer_range __A : str = num_labels __A : Union[str, Any] = num_choices __A : str = scope def UpperCAmelCase_ ( self ): __A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : Optional[Any] = None if self.use_input_mask: __A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __A : Dict = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = None __A : List[Any] = None __A : List[Any] = None if self.use_labels: __A : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __A : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[str] = LlamaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A , attention_mask=_A ) __A : Any = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Dict = True __A : int = LlamaModel(_A ) model.to(_A ) model.eval() __A : str = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __A : int = model( _A , attention_mask=_A , encoder_hidden_states=_A , ) __A : List[Any] = model(_A , attention_mask=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Optional[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : int = True __A : List[Any] = True __A : List[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() # first forward pass __A : Optional[Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , ) __A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __A : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) __A : str = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __A : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : str = torch.cat([input_mask, next_mask] , dim=-1 ) __A : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['hidden_states'][0] __A : Union[str, Any] = 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 __A : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() __A : Tuple = 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 UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Tuple = config_and_inputs __A : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () UpperCamelCase : Optional[Any] = (LlamaForCausalLM,) if is_torch_available() else () UpperCamelCase : Optional[Any] = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False def UpperCAmelCase_ ( self ): __A : List[Any] = LlamaModelTester(self ) __A : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : int = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() __A : str = 3 __A : Optional[int] = input_dict['input_ids'] __A : int = input_ids.ne(1 ).to(_A ) __A : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Union[str, Any] = 3 __A : Tuple = 'single_label_classification' __A : Union[str, Any] = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[int] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Any = 3 __A : int = 'multi_label_classification' __A : int = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __A : List[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def UpperCAmelCase_ ( self ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def UpperCAmelCase_ ( self , _A ): __A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Dict = ids_tensor([1, 10] , config.vocab_size ) __A : Union[str, Any] = 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 __A : List[Any] = LlamaModel(_A ) original_model.to(_A ) original_model.eval() __A : Dict = original_model(_A ).last_hidden_state __A : int = original_model(_A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : int = {'type': scaling_type, 'factor': 1_0.0} __A : str = LlamaModel(_A ) scaled_model.to(_A ) scaled_model.eval() __A : Dict = scaled_model(_A ).last_hidden_state __A : str = 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 ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) __A : Union[str, Any] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __A : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[str] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) __A : int = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) __A : Optional[int] = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : Optional[Any] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) __A : List[Any] = model(torch.tensor(_A ) ) __A : Tuple = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # fmt: off __A : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' __A : List[str] = 'Simply put, the theory of relativity states that ' __A : Union[str, Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) __A : List[str] = tokenizer.encode(_A , return_tensors='pt' ) __A : Tuple = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=_A ) # greedy generation outputs __A : Union[str, Any] = model.generate(_A , max_new_tokens=64 , top_p=_A , temperature=1 , do_sample=_A ) __A : List[str] = tokenizer.decode(generated_ids[0] , skip_special_tokens=_A ) self.assertEqual(_A , _A )
77
1
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
77
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Dict = {'''vocab_file''': '''vocab.txt'''} UpperCAmelCase : List[Any] = { '''vocab_file''': { '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt''', } } UpperCAmelCase : str = { '''YituTech/conv-bert-base''': 5_12, '''YituTech/conv-bert-medium-small''': 5_12, '''YituTech/conv-bert-small''': 5_12, } UpperCAmelCase : List[Any] = { '''YituTech/conv-bert-base''': {'''do_lower_case''': True}, '''YituTech/conv-bert-medium-small''': {'''do_lower_case''': True}, '''YituTech/conv-bert-small''': {'''do_lower_case''': True}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Dict = VOCAB_FILES_NAMES UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Tuple = ConvBertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : List[str] = getattr(_A , normalizer_state.pop('type' ) ) __A : str = do_lower_case __A : str = strip_accents __A : Optional[Any] = tokenize_chinese_chars __A : str = normalizer_class(**_A ) __A : Any = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase_ ( self , _A , _A = None ): __A : List[Any] = [self.sep_token_id] __A : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : Union[str, Any] = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
import numpy as np from PIL import Image def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : Union[str, Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : List[Any] = 0 __A : Optional[Any] = 0 __A : List[Any] = 0 __A : Dict = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __A : Tuple = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : List[str] = 0 __A : Union[str, Any] = 0 return updated_arr def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : List[Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : Dict = 0 __A : str = 0 __A : Tuple = 0 __A : Optional[int] = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __A : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : Dict = 0 __A : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image UpperCAmelCase : int = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
77
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Optional[int] = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } UpperCAmelCase : List[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = BertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : Any = getattr(_A , normalizer_state.pop('type' ) ) __A : Union[str, Any] = do_lower_case __A : Optional[int] = strip_accents __A : List[Any] = tokenize_chinese_chars __A : int = normalizer_class(**_A ) __A : Union[str, Any] = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : Tuple = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[Any] = [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : int = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float: __A : Any = x_start __A : List[str] = fnc(a ) __A : Optional[Any] = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area __A : Any = (x_end - x_start) / steps + xa __A : List[str] = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __A : Any = xa __A : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( a ) -> int: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') UpperCAmelCase : Tuple = 10 while i <= 10_00_00: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
77
1
import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self , _A , _A ): __A : str = jnp.ones((batch_size, length) ) / length return scores def UpperCAmelCase_ ( self ): __A : Union[str, Any] = None __A : List[Any] = 20 __A : str = self._get_uniform_logits(batch_size=2 , length=_A ) # tweak scores to not be uniform anymore __A : int = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch __A : int = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax __A : List[str] = jax.nn.softmax(_A , axis=-1 ) __A : Union[str, Any] = FlaxTemperatureLogitsWarper(temperature=0.5 ) __A : Optional[Any] = FlaxTemperatureLogitsWarper(temperature=1.3 ) __A : Tuple = jax.nn.softmax(temp_dist_warper_sharper(_A , scores.copy() , cur_len=_A ) , axis=-1 ) __A : str = jax.nn.softmax(temp_dist_warper_smoother(_A , scores.copy() , cur_len=_A ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def UpperCAmelCase_ ( self ): __A : List[str] = None __A : Dict = 10 __A : Optional[Any] = 2 # create ramp distribution __A : Union[str, Any] = np.broadcast_to(np.arange(_A )[None, :] , (batch_size, vocab_size) ).copy() __A : Any = ramp_logits[1:, : vocab_size // 2] + vocab_size __A : List[Any] = FlaxTopKLogitsWarper(3 ) __A : List[Any] = top_k_warp(_A , _A , cur_len=_A ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case __A : List[str] = 5 __A : int = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) __A : List[str] = np.broadcast_to(np.arange(_A )[None, :] , (batch_size, length) ).copy() __A : Optional[int] = top_k_warp_safety_check(_A , _A , cur_len=_A ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def UpperCAmelCase_ ( self ): __A : Tuple = None __A : Optional[Any] = 10 __A : Optional[int] = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) __A : List[Any] = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.1_5, 0.3, 0.3, 0.2_5]] ) ) __A : Any = FlaxTopPLogitsWarper(0.8 ) __A : Any = np.exp(top_p_warp(_A , _A , cur_len=_A ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 __A : Optional[int] = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.2_5]] ) self.assertTrue(np.allclose(_A , _A , atol=1e-3 ) ) # check edge cases with negative and extreme logits __A : str = np.broadcast_to(np.arange(_A )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme __A : Any = ramp_logits[1] * 1_0_0.0 # make sure at least 2 tokens are kept __A : Optional[Any] = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) __A : int = top_p_warp(_A , _A , cur_len=_A ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def UpperCAmelCase_ ( self ): __A : List[Any] = 20 __A : List[Any] = 4 __A : Dict = 0 __A : Union[str, Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_A ) # check that min length is applied at length 5 __A : Optional[int] = ids_tensor((batch_size, 20) , vocab_size=20 ) __A : str = 5 __A : Union[str, Any] = self._get_uniform_logits(_A , _A ) __A : str = min_dist_processor(_A , _A , cur_len=_A ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('inf' )] ) # check that min length is not applied anymore at length 15 __A : Tuple = self._get_uniform_logits(_A , _A ) __A : Any = 15 __A : Dict = min_dist_processor(_A , _A , cur_len=_A ) self.assertFalse(jnp.isinf(_A ).any() ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = 20 __A : int = 4 __A : int = 0 __A : List[str] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_A ) # check that all scores are -inf except the bos_token_id score __A : Optional[int] = ids_tensor((batch_size, 1) , vocab_size=20 ) __A : Tuple = 1 __A : Tuple = self._get_uniform_logits(_A , _A ) __A : Optional[int] = logits_processor(_A , _A , cur_len=_A ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 __A : str = 3 __A : Optional[int] = self._get_uniform_logits(_A , _A ) __A : Tuple = logits_processor(_A , _A , cur_len=_A ) self.assertFalse(jnp.isinf(_A ).any() ) def UpperCAmelCase_ ( self ): __A : List[Any] = 20 __A : Optional[Any] = 4 __A : Dict = 0 __A : Optional[Any] = 5 __A : str = FlaxForcedEOSTokenLogitsProcessor(max_length=_A , eos_token_id=_A ) # check that all scores are -inf except the eos_token_id when max_length is reached __A : int = ids_tensor((batch_size, 4) , vocab_size=20 ) __A : int = 4 __A : Union[str, Any] = self._get_uniform_logits(_A , _A ) __A : List[str] = logits_processor(_A , _A , cur_len=_A ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached __A : Any = 3 __A : Union[str, Any] = self._get_uniform_logits(_A , _A ) __A : Optional[Any] = logits_processor(_A , _A , cur_len=_A ) self.assertFalse(jnp.isinf(_A ).any() ) def UpperCAmelCase_ ( self ): __A : int = 4 __A : List[str] = 10 __A : int = 15 __A : Any = 2 __A : Dict = 1 __A : Optional[int] = 15 # dummy input_ids and scores __A : Union[str, Any] = ids_tensor((batch_size, sequence_length) , _A ) __A : str = input_ids.copy() __A : Union[str, Any] = self._get_uniform_logits(_A , _A ) __A : int = scores.copy() # instantiate all dist processors __A : List[str] = FlaxTemperatureLogitsWarper(temperature=0.5 ) __A : Optional[int] = FlaxTopKLogitsWarper(3 ) __A : Union[str, Any] = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors __A : List[Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_A ) __A : Tuple = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_A ) __A : Any = FlaxForcedEOSTokenLogitsProcessor(max_length=_A , eos_token_id=_A ) __A : List[str] = 10 # no processor list __A : Dict = temp_dist_warp(_A , _A , cur_len=_A ) __A : Optional[int] = top_k_warp(_A , _A , cur_len=_A ) __A : Dict = top_p_warp(_A , _A , cur_len=_A ) __A : int = min_dist_proc(_A , _A , cur_len=_A ) __A : List[Any] = bos_dist_proc(_A , _A , cur_len=_A ) __A : Optional[int] = eos_dist_proc(_A , _A , cur_len=_A ) # with processor list __A : Dict = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) __A : List[str] = processor(_A , _A , cur_len=_A ) # scores should be equal self.assertTrue(jnp.allclose(_A , _A , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def UpperCAmelCase_ ( self ): __A : int = 4 __A : List[Any] = 10 __A : Tuple = 15 __A : Union[str, Any] = 2 __A : Optional[int] = 1 __A : List[str] = 15 # dummy input_ids and scores __A : int = ids_tensor((batch_size, sequence_length) , _A ) __A : Optional[int] = input_ids.copy() __A : Optional[Any] = self._get_uniform_logits(_A , _A ) __A : List[Any] = scores.copy() # instantiate all dist processors __A : Optional[int] = FlaxTemperatureLogitsWarper(temperature=0.5 ) __A : Optional[int] = FlaxTopKLogitsWarper(3 ) __A : Tuple = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors __A : Optional[int] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_A ) __A : Optional[int] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_A ) __A : Any = FlaxForcedEOSTokenLogitsProcessor(max_length=_A , eos_token_id=_A ) __A : List[str] = 10 # no processor list def run_no_processor_list(_A , _A , _A ): __A : Optional[Any] = temp_dist_warp(_A , _A , cur_len=_A ) __A : Optional[Any] = top_k_warp(_A , _A , cur_len=_A ) __A : List[Any] = top_p_warp(_A , _A , cur_len=_A ) __A : Optional[Any] = min_dist_proc(_A , _A , cur_len=_A ) __A : Tuple = bos_dist_proc(_A , _A , cur_len=_A ) __A : Dict = eos_dist_proc(_A , _A , cur_len=_A ) return scores # with processor list def run_processor_list(_A , _A , _A ): __A : Optional[Any] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) __A : List[Any] = processor(_A , _A , cur_len=_A ) return scores __A : Dict = jax.jit(_A ) __A : Optional[Any] = jax.jit(_A ) __A : List[str] = jitted_run_no_processor_list(_A , _A , _A ) __A : List[Any] = jitted_run_processor_list(_A , _A , _A ) # scores should be equal self.assertTrue(jnp.allclose(_A , _A , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
77
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def _SCREAMING_SNAKE_CASE ( ) -> None: print('Making key files...' ) make_key_files('rsa' , 10_24 ) print('Key files generation successful.' ) def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]: print('Generating prime p...' ) __A : Optional[Any] = rabinMiller.generate_large_prime(a ) print('Generating prime q...' ) __A : Union[str, Any] = rabinMiller.generate_large_prime(a ) __A : Tuple = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...' ) while True: __A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1: break print('Calculating d that is mod inverse of e...' ) __A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) ) __A : Dict = (n, e) __A : Dict = (n, d) return (public_key, private_key) def _SCREAMING_SNAKE_CASE ( a , a ) -> None: if os.path.exists(F"""{name}_pubkey.txt""" ) or os.path.exists(F"""{name}_privkey.txt""" ): print('\nWARNING:' ) print( F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n""" 'Use a different name or delete these files and re-run this program.' ) sys.exit() __A , __A : Optional[int] = generate_key(a ) print(F"""\nWriting public key to file {name}_pubkey.txt...""" ) with open(F"""{name}_pubkey.txt""" , 'w' ) as out_file: out_file.write(F"""{key_size},{public_key[0]},{public_key[1]}""" ) print(F"""Writing private key to file {name}_privkey.txt...""" ) with open(F"""{name}_privkey.txt""" , 'w' ) as out_file: out_file.write(F"""{key_size},{private_key[0]},{private_key[1]}""" ) if __name__ == "__main__": main()
77
1
UpperCAmelCase : List[Any] = 0 # The first color of the flag. UpperCAmelCase : str = 1 # The second color of the flag. UpperCAmelCase : List[Any] = 2 # The third color of the flag. UpperCAmelCase : Optional[Any] = (red, white, blue) def _SCREAMING_SNAKE_CASE ( a ) -> list: if not sequence: return [] if len(a ) == 1: return list(a ) __A : List[str] = 0 __A : List[str] = len(a ) - 1 __A : str = 0 while mid <= high: if sequence[mid] == colors[0]: __A , __A : Dict = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: __A , __A : Any = sequence[high], sequence[mid] high -= 1 else: __A : List[Any] = F"""The elements inside the sequence must contains only {colors} values""" raise ValueError(a ) return sequence if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase : Tuple = input('''Enter numbers separated by commas:\n''').strip() UpperCAmelCase : str = [int(item.strip()) for item in user_input.split(''',''')] print(F"""{dutch_national_flag_sort(unsorted)}""")
77
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ProphetNetTokenizer UpperCamelCase : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() __A : Any = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = 'UNwant\u00E9d,running' __A : List[str] = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class(self.vocab_file ) __A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase_ ( self ): __A : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCAmelCase_ ( self ): __A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __A : Optional[int] = {} for i, token in enumerate(_A ): __A : Tuple = i __A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __A : str = tokenizer(_A , padding=_A , return_tensors='pt' ) self.assertIsInstance(_A , _A ) __A : List[str] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A ) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A ) __A : str = tokenizer.build_inputs_with_special_tokens(_A ) __A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
77
1
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 _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Any = tf.convert_to_tensor( [ [ 8.2_2_2_0_9_9_1, # 3rd highest value; idx. 0 -0.5_6_2_0_0_4_4, 5.2_3_2_2_9_7_5_2, 4.0_3_8_6_3_9_3, -6.8_7_9_8_3_7_8, -0.5_4_7_8_5_8_0_2, -3.2_0_1_2_1_5_3, 2.9_2_7_7_7_1_7_6, 1.8_8_1_7_1_9_5_3, 7.3_5_3_4_1_2_7_6, # 5th highest value; idx. 9 8.4_3_2_0_7_8_3_3, # 2nd highest value; idx. 10 -9.8_5_7_1_1_8_3_6, -5.9_6_2_0_9_2_3_6, -1.1_3_0_3_9_1_6_1, -7.1_1_1_5_2_9_4, -0.8_3_6_9_6_3_3, -5.3_1_8_6_4_0_8, 7.0_6_4_2_7_4_0_7, 0.8_1_3_6_9_3_4_4, -0.8_2_0_2_3_8_1_7, -5.9_1_7_9_7_9_6, 0.5_8_8_1_3_4_4_3, -6.9_9_7_7_8_4_3_8, 4.7_1_5_5_1_1_8_9, -0.1_8_7_7_1_6_3_7, 7.4_4_0_2_0_7_5_9, # 4th highest value; idx. 25 9.3_8_4_5_0_9_8_7, # 1st highest value; idx. 26 2.1_2_6_6_2_9_4_1, -9.3_2_5_6_2_0_3_8, 2.3_5_6_5_2_5_2_2, ], # cummulative prob of 5 highest values <= 0.6 [ 0.5_8_4_2_5_5_1_8, 4.5_3_1_3_9_2_3_8, -5.5_7_5_1_0_4_6_4, -6.2_8_0_3_0_6_9_9, -7.1_9_5_2_9_5_0_3, -4.0_2_1_2_2_5_5_1, 1.3_9_3_3_7_0_3_7, -6.0_6_7_0_7_0_5_7, 1.5_9_4_8_0_5_1_7, -9.6_4_3_1_1_9, 0.0_3_9_0_7_7_9_9, 0.6_7_2_3_1_7_6_2, -8.8_8_2_0_6_7_2_6, 6.2_7_1_1_5_9_2_2, # 4th highest value; idx. 13 2.2_8_5_2_0_7_2_3, 4.8_2_7_6_7_5_0_6, 4.3_0_4_2_1_3_6_8, 8.8_2_7_5_3_1_3, # 2nd highest value; idx. 17 5.4_4_0_2_9_9_5_8, # 5th highest value; idx. 18 -4.4_7_3_5_7_9_4, 7.3_8_5_7_9_5_3_6, # 3rd highest value; idx. 20 -2.9_1_0_5_1_6_6_3, 2.6_1_9_4_6_0_7_7, -2.5_6_7_4_7_6_2, -9.4_8_9_5_9_3_0_2, -4.0_2_9_2_2_6_4_5, -1.3_5_4_1_6_9_1_8, 9.6_7_7_0_2_3_2_3, # 1st highest value; idx. 27 -5.8_9_4_7_8_5_5_3, 1.8_5_3_7_0_4_6_7, ], # cummulative prob of 5 highest values <= 0.6 ] , dtype=tf.floataa , ) __A : Union[str, Any] = tf.convert_to_tensor( [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]] , dtype=tf.intaa , ) # expected non filtered idx as noted above __A : int = tf.convert_to_tensor( [8.2_2_2_0_9_9, 7.3_5_3_4_1_2_6, 8.4_3_2_0_7_8, 7.4_4_0_2_0_7_5, 9.3_8_4_5_1, 6.2_7_1_1_5_9, 8.8_2_7_5_3_1, 5.4_4_0_2_9_9_5, 7.3_8_5_7_9_5_6, 9.6_7_7_0_2_3] , dtype=tf.floataa , ) # expected non filtered values as noted above __A : List[Any] = tf_top_k_top_p_filtering(_A , top_k=10 , top_p=0.6 , min_tokens_to_keep=4 ) __A : List[str] = output[output != -float('inf' )] __A : int = tf.cast( tf.where(tf.not_equal(_A , tf.constant(-float('inf' ) , dtype=tf.floataa ) ) ) , dtype=tf.intaa , ) tf.debugging.assert_near(_A , _A , rtol=1e-1_2 ) tf.debugging.assert_equal(_A , _A ) @require_tf class _A( unittest.TestCase , snake_case__ ): """simple docstring""" if is_tf_available(): UpperCamelCase : Tuple = { '''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 UpperCAmelCase_ ( self ): # TF-only test: tf.saved_model export __A : int = TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __A : str = 2 __A : int = 2 class _A( tf.Module ): """simple docstring""" def __init__( self , _A ): super(_A , self ).__init__() __A : Any = 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=_A , ) def UpperCAmelCase_ ( self , _A , _A ): __A : Union[str, Any] = self.model.generate( input_ids=_A , attention_mask=_A , max_new_tokens=_A , return_dict_in_generate=_A , ) return {"sequences": outputs["sequences"]} __A : Optional[Any] = [[2, 0], [102, 103]] __A : Tuple = [[1, 0], [1, 1]] __A : List[Any] = DummyModel(model=_A ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(_A , _A , signatures={'serving_default': dummy_model.serving} ) __A : Dict = tf.saved_model.load(_A ).signatures['serving_default'] for batch_size in range(1 , len(_A ) + 1 ): __A : List[Any] = { 'input_ids': tf.constant(dummy_input_ids[:batch_size] ), 'attention_mask': tf.constant(dummy_attention_masks[:batch_size] ), } __A : str = serving_func(**_A )['sequences'] __A : List[Any] = test_model.generate(**_A , max_new_tokens=_A ) tf.debugging.assert_equal(_A , _A ) @slow def UpperCAmelCase_ ( self ): # TF-only test: tf.saved_model export __A : Optional[int] = TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __A : int = 1 __A : List[str] = 2 class _A( tf.Module ): """simple docstring""" def __init__( self , _A ): super(_A , self ).__init__() __A : Tuple = 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=_A , ) def UpperCAmelCase_ ( self , _A , _A ): __A : int = self.model.generate( input_ids=_A , attention_mask=_A , max_new_tokens=_A , return_dict_in_generate=_A , ) return {"sequences": outputs["sequences"]} __A : List[str] = [[2], [102, 103]] __A : Optional[Any] = [[1], [1, 1]] __A : List[str] = DummyModel(model=_A ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(_A , _A , signatures={'serving_default': dummy_model.serving} ) __A : int = tf.saved_model.load(_A ).signatures['serving_default'] for input_row in range(len(_A ) ): __A : str = { 'input_ids': tf.constant([dummy_input_ids[input_row]] ), 'attention_mask': tf.constant([dummy_attention_masks[input_row]] ), } __A : Tuple = serving_func(**_A )['sequences'] __A : Dict = test_model.generate(**_A , max_new_tokens=_A ) tf.debugging.assert_equal(_A , _A ) @slow @require_tensorflow_text def UpperCAmelCase_ ( self ): # TF-only test: tf.saved_model export 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=_A ) class _A( tf.keras.layers.Layer ): """simple docstring""" def __init__( self ): super().__init__() __A : Any = text.SentencepieceTokenizer( model=tf.io.gfile.GFile(os.path.join(_A , 'spiece.model' ) , 'rb' ).read() ) __A : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained('hf-internal-testing/tiny-random-t5' ) def UpperCAmelCase_ ( self , _A , *_A , **_A ): __A : Tuple = self.tokenizer.tokenize(_A ) __A , __A : Optional[int] = text.pad_model_inputs( _A , max_seq_length=64 , pad_value=self.model.config.pad_token_id ) __A : str = self.model.generate(input_ids=_A , attention_mask=_A ) return self.tokenizer.detokenize(_A ) __A : int = CompleteSentenceTransformer() __A : Any = tf.keras.layers.Input(shape=(1,) , dtype=tf.string , name='inputs' ) __A : List[Any] = complete_model(_A ) __A : List[Any] = tf.keras.Model(_A , _A ) keras_model.save(_A ) def UpperCAmelCase_ ( self ): # Has PT equivalent: this test relies on random sampling __A : Optional[int] = { 'do_sample': True, 'num_beams': 1, 'top_p': 0.7, 'top_k': 10, 'temperature': 0.7, } __A : Union[str, Any] = 14 __A : Optional[Any] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __A : Union[str, Any] = 'Hello, my dog is cute and' __A : Optional[int] = tokenizer(_A , return_tensors='tf' ) __A : Dict = TFAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __A : List[str] = 638 # forces the generation to happen on CPU, to avoid GPU-related quirks with tf.device(':/CPU:0' ): tf.random.set_seed(0 ) __A : Union[str, Any] = model.generate(**_A , eos_token_id=_A , **_A ) self.assertTrue(expectation == len(generated_tokens[0] ) ) __A : List[str] = [638, 198] with tf.device(':/CPU:0' ): tf.random.set_seed(0 ) __A : Dict = model.generate(**_A , eos_token_id=_A , **_A ) self.assertTrue(expectation == len(generated_tokens[0] ) ) def UpperCAmelCase_ ( self ): # Has PT equivalent: ample use of framework-specific code __A : Tuple = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-bart' ) __A : Optional[Any] = 'Hugging Face is a technology company based in New York and Paris.' __A : Optional[Any] = bart_tokenizer(_A , return_tensors='tf' ).input_ids __A : List[Any] = TFBartForConditionalGeneration.from_pretrained('hf-internal-testing/tiny-random-bart' ) __A : str = bart_model.generate(_A ).numpy() class _A( snake_case__ ): """simple docstring""" def UpperCAmelCase_ ( self , _A , _A=None , **_A ): return super().call(_A , **_A ) __A : Any = FakeBart.from_pretrained('hf-internal-testing/tiny-random-bart' ) __A : Tuple = bart_model.generate(_A , foo='bar' ).numpy() self.assertTrue(np.array_equal(_A , _A ) ) class _A( bart_model.model.encoder.__class__ ): """simple docstring""" def UpperCAmelCase_ ( self , _A , **_A ): return super().call(_A , **_A ) __A : Union[str, Any] = FakeEncoder(bart_model.config , bart_model.model.shared ) __A : Any = fake_encoder # Normal generation still works (the output will be different because the encoder weights are different) __A : Tuple = bart_model.generate(_A ).numpy() with self.assertRaises(_A ): # FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo" bart_model.generate(_A , foo='bar' )
77
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Optional[int] = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } UpperCAmelCase : List[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = BertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : Any = getattr(_A , normalizer_state.pop('type' ) ) __A : Union[str, Any] = do_lower_case __A : Optional[int] = strip_accents __A : List[Any] = tokenize_chinese_chars __A : int = normalizer_class(**_A ) __A : Union[str, Any] = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : Tuple = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[Any] = [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : int = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
1
import heapq as hq import math from collections.abc import Iterator class _A: """simple docstring""" def __init__( self , _A ): __A : Tuple = str(id_ ) __A : Optional[int] = None __A : List[str] = None __A : int = [] __A : int = {} # {vertex:distance} def __lt__( self , _A ): return self.key < other.key def __repr__( self ): return self.id def UpperCAmelCase_ ( self , _A ): self.neighbors.append(_A ) def UpperCAmelCase_ ( self , _A , _A ): __A : str = weight def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> str: # 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] , a ) graph[b - 1].add_edge(graph[a - 1] , a ) def _SCREAMING_SNAKE_CASE ( a , a ) -> list: __A : Optional[Any] = [] for u in graph: __A : str = math.inf __A : int = None __A : Tuple = 0 __A : Union[str, Any] = graph[:] while q: __A : Tuple = min(a ) q.remove(a ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): __A : Dict = u __A : List[Any] = u.edges[v.id] for i in range(1 , len(a ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _SCREAMING_SNAKE_CASE ( a , a ) -> Iterator[tuple]: for u in graph: __A : Any = math.inf __A : Any = None __A : Optional[int] = 0 __A : Any = list(a ) hq.heapify(a ) while h: __A : Optional[Any] = hq.heappop(a ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): __A : Optional[int] = u __A : Dict = u.edges[v.id] hq.heapify(a ) for i in range(1 , len(a ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _SCREAMING_SNAKE_CASE ( ) -> None: pass if __name__ == "__main__": import doctest doctest.testmod()
77
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): debug_launcher(test_script.main ) def UpperCAmelCase_ ( self ): debug_launcher(test_ops.main )
77
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = ShapEPipeline UpperCamelCase : str = ['''prompt'''] UpperCamelCase : Tuple = ['''prompt'''] UpperCamelCase : Optional[int] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] UpperCamelCase : int = False @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self ): return 8 @property def UpperCAmelCase_ ( self ): __A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_A ) @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : int = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __A : Optional[Any] = PriorTransformer(**_A ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : List[str] = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __A : List[Any] = ShapERenderer(**_A ) return model def UpperCAmelCase_ ( self ): __A : List[str] = self.dummy_prior __A : Optional[int] = self.dummy_text_encoder __A : List[Any] = self.dummy_tokenizer __A : str = self.dummy_renderer __A : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=_A , clip_sample=_A , clip_sample_range=1.0 , ) __A : Any = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): if str(_A ).startswith('mps' ): __A : List[Any] = torch.manual_seed(_A ) else: __A : Dict = torch.Generator(device=_A ).manual_seed(_A ) __A : int = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def UpperCAmelCase_ ( self ): __A : Tuple = 'cpu' __A : Any = self.get_dummy_components() __A : Tuple = self.pipeline_class(**_A ) __A : List[str] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Tuple = pipe(**self.get_dummy_inputs(_A ) ) __A : int = output.images[0] __A : str = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __A : Any = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCAmelCase_ ( self ): __A : List[str] = torch_device == 'cpu' __A : Any = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_A , relax_max_difference=_A , ) def UpperCAmelCase_ ( self ): __A : Any = self.get_dummy_components() __A : Any = self.pipeline_class(**_A ) __A : Dict = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Any = 1 __A : Dict = 2 __A : Tuple = self.get_dummy_inputs(_A ) for key in inputs.keys(): if key in self.batch_params: __A : Optional[int] = batch_size * [inputs[key]] __A : Optional[int] = pipe(**_A , num_images_per_prompt=_A )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __A : Dict = ShapEPipeline.from_pretrained('openai/shap-e' ) __A : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : str = torch.Generator(device=_A ).manual_seed(0 ) __A : Tuple = pipe( 'a shark' , generator=_A , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_A , _A )
77
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Tuple = tempfile.mkdtemp() # fmt: off __A : Union[str, Any] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Dict = dict(zip(_A , range(len(_A ) ) ) ) __A : int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : Optional[Any] = {'unk_token': '<unk>'} __A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : Union[str, Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : List[str] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[str] = self.get_tokenizer() __A : Dict = self.get_rust_tokenizer() __A : Optional[Any] = self.get_image_processor() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Any = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : int = self.get_image_processor(do_normalize=_A ) __A : int = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : List[Any] = self.prepare_image_inputs() __A : Any = image_processor(_A , return_tensors='np' ) __A : Tuple = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_image_processor() __A : int = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = 'lower newer' __A : Any = processor(text=_A , return_tensors='np' ) __A : Dict = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Tuple = 'lower newer' __A : Union[str, Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[int] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Any = ['cat', 'nasa badge'] __A : List[Any] = processor(text=_A ) __A : Dict = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : int = [['cat', 'nasa badge'], ['person']] __A : str = processor(text=_A ) __A : int = 16 __A : Optional[int] = len(_A ) __A : int = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : int = 'google/owlvit-base-patch32' __A : List[str] = OwlViTProcessor.from_pretrained(_A ) __A : Tuple = ['cat', 'nasa badge'] __A : Dict = processor(text=_A ) __A : Tuple = 16 __A : str = inputs['input_ids'] __A : str = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Dict = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = self.prepare_image_inputs() __A : Tuple = self.prepare_image_inputs() __A : Any = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Union[str, Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
77
1
import os from datetime import datetime as dt from github import Github UpperCAmelCase : List[Any] = [ '''good first issue''', '''good second issue''', '''good difficult issue''', '''enhancement''', '''new pipeline/model''', '''new scheduler''', '''wip''', ] def _SCREAMING_SNAKE_CASE ( ) -> Tuple: __A : Tuple = Github(os.environ['GITHUB_TOKEN'] ) __A : Tuple = g.get_repo('huggingface/diffusers' ) __A : Any = repo.get_issues(state='open' ) for issue in open_issues: __A : int = sorted(issue.get_comments() , key=lambda a : i.created_at , reverse=a ) __A : Any = comments[0] if len(a ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state='closed' ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state='open' ) issue.remove_from_labels('stale' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( 'This issue has been automatically marked as stale because it has not had ' 'recent activity. If you think this still needs to be addressed ' 'please comment on this thread.\n\nPlease note that issues that do not follow the ' '[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) ' 'are likely to be ignored.' ) issue.add_to_labels('stale' ) if __name__ == "__main__": main()
77
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase : Union[str, Any] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Tuple: for attribute in key.split('.' ): __A : Dict = getattr(a , a ) if weight_type is not None: __A : Any = getattr(a , a ).shape else: __A : Any = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __A : Union[str, Any] = value elif weight_type == "weight_g": __A : Dict = value elif weight_type == "weight_v": __A : Optional[int] = value elif weight_type == "bias": __A : int = value elif weight_type == "running_mean": __A : Union[str, Any] = value elif weight_type == "running_var": __A : Union[str, Any] = value elif weight_type == "num_batches_tracked": __A : Any = value elif weight_type == "inv_freq": __A : Optional[Any] = value else: __A : int = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]: __A : Any = [] __A : Optional[int] = fairseq_model.state_dict() __A : Union[str, Any] = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __A : int = False if "conv_layers" in name: load_conv_layer( a , a , a , a , hf_model.config.feat_extract_norm == 'group' , ) __A : Optional[int] = True else: for key, mapped_key in MAPPING.items(): __A : Any = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __A : Optional[Any] = True if "*" in mapped_key: __A : str = name.split(a )[0].split('.' )[-2] __A : int = mapped_key.replace('*' , a ) if "pos_bias_u" in name: __A : Optional[int] = None elif "pos_bias_v" in name: __A : Dict = None elif "weight_g" in name: __A : Optional[Any] = 'weight_g' elif "weight_v" in name: __A : Dict = 'weight_v' elif "bias" in name: __A : Tuple = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __A : int = 'weight' elif "running_mean" in name: __A : str = 'running_mean' elif "inv_freq" in name: __A : List[Any] = 'inv_freq' elif "running_var" in name: __A : Union[str, Any] = 'running_var' elif "num_batches_tracked" in name: __A : Optional[Any] = 'num_batches_tracked' else: __A : List[str] = None set_recursively(a , a , a , a , a ) continue if not is_used: unused_weights.append(a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Any: __A : str = full_name.split('conv_layers.' )[-1] __A : str = name.split('.' ) __A : Dict = int(items[0] ) __A : Any = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) __A : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) __A : List[str] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a ) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a=None , a=None , a=True ) -> Any: if config_path is not None: __A : Tuple = WavaVecaConformerConfig.from_pretrained(a , hidden_act='swish' ) else: __A : Optional[Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: __A : Dict = 'rotary' if is_finetuned: if dict_path: __A : Dict = Dictionary.load(a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __A : int = target_dict.pad_index __A : List[Any] = target_dict.bos_index __A : Any = target_dict.eos_index __A : Dict = len(target_dict.symbols ) __A : Optional[Any] = os.path.join(a , 'vocab.json' ) if not os.path.isdir(a ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(a ) ) return os.makedirs(a , exist_ok=a ) __A : List[str] = target_dict.indices # fairseq has the <pad> and <s> switched __A : int = 0 __A : Optional[Any] = 1 with open(a , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(a , a ) __A : Optional[Any] = WavaVecaCTCTokenizer( a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=a , ) __A : Tuple = True if config.feat_extract_norm == 'layer' else False __A : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=a , return_attention_mask=a , ) __A : Optional[int] = WavaVecaProcessor(feature_extractor=a , tokenizer=a ) processor.save_pretrained(a ) __A : List[Any] = WavaVecaConformerForCTC(a ) else: __A : List[Any] = WavaVecaConformerForPreTraining(a ) if is_finetuned: __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: __A : Optional[Any] = argparse.Namespace(task='audio_pretraining' ) __A : str = fairseq.tasks.setup_task(a ) __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=a ) __A : Tuple = model[0].eval() recursively_load_weights(a , a , not is_finetuned ) hf_wavavec.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) UpperCAmelCase : List[str] = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
77
1
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def _SCREAMING_SNAKE_CASE ( a , a , a , a , a=True , a="pt" ) -> List[Any]: __A : Dict = {'add_prefix_space': True} if isinstance(a , a ) and not line.startswith(' ' ) else {} __A : Any = padding_side return tokenizer( [line] , max_length=a , padding='max_length' if pad_to_max_length else None , truncation=a , return_tensors=a , add_special_tokens=a , **a , ) def _SCREAMING_SNAKE_CASE ( a , a , a=None , ) -> List[str]: __A : Dict = input_ids.ne(a ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A , _A , _A , _A="train" , _A=None , _A=None , _A=None , _A="" , ): super().__init__() __A : Optional[int] = Path(_A ).joinpath(type_path + '.source' ) __A : Dict = Path(_A ).joinpath(type_path + '.target' ) __A : int = self.get_char_lens(self.src_file ) __A : Optional[int] = max_source_length __A : List[Any] = max_target_length assert min(self.src_lens ) > 0, F"""found empty line in {self.src_file}""" __A : Union[str, Any] = tokenizer __A : Optional[int] = prefix if n_obs is not None: __A : Optional[int] = self.src_lens[:n_obs] __A : Optional[int] = src_lang __A : Any = tgt_lang def __len__( self ): return len(self.src_lens ) def __getitem__( self , _A ): __A : str = index + 1 # linecache starts at 1 __A : List[Any] = self.prefix + linecache.getline(str(self.src_file ) , _A ).rstrip('\n' ) __A : List[str] = linecache.getline(str(self.tgt_file ) , _A ).rstrip('\n' ) assert source_line, F"""empty source line for index {index}""" assert tgt_line, F"""empty tgt line for index {index}""" # Need to add eos token manually for T5 if isinstance(self.tokenizer , _A ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __A : List[str] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _A ) else self.tokenizer ) __A : Any = self.tokenizer.generator if isinstance(self.tokenizer , _A ) else self.tokenizer __A : List[str] = encode_line(_A , _A , self.max_source_length , 'right' ) __A : Optional[Any] = encode_line(_A , _A , self.max_target_length , 'right' ) __A : List[str] = source_inputs['input_ids'].squeeze() __A : Any = target_inputs['input_ids'].squeeze() __A : List[Any] = source_inputs['attention_mask'].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def UpperCAmelCase_ ( _A ): return [len(_A ) for x in Path(_A ).open().readlines()] def UpperCAmelCase_ ( self , _A ): __A : Tuple = torch.stack([x['input_ids'] for x in batch] ) __A : Tuple = torch.stack([x['attention_mask'] for x in batch] ) __A : Optional[int] = torch.stack([x['decoder_input_ids'] for x in batch] ) __A : Tuple = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _A ) else self.tokenizer.pad_token_id ) __A : List[str] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _A ) else self.tokenizer.pad_token_id ) __A : Union[str, Any] = trim_batch(_A , _A ) __A , __A : str = trim_batch(_A , _A , attention_mask=_A ) __A : Union[str, Any] = { 'input_ids': source_ids, 'attention_mask': source_mask, 'decoder_input_ids': y, } return batch UpperCAmelCase : Dict = getLogger(__name__) def _SCREAMING_SNAKE_CASE ( a ) -> Any: return list(itertools.chain.from_iterable(a ) ) def _SCREAMING_SNAKE_CASE ( a ) -> None: __A : List[str] = get_git_info() save_json(a , os.path.join(a , 'git_log.json' ) ) def _SCREAMING_SNAKE_CASE ( a , a , a=4 , **a ) -> str: with open(a , 'w' ) as f: json.dump(a , a , indent=a , **a ) def _SCREAMING_SNAKE_CASE ( a ) -> str: with open(a ) as f: return json.load(a ) def _SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: __A : List[str] = git.Repo(search_parent_directories=a ) __A : Dict = { 'repo_id': str(a ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), 'hostname': str(socket.gethostname() ), } return repo_infos def _SCREAMING_SNAKE_CASE ( a , a ) -> List: return list(map(a , a ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Dict: with open(a , 'wb' ) as f: return pickle.dump(a , a ) def _SCREAMING_SNAKE_CASE ( a ) -> str: def remove_articles(a ): return re.sub(r'\b(a|an|the)\b' , ' ' , a ) def white_space_fix(a ): return " ".join(text.split() ) def remove_punc(a ): __A : Dict = 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(a ) ) ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: __A : Any = normalize_answer(a ).split() __A : List[Any] = normalize_answer(a ).split() __A : str = Counter(a ) & Counter(a ) __A : Tuple = sum(common.values() ) if num_same == 0: return 0 __A : Union[str, Any] = 1.0 * num_same / len(a ) __A : List[Any] = 1.0 * num_same / len(a ) __A : List[str] = (2 * precision * recall) / (precision + recall) return fa def _SCREAMING_SNAKE_CASE ( a , a ) -> str: return normalize_answer(a ) == normalize_answer(a ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Dict: assert len(a ) == len(a ) __A : Dict = 0 for hypo, pred in zip(a , a ): em += exact_match_score(a , a ) if len(a ) > 0: em /= len(a ) return {"em": em} def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: return model_prefix.startswith('rag' ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Dict: __A : List[Any] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __A : str = 'dropout_rate' for p in extra_params: if getattr(a , a , a ): if not hasattr(a , a ) and not hasattr(a , equivalent_param[p] ): logger.info('config doesn\'t have a `{}` attribute'.format(a ) ) delattr(a , a ) continue __A : List[Any] = p if hasattr(a , a ) else equivalent_param[p] setattr(a , a , getattr(a , a ) ) delattr(a , a ) return hparams, config
77
from abc import ABC, abstractmethod from argparse import ArgumentParser class _A( snake_case__ ): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( _A ): raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self ): raise NotImplementedError()
77
1
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class _A( snake_case__ ): """simple docstring""" UpperCamelCase : torch.FloatTensor class _A( snake_case__ , snake_case__ ): """simple docstring""" @register_to_config def __init__( self , _A = 32 , _A = 64 , _A = 20 , _A = 768 , _A=77 , _A=4 , _A = 0.0 , _A = "silu" , _A = None , _A = None , _A = "linear" , _A = "prd" , _A = None , _A = None , _A = None , ): super().__init__() __A : List[str] = num_attention_heads __A : Optional[int] = attention_head_dim __A : Optional[int] = num_attention_heads * attention_head_dim __A : Any = additional_embeddings __A : str = time_embed_dim or inner_dim __A : Union[str, Any] = embedding_proj_dim or embedding_dim __A : Tuple = clip_embed_dim or embedding_dim __A : Optional[Any] = Timesteps(_A , _A , 0 ) __A : Dict = TimestepEmbedding(_A , _A , out_dim=_A , act_fn=_A ) __A : Any = nn.Linear(_A , _A ) if embedding_proj_norm_type is None: __A : Any = None elif embedding_proj_norm_type == "layer": __A : Dict = nn.LayerNorm(_A ) else: raise ValueError(F"""unsupported embedding_proj_norm_type: {embedding_proj_norm_type}""" ) __A : int = nn.Linear(_A , _A ) if encoder_hid_proj_type is None: __A : Dict = None elif encoder_hid_proj_type == "linear": __A : Tuple = nn.Linear(_A , _A ) else: raise ValueError(F"""unsupported encoder_hid_proj_type: {encoder_hid_proj_type}""" ) __A : List[str] = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , _A ) ) if added_emb_type == "prd": __A : Any = nn.Parameter(torch.zeros(1 , 1 , _A ) ) elif added_emb_type is None: __A : Any = None else: raise ValueError( F"""`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`.""" ) __A : Any = nn.ModuleList( [ BasicTransformerBlock( _A , _A , _A , dropout=_A , activation_fn='gelu' , attention_bias=_A , ) for d in range(_A ) ] ) if norm_in_type == "layer": __A : List[str] = nn.LayerNorm(_A ) elif norm_in_type is None: __A : Dict = None else: raise ValueError(F"""Unsupported norm_in_type: {norm_in_type}.""" ) __A : List[Any] = nn.LayerNorm(_A ) __A : int = nn.Linear(_A , _A ) __A : Optional[Any] = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -1_0_0_0_0.0 ) causal_attention_mask.triu_(1 ) __A : str = causal_attention_mask[None, ...] self.register_buffer('causal_attention_mask' , _A , persistent=_A ) __A : str = nn.Parameter(torch.zeros(1 , _A ) ) __A : Union[str, Any] = nn.Parameter(torch.zeros(1 , _A ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def UpperCAmelCase_ ( self ): __A : Union[str, Any] = {} def fn_recursive_add_processors(_A , _A , _A ): if hasattr(_A , 'set_processor' ): __A : int = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"""{name}.{sub_name}""" , _A , _A ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_A , _A , _A ) return processors def UpperCAmelCase_ ( self , _A ): __A : int = len(self.attn_processors.keys() ) if isinstance(_A , _A ) and len(_A ) != count: raise ValueError( F"""A dict of processors was passed, but the number of processors {len(_A )} does not match the""" F""" number of attention layers: {count}. Please make sure to pass {count} processor classes.""" ) def fn_recursive_attn_processor(_A , _A , _A ): if hasattr(_A , 'set_processor' ): if not isinstance(_A , _A ): module.set_processor(_A ) else: module.set_processor(processor.pop(F"""{name}.processor""" ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"""{name}.{sub_name}""" , _A , _A ) for name, module in self.named_children(): fn_recursive_attn_processor(_A , _A , _A ) def UpperCAmelCase_ ( self ): self.set_attn_processor(AttnProcessor() ) def UpperCAmelCase_ ( self , _A , _A , _A , _A = None , _A = None , _A = True , ): __A : int = hidden_states.shape[0] __A : Optional[int] = timestep if not torch.is_tensor(_A ): __A : Optional[Any] = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(_A ) and len(timesteps.shape ) == 0: __A : Optional[int] = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __A : List[Any] = timesteps * torch.ones(_A , dtype=timesteps.dtype , device=timesteps.device ) __A : int = self.time_proj(_A ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. __A : List[Any] = timesteps_projected.to(dtype=self.dtype ) __A : str = self.time_embedding(_A ) if self.embedding_proj_norm is not None: __A : Dict = self.embedding_proj_norm(_A ) __A : Dict = self.embedding_proj(_A ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: __A : Any = self.encoder_hidden_states_proj(_A ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError('`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set' ) __A : Optional[int] = self.proj_in(_A ) __A : Tuple = self.positional_embedding.to(hidden_states.dtype ) __A : List[Any] = [] __A : str = 0 if encoder_hidden_states is not None: additional_embeds.append(_A ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: __A : Optional[Any] = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: __A : int = hidden_states[:, None, :] __A : Dict = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: __A : str = self.prd_embedding.to(hidden_states.dtype ).expand(_A , -1 , -1 ) additional_embeds.append(_A ) __A : Union[str, Any] = torch.cat( _A , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens __A : str = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: __A : int = F.pad( _A , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) __A : int = hidden_states + positional_embeddings if attention_mask is not None: __A : List[str] = (1 - attention_mask.to(hidden_states.dtype )) * -1_0_0_0_0.0 __A : Any = F.pad(_A , (0, self.additional_embeddings) , value=0.0 ) __A : int = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) __A : Optional[Any] = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: __A : int = self.norm_in(_A ) for block in self.transformer_blocks: __A : Optional[Any] = block(_A , attention_mask=_A ) __A : int = self.norm_out(_A ) if self.prd_embedding is not None: __A : Any = hidden_states[:, -1] else: __A : Dict = hidden_states[:, additional_embeddings_len:] __A : Any = self.proj_to_clip_embeddings(_A ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=_A ) def UpperCAmelCase_ ( self , _A ): __A : str = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
77
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = ShapEPipeline UpperCamelCase : str = ['''prompt'''] UpperCamelCase : Tuple = ['''prompt'''] UpperCamelCase : Optional[int] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] UpperCamelCase : int = False @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self ): return 8 @property def UpperCAmelCase_ ( self ): __A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_A ) @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : int = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __A : Optional[Any] = PriorTransformer(**_A ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : List[str] = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __A : List[Any] = ShapERenderer(**_A ) return model def UpperCAmelCase_ ( self ): __A : List[str] = self.dummy_prior __A : Optional[int] = self.dummy_text_encoder __A : List[Any] = self.dummy_tokenizer __A : str = self.dummy_renderer __A : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=_A , clip_sample=_A , clip_sample_range=1.0 , ) __A : Any = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): if str(_A ).startswith('mps' ): __A : List[Any] = torch.manual_seed(_A ) else: __A : Dict = torch.Generator(device=_A ).manual_seed(_A ) __A : int = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def UpperCAmelCase_ ( self ): __A : Tuple = 'cpu' __A : Any = self.get_dummy_components() __A : Tuple = self.pipeline_class(**_A ) __A : List[str] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Tuple = pipe(**self.get_dummy_inputs(_A ) ) __A : int = output.images[0] __A : str = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __A : Any = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCAmelCase_ ( self ): __A : List[str] = torch_device == 'cpu' __A : Any = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_A , relax_max_difference=_A , ) def UpperCAmelCase_ ( self ): __A : Any = self.get_dummy_components() __A : Any = self.pipeline_class(**_A ) __A : Dict = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Any = 1 __A : Dict = 2 __A : Tuple = self.get_dummy_inputs(_A ) for key in inputs.keys(): if key in self.batch_params: __A : Optional[int] = batch_size * [inputs[key]] __A : Optional[int] = pipe(**_A , num_images_per_prompt=_A )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __A : Dict = ShapEPipeline.from_pretrained('openai/shap-e' ) __A : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : str = torch.Generator(device=_A ).manual_seed(0 ) __A : Tuple = pipe( 'a shark' , generator=_A , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_A , _A )
77
1
def _SCREAMING_SNAKE_CASE ( a ) -> bool: if p < 2: raise ValueError('p should not be less than 2!' ) elif p == 2: return True __A : List[Any] = 4 __A : Any = (1 << p) - 1 for _ in range(p - 2 ): __A : Any = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
77
from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if len(a ) != 2 or len(a[0] ) != 2 or len(a ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __A : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> str: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a ) -> tuple[list, list, list, list]: if len(a ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __A : str = len(a ) __A : List[Any] = matrix_length // 2 __A : List[str] = [[a[i][j] for j in range(a , a )] for i in range(a )] __A : Dict = [ [a[i][j] for j in range(a , a )] for i in range(a , a ) ] __A : int = [[a[i][j] for j in range(a )] for i in range(a )] __A : Any = [[a[i][j] for j in range(a )] for i in range(a , a )] return top_left, top_right, bot_left, bot_right def _SCREAMING_SNAKE_CASE ( a ) -> tuple[int, int]: return len(a ), len(matrix[0] ) def _SCREAMING_SNAKE_CASE ( a ) -> None: print('\n'.join(str(a ) for line in matrix ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a ) == (2, 2): return default_matrix_multiplication(a , a ) __A , __A , __A , __A : str = split_matrix(a ) __A , __A , __A , __A : List[Any] = split_matrix(a ) __A : Any = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Tuple = actual_strassen(matrix_addition(a , a ) , a ) __A : List[str] = actual_strassen(matrix_addition(a , a ) , a ) __A : Optional[int] = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Any = actual_strassen(matrix_addition(a , a ) , matrix_addition(a , a ) ) __A : Any = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = matrix_addition(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) __A : Union[str, Any] = matrix_addition(a , a ) __A : str = matrix_addition(a , a ) __A : Dict = matrix_subtraction(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) # construct the new matrix from our 4 quadrants __A : List[Any] = [] for i in range(len(a ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(a ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a )[1] != matrix_dimensions(a )[0]: __A : Dict = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"""Matrix A: {matrixa}\n""" F"""Matrix B: {matrixa}""" ) raise Exception(a ) __A : int = matrix_dimensions(a ) __A : Any = matrix_dimensions(a ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __A : List[Any] = max(*a , *a ) __A : Optional[Any] = int(math.pow(2 , math.ceil(math.loga(a ) ) ) ) __A : Union[str, Any] = matrixa __A : Optional[int] = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __A : str = actual_strassen(a , a ) # Removing the additional zeros for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] UpperCAmelCase : Optional[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
77
1
def _SCREAMING_SNAKE_CASE ( a ) -> list: __A : Union[str, Any] = len(a ) for _ in range(a ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: __A , __A : Tuple = arr[i + 1], arr[i] return arr if __name__ == "__main__": UpperCAmelCase : Optional[Any] = list(range(10, 0, -1)) print(F"""Original: {arr}. Sorted: {odd_even_transposition(arr)}""")
77
def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : List[str] = [] __A : Tuple = [] __A : Union[str, Any] = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, } # Priority of each operator __A : List[str] = len(a ) if (len(a ) > 7) else 7 # Print table header for output print( 'Symbol'.center(8 ) , 'Stack'.center(a ) , 'Postfix'.center(a ) , sep=' | ' , ) print('-' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(a ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(a ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(a ) == 0: stack.append(a ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(a ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(a ) # push x to stack print( x.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format while len(a ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ' '.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format return "".join(a ) # return Postfix as str def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : List[Any] = list(infix[::-1] ) # reverse the infix equation for i in range(len(a ) ): if infix[i] == "(": __A : List[str] = ')' # change "(" to ")" elif infix[i] == ")": __A : Any = '(' # change ")" to "(" return (infix_2_postfix(''.join(a ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": UpperCAmelCase : List[str] = input('''\nEnter an Infix Equation = ''') # Input an Infix equation UpperCAmelCase : Union[str, Any] = ''''''.join(Infix.split()) # Remove spaces from the input print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
77
1
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. UpperCAmelCase : str = 2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. UpperCAmelCase : Optional[Any] = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. UpperCAmelCase : Dict = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[str, float]: __A : Optional[int] = len([g for position, g in enumerate(a ) if g == main_target[position]] ) return (item, float(a )) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[str, str]: __A : List[Any] = random.randint(0 , len(a ) - 1 ) __A : int = parent_a[:random_slice] + parent_a[random_slice:] __A : Union[str, Any] = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def _SCREAMING_SNAKE_CASE ( a , a ) -> str: __A : Optional[int] = list(a ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: __A : str = random.choice(a ) return "".join(a ) def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> list[str]: __A : int = [] # Generate more children proportionally to the fitness score. __A : str = int(parent_a[1] * 1_00 ) + 1 __A : List[Any] = 10 if child_n >= 10 else child_n for _ in range(a ): __A : Any = population_score[random.randint(0 , a )][0] __A , __A : Optional[int] = crossover(parent_a[0] , a ) # Append new string to the population list. pop.append(mutate(a , a ) ) pop.append(mutate(a , a ) ) return pop def _SCREAMING_SNAKE_CASE ( a , a , a = True ) -> tuple[int, int, str]: # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: __A : int = F"""{N_POPULATION} must be bigger than {N_SELECTED}""" raise ValueError(a ) # Verify that the target contains no genes besides the ones inside genes variable. __A : Optional[int] = sorted({c for c in target if c not in genes} ) if not_in_genes_list: __A : List[Any] = F"""{not_in_genes_list} is not in genes list, evolution cannot converge""" raise ValueError(a ) # Generate random starting population. __A : Any = [] for _ in range(a ): population.append(''.join([random.choice(a ) for i in range(len(a ) )] ) ) # Just some logs to know what the algorithms is doing. __A , __A : Optional[int] = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(a ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. __A : Union[str, Any] = [evaluate(a , a ) for item in population] # Check if there is a matching evolution. __A : Any = sorted(a , key=lambda a : x[1] , reverse=a ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F"""\nGeneration: {generation}""" F"""\nTotal Population:{total_population}""" F"""\nBest score: {population_score[0][1]}""" F"""\nBest string: {population_score[0][0]}""" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. __A : List[Any] = population[: int(N_POPULATION / 3 )] population.clear() population.extend(a ) # Normalize population score to be between 0 and 1. __A : Union[str, Any] = [ (item, score / len(a )) for item, score in population_score ] # This is selection for i in range(a ): population.extend(select(population_score[int(a )] , a , a ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(a ) > N_POPULATION: break if __name__ == "__main__": UpperCAmelCase : Tuple = ( '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!''' ) UpperCAmelCase : Union[str, Any] = list( ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm''' '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\''' ) UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Union[str, Any] = basic(target_str, genes_list) print( F"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}""" )
77
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : Tuple = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json''' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase : int = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = '''mask2former''' UpperCamelCase : Any = ['''swin'''] UpperCamelCase : Union[str, Any] = {'''hidden_size''': '''hidden_dim'''} def __init__( self , _A = None , _A = 256 , _A = 256 , _A = 256 , _A = 1024 , _A = "relu" , _A = 6 , _A = 10 , _A = 8 , _A = 0.0 , _A = 2048 , _A = False , _A = False , _A = 4 , _A = 255 , _A = 100 , _A = 0.1 , _A = 2.0 , _A = 5.0 , _A = 5.0 , _A = 12544 , _A = 3.0 , _A = 0.7_5 , _A = 0.0_2 , _A = 1.0 , _A = True , _A = [4, 8, 16, 32] , _A = None , **_A , ): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) __A : Optional[int] = CONFIG_MAPPING['swin']( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=_A , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(_A , _A ): __A : Dict = backbone_config.pop('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[str] = config_class.from_dict(_A ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) __A : Optional[int] = backbone_config __A : Optional[Any] = feature_size __A : Any = mask_feature_size __A : Optional[Any] = hidden_dim __A : Union[str, Any] = encoder_feedforward_dim __A : Optional[Any] = activation_function __A : List[Any] = encoder_layers __A : Union[str, Any] = decoder_layers __A : Dict = num_attention_heads __A : Tuple = dropout __A : Dict = dim_feedforward __A : Tuple = pre_norm __A : Dict = enforce_input_projection __A : Optional[int] = common_stride __A : Optional[Any] = ignore_value __A : str = num_queries __A : List[Any] = no_object_weight __A : List[str] = class_weight __A : List[Any] = mask_weight __A : List[Any] = dice_weight __A : Tuple = train_num_points __A : Optional[Any] = oversample_ratio __A : Union[str, Any] = importance_sample_ratio __A : Union[str, Any] = init_std __A : int = init_xavier_std __A : Union[str, Any] = use_auxiliary_loss __A : Union[str, Any] = feature_strides __A : List[Any] = output_auxiliary_logits __A : Optional[Any] = decoder_layers super().__init__(**_A ) @classmethod def UpperCAmelCase_ ( cls , _A , **_A ): return cls( backbone_config=_A , **_A , ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = copy.deepcopy(self.__dict__ ) __A : List[Any] = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output
77
1
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance UpperCAmelCase : Any = 6378137.0 UpperCAmelCase : str = 6356752.314245 UpperCAmelCase : Tuple = 6_37_81_37 def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> float: __A : int = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude __A : List[Any] = atan((1 - flattening) * tan(radians(a ) ) ) __A : Tuple = atan((1 - flattening) * tan(radians(a ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius __A : Optional[Any] = haversine_distance(a , a , a , a ) / EQUATORIAL_RADIUS # Intermediate P and Q values __A : Optional[Any] = (b_lata + b_lata) / 2 __A : Any = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) __A : Dict = (sin(a ) ** 2) * (cos(a ) ** 2) __A : str = cos(sigma / 2 ) ** 2 __A : Union[str, Any] = (sigma - sin(a )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) __A : List[Any] = (cos(a ) ** 2) * (sin(a ) ** 2) __A : str = sin(sigma / 2 ) ** 2 __A : Dict = (sigma + sin(a )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
77
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : str = '''conditional_detr''' UpperCamelCase : int = ['''past_key_values'''] UpperCamelCase : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , _A=True , _A=None , _A=3 , _A=300 , _A=6 , _A=2048 , _A=8 , _A=6 , _A=2048 , _A=8 , _A=0.0 , _A=0.0 , _A=True , _A="relu" , _A=256 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1.0 , _A=False , _A="sine" , _A="resnet50" , _A=True , _A=False , _A=2 , _A=5 , _A=2 , _A=1 , _A=1 , _A=2 , _A=5 , _A=2 , _A=0.2_5 , **_A , ): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __A : List[str] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_A , _A ): __A : Tuple = backbone_config.get('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[Any] = config_class.from_dict(_A ) __A : Tuple = use_timm_backbone __A : List[str] = backbone_config __A : Dict = num_channels __A : int = num_queries __A : int = d_model __A : str = encoder_ffn_dim __A : List[str] = encoder_layers __A : Optional[Any] = encoder_attention_heads __A : Union[str, Any] = decoder_ffn_dim __A : List[Any] = decoder_layers __A : Optional[Any] = decoder_attention_heads __A : Any = dropout __A : Any = attention_dropout __A : int = activation_dropout __A : Optional[int] = activation_function __A : Union[str, Any] = init_std __A : Union[str, Any] = init_xavier_std __A : Optional[Any] = encoder_layerdrop __A : int = decoder_layerdrop __A : List[str] = encoder_layers __A : str = auxiliary_loss __A : Union[str, Any] = position_embedding_type __A : Optional[int] = backbone __A : List[str] = use_pretrained_backbone __A : List[Any] = dilation # Hungarian matcher __A : List[str] = class_cost __A : Optional[int] = bbox_cost __A : Dict = giou_cost # Loss coefficients __A : Optional[int] = mask_loss_coefficient __A : Union[str, Any] = dice_loss_coefficient __A : List[Any] = cls_loss_coefficient __A : Dict = bbox_loss_coefficient __A : Tuple = giou_loss_coefficient __A : Tuple = focal_alpha super().__init__(is_encoder_decoder=_A , **_A ) @property def UpperCAmelCase_ ( self ): return self.encoder_attention_heads @property def UpperCAmelCase_ ( self ): return self.d_model def UpperCAmelCase_ ( self ): __A : str = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __A : Dict = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = version.parse('''1.11''' ) @property def UpperCAmelCase_ ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def UpperCAmelCase_ ( self ): return 1e-5 @property def UpperCAmelCase_ ( self ): return 12
77
1
from __future__ import annotations UpperCAmelCase : int = list[list[int]] # assigning initial values to the grid UpperCAmelCase : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def _SCREAMING_SNAKE_CASE ( a ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def _SCREAMING_SNAKE_CASE ( a ) -> Matrix | None: if location := find_empty_location(a ): __A , __A : str = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): __A : Dict = digit if sudoku(a ) is not None: return grid __A : List[Any] = 0 return None def _SCREAMING_SNAKE_CASE ( a ) -> None: for row in grid: for cell in row: print(a , end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 20) print_solution(example_grid) print('''\nExample grid solution:''') UpperCAmelCase : Tuple = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
77
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _A( nn.Module ): """simple docstring""" def __init__( self ): super().__init__() __A : List[str] = nn.Linear(3 , 4 ) __A : Optional[Any] = nn.BatchNormad(4 ) __A : List[Any] = nn.Linear(4 , 5 ) def UpperCAmelCase_ ( self , _A ): return self.lineara(self.batchnorm(self.lineara(_A ) ) ) class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Dict = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , model.state_dict() ) __A : str = os.path.join(_A , 'index.json' ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: __A : Optional[int] = os.path.join(_A , F"""{key}.dat""" ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on the fact weights are properly loaded def UpperCAmelCase_ ( self ): __A : Dict = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: __A : Tuple = torch.randn(2 , 3 , dtype=_A ) with TemporaryDirectory() as tmp_dir: __A : int = offload_weight(_A , 'weight' , _A , {} ) __A : Union[str, Any] = os.path.join(_A , 'weight.dat' ) self.assertTrue(os.path.isfile(_A ) ) self.assertDictEqual(_A , {'weight': {'shape': [2, 3], 'dtype': str(_A ).split('.' )[1]}} ) __A : List[str] = load_offloaded_weight(_A , index['weight'] ) self.assertTrue(torch.equal(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : int = ModelForTest() __A : Union[str, Any] = model.state_dict() __A : Optional[Any] = {k: v for k, v in state_dict.items() if 'linear2' not in k} __A : str = {k: v for k, v in state_dict.items() if 'linear2' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : List[str] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) __A : Union[str, Any] = {k: v for k, v in state_dict.items() if 'weight' in k} __A : List[Any] = {k: v for k, v in state_dict.items() if 'weight' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : Optional[int] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) # Duplicates are removed __A : str = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) def UpperCAmelCase_ ( self ): __A : Dict = {'a.1': 0, 'a.10': 1, 'a.2': 2} __A : str = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1': 0, 'a.2': 2} ) __A : Optional[Any] = {'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2} __A : Any = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1.a': 0, 'a.2.a': 2} )
77
1
import numpy as np from PIL import Image def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : Union[str, Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : List[Any] = 0 __A : Optional[Any] = 0 __A : List[Any] = 0 __A : Dict = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __A : Tuple = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : List[str] = 0 __A : Union[str, Any] = 0 return updated_arr def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : List[Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : Dict = 0 __A : str = 0 __A : Tuple = 0 __A : Optional[int] = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __A : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : Dict = 0 __A : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image UpperCAmelCase : int = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
77
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): __A : Any = data def __iter__( self ): for element in self.data: yield element def _SCREAMING_SNAKE_CASE ( a=True ) -> Any: __A : List[Any] = Accelerator(even_batches=a ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str: if iterable: __A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) ) else: __A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) ) __A : Optional[Any] = DataLoader(a , batch_size=a ) __A : Optional[int] = accelerator.prepare(a ) return dl def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]: __A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a ) __A : Tuple = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : int = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : str = create_accelerator(even_batches=a ) verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _SCREAMING_SNAKE_CASE ( ) -> str: __A : Optional[Any] = create_accelerator(even_batches=a ) __A : str = torch.nn.Linear(1 , 1 ) __A : Optional[int] = accelerator.prepare(a ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : str = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(a ): __A : Dict = ddp_model(batch[0].float() ) __A : List[str] = output.sum() loss.backward() batch_idxs.append(a ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , a ) assert "only supported for multi-GPU" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : int = True __A : Union[str, Any] = False __A : Optional[int] = create_accelerator(even_batches=a ) __A : int = torch.nn.Linear(1 , 1 ) __A : List[Any] = accelerator.prepare(a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : List[str] = train_dl.batch_sampler.even_batches __A : Dict = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Any = True __A : List[Any] = False __A : Tuple = create_accelerator(even_batches=a ) __A : List[str] = torch.nn.Linear(1 , 1 ) __A : Optional[Any] = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('ignore' ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : Tuple = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Any = create_accelerator() __A : Union[str, Any] = torch.nn.Linear(1 , 1 ) __A : str = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): pass assert issubclass(w[-1].category , a ) assert "only supported for map-style datasets" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : str = create_accelerator() accelerator.print('Test that even_batches variable ensures uniform batches across processes' ) test_default_ensures_even_batch_sizes() accelerator.print('Run tests with even_batches disabled' ) test_can_disable_even_batches() accelerator.print('Test joining uneven inputs' ) test_can_join_uneven_inputs() accelerator.print('Test overriding even_batches when joining uneven inputs' ) test_join_can_override_even_batches() accelerator.print('Test overriding even_batches for mixed dataloader types' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('Test join with non DDP distributed raises warning' ) __A : int = accelerator.state.distributed_type __A : Tuple = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(a ) __A : str = original_state if __name__ == "__main__": main()
77
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class _A( snake_case__ ): """simple docstring""" UpperCamelCase : int = '''Salesforce/blip-image-captioning-base''' UpperCamelCase : str = ( '''This is a tool that generates a description of an image. It takes an input named `image` which should be the ''' '''image to caption, and returns a text that contains the description in English.''' ) UpperCamelCase : int = '''image_captioner''' UpperCamelCase : Union[str, Any] = AutoModelForVisionaSeq UpperCamelCase : Dict = ['''image'''] UpperCamelCase : Union[str, Any] = ['''text'''] def __init__( self , *_A , **_A ): requires_backends(self , ['vision'] ) super().__init__(*_A , **_A ) def UpperCAmelCase_ ( self , _A ): return self.pre_processor(images=_A , return_tensors='pt' ) def UpperCAmelCase_ ( self , _A ): return self.model.generate(**_A ) def UpperCAmelCase_ ( self , _A ): return self.pre_processor.batch_decode(_A , skip_special_tokens=_A )[0].strip()
77
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : str = { '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''', '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''', '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''', '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''', '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''', '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''', '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''', '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''', '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''', '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''', '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''', '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = '''codegen''' UpperCamelCase : List[str] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ): __A : Any = vocab_size __A : Tuple = n_ctx __A : Union[str, Any] = n_positions __A : Optional[Any] = n_embd __A : Any = n_layer __A : Dict = n_head __A : Union[str, Any] = n_inner __A : List[Any] = rotary_dim __A : str = activation_function __A : Any = resid_pdrop __A : Tuple = embd_pdrop __A : Tuple = attn_pdrop __A : Union[str, Any] = layer_norm_epsilon __A : str = initializer_range __A : Optional[Any] = use_cache __A : Union[str, Any] = bos_token_id __A : Tuple = eos_token_id super().__init__( bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A ) class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A = "default" , _A = None , _A = False , ): super().__init__(_A , task=_A , patching_specs=_A , use_past=_A ) if not getattr(self._config , 'pad_token_id' , _A ): # TODO: how to do that better? __A : Dict = 0 @property def UpperCAmelCase_ ( self ): __A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) __A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'} else: __A : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase_ ( self ): return self._config.n_layer @property def UpperCAmelCase_ ( self ): return self._config.n_head def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Any = super(_A , self ).generate_dummy_inputs( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) # We need to order the input in the way they appears in the forward() __A : str = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __A , __A : Any = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Any = seqlen + 2 __A : List[str] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __A : Optional[Any] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] __A : Tuple = common_inputs['attention_mask'] if self.use_past: __A : str = ordered_inputs['attention_mask'].dtype __A : List[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self ): return 13
77
1
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _A( nn.Module ): """simple docstring""" def __init__( self ): super().__init__() __A : List[str] = nn.Linear(3 , 4 ) __A : Optional[Any] = nn.BatchNormad(4 ) __A : List[Any] = nn.Linear(4 , 5 ) def UpperCAmelCase_ ( self , _A ): return self.lineara(self.batchnorm(self.lineara(_A ) ) ) class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Dict = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , model.state_dict() ) __A : str = os.path.join(_A , 'index.json' ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: __A : Optional[int] = os.path.join(_A , F"""{key}.dat""" ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on the fact weights are properly loaded def UpperCAmelCase_ ( self ): __A : Dict = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: __A : Tuple = torch.randn(2 , 3 , dtype=_A ) with TemporaryDirectory() as tmp_dir: __A : int = offload_weight(_A , 'weight' , _A , {} ) __A : Union[str, Any] = os.path.join(_A , 'weight.dat' ) self.assertTrue(os.path.isfile(_A ) ) self.assertDictEqual(_A , {'weight': {'shape': [2, 3], 'dtype': str(_A ).split('.' )[1]}} ) __A : List[str] = load_offloaded_weight(_A , index['weight'] ) self.assertTrue(torch.equal(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : int = ModelForTest() __A : Union[str, Any] = model.state_dict() __A : Optional[Any] = {k: v for k, v in state_dict.items() if 'linear2' not in k} __A : str = {k: v for k, v in state_dict.items() if 'linear2' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : List[str] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) __A : Union[str, Any] = {k: v for k, v in state_dict.items() if 'weight' in k} __A : List[Any] = {k: v for k, v in state_dict.items() if 'weight' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : Optional[int] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) # Duplicates are removed __A : str = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) def UpperCAmelCase_ ( self ): __A : Dict = {'a.1': 0, 'a.10': 1, 'a.2': 2} __A : str = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1': 0, 'a.2': 2} ) __A : Optional[Any] = {'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2} __A : Any = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1.a': 0, 'a.2.a': 2} )
77
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase : List[Any] = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _A , ) super().__init__(*_A , **_A )
77
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase : List[Any] = { '''tanreinama/GPTSAN-2.8B-spout_is_uniform''': ( '''https://huggingface.co/tanreinama/GPTSAN-2.8B-spout_is_uniform/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = '''gptsan-japanese''' UpperCamelCase : Optional[int] = [ '''past_key_values''', ] UpperCamelCase : Dict = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , _A=36000 , _A=1280 , _A=1024 , _A=8192 , _A=4096 , _A=128 , _A=10 , _A=0 , _A=16 , _A=16 , _A=128 , _A=0.0 , _A=1e-5 , _A=False , _A=0.0 , _A="float32" , _A=False , _A=False , _A=False , _A=0.0_0_2 , _A=False , _A=True , _A=35998 , _A=35995 , _A=35999 , **_A , ): __A : int = vocab_size __A : Dict = max_position_embeddings __A : Dict = d_model __A : Optional[int] = d_ff __A : List[str] = d_ext __A : Dict = d_spout __A : Any = num_switch_layers __A : List[str] = num_ext_layers __A : int = num_switch_layers + num_ext_layers __A : Any = num_heads __A : Optional[Any] = num_experts __A : Optional[Any] = expert_capacity __A : str = dropout_rate __A : Tuple = layer_norm_epsilon __A : Tuple = router_bias __A : List[str] = router_jitter_noise __A : List[str] = router_dtype __A : Tuple = router_ignore_padding_tokens __A : int = output_hidden_states __A : Any = output_attentions __A : int = initializer_factor __A : str = output_router_logits __A : Optional[Any] = use_cache super().__init__( separator_token_id=_A , pad_token_id=_A , eos_token_id=_A , **_A , )
77
import glob import os import random from string import ascii_lowercase, digits import cva UpperCAmelCase : Dict = '''''' UpperCAmelCase : Union[str, Any] = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal) def _SCREAMING_SNAKE_CASE ( ) -> None: __A , __A : List[Any] = get_dataset(a , a ) print('Processing...' ) __A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a ) for index, image in enumerate(a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __A : Optional[int] = random_chars(32 ) __A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] __A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Success {index+1}/{len(a )} with {file_name}""" ) __A : int = [] for anno in new_annos[index]: __A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(a ) with open(F"""/{file_root}.txt""" , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]: __A : int = [] __A : List[Any] = [] for label_file in glob.glob(os.path.join(a , '*.txt' ) ): __A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(a ) as in_file: __A : Tuple = in_file.readlines() __A : Dict = os.path.join(a , F"""{label_name}.jpg""" ) __A : Dict = [] for obj_list in obj_lists: __A : int = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(a ) labels.append(a ) return img_paths, labels def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]: __A : int = [] __A : Optional[Any] = [] __A : Dict = [] for idx in range(len(a ) ): __A : Dict = [] __A : Optional[Any] = img_list[idx] path_list.append(a ) __A : Union[str, Any] = anno_list[idx] __A : Optional[Any] = cva.imread(a ) if flip_type == 1: __A : Any = cva.flip(a , a ) for bbox in img_annos: __A : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __A : Union[str, Any] = cva.flip(a , a ) for bbox in img_annos: __A : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(a ) new_imgs_list.append(a ) return new_imgs_list, new_annos_lists, path_list def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __A : List[Any] = ascii_lowercase + digits return "".join(random.choice(a ) for _ in range(a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
77
1
from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('''To use the rich extension, install rich with `pip install rich`''')
77
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A: """simple docstring""" def __init__( self , _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.0_2 , _A=3 , _A=4 , _A=None , ): __A : Union[str, Any] = parent __A : List[str] = batch_size __A : Optional[int] = seq_length __A : List[Any] = is_training __A : Optional[Any] = use_input_mask __A : List[Any] = use_token_type_ids __A : Optional[Any] = use_labels __A : List[str] = vocab_size __A : Optional[int] = hidden_size __A : List[Any] = num_hidden_layers __A : int = num_attention_heads __A : Dict = intermediate_size __A : Any = hidden_act __A : Union[str, Any] = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : Optional[int] = max_position_embeddings __A : Dict = type_vocab_size __A : Any = type_sequence_label_size __A : Dict = initializer_range __A : str = num_labels __A : Union[str, Any] = num_choices __A : str = scope def UpperCAmelCase_ ( self ): __A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : Optional[Any] = None if self.use_input_mask: __A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __A : Dict = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = None __A : List[Any] = None __A : List[Any] = None if self.use_labels: __A : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __A : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[str] = LlamaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A , attention_mask=_A ) __A : Any = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Dict = True __A : int = LlamaModel(_A ) model.to(_A ) model.eval() __A : str = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __A : int = model( _A , attention_mask=_A , encoder_hidden_states=_A , ) __A : List[Any] = model(_A , attention_mask=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Optional[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : int = True __A : List[Any] = True __A : List[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() # first forward pass __A : Optional[Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , ) __A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __A : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) __A : str = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __A : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : str = torch.cat([input_mask, next_mask] , dim=-1 ) __A : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['hidden_states'][0] __A : Union[str, Any] = 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 __A : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() __A : Tuple = 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 UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Tuple = config_and_inputs __A : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () UpperCamelCase : Optional[Any] = (LlamaForCausalLM,) if is_torch_available() else () UpperCamelCase : Optional[Any] = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False def UpperCAmelCase_ ( self ): __A : List[Any] = LlamaModelTester(self ) __A : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : int = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() __A : str = 3 __A : Optional[int] = input_dict['input_ids'] __A : int = input_ids.ne(1 ).to(_A ) __A : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Union[str, Any] = 3 __A : Tuple = 'single_label_classification' __A : Union[str, Any] = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[int] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Any = 3 __A : int = 'multi_label_classification' __A : int = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __A : List[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def UpperCAmelCase_ ( self ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def UpperCAmelCase_ ( self , _A ): __A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Dict = ids_tensor([1, 10] , config.vocab_size ) __A : Union[str, Any] = 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 __A : List[Any] = LlamaModel(_A ) original_model.to(_A ) original_model.eval() __A : Dict = original_model(_A ).last_hidden_state __A : int = original_model(_A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : int = {'type': scaling_type, 'factor': 1_0.0} __A : str = LlamaModel(_A ) scaled_model.to(_A ) scaled_model.eval() __A : Dict = scaled_model(_A ).last_hidden_state __A : str = 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 ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) __A : Union[str, Any] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __A : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[str] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) __A : int = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) __A : Optional[int] = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : Optional[Any] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) __A : List[Any] = model(torch.tensor(_A ) ) __A : Tuple = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # fmt: off __A : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' __A : List[str] = 'Simply put, the theory of relativity states that ' __A : Union[str, Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) __A : List[str] = tokenizer.encode(_A , return_tensors='pt' ) __A : Tuple = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=_A ) # greedy generation outputs __A : Union[str, Any] = model.generate(_A , max_new_tokens=64 , top_p=_A , temperature=1 , do_sample=_A ) __A : List[str] = tokenizer.decode(generated_ids[0] , skip_special_tokens=_A ) self.assertEqual(_A , _A )
77
1
import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _A( snake_case__ ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : List[str] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_A , 'width_multiplier' ) ) class _A: """simple docstring""" def __init__( self , _A , _A=13 , _A=64 , _A=2 , _A=3 , _A="swish" , _A=3 , _A=32 , _A=0.1 , _A=0.0_2 , _A=True , _A=True , _A=10 , _A=None , _A=0.2_5 , _A=0.0 , _A=0.0 , ): __A : Optional[Any] = parent __A : Dict = batch_size __A : Union[str, Any] = image_size __A : Dict = patch_size __A : Tuple = num_channels __A : List[Any] = make_divisible(512 * width_multiplier , divisor=8 ) __A : List[str] = hidden_act __A : Union[str, Any] = conv_kernel_size __A : Union[str, Any] = output_stride __A : Union[str, Any] = classifier_dropout_prob __A : str = use_labels __A : Optional[int] = is_training __A : Any = num_labels __A : Any = initializer_range __A : Tuple = scope __A : Optional[Any] = width_multiplier __A : str = ffn_dropout __A : Dict = attn_dropout def UpperCAmelCase_ ( self ): __A : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A : Union[str, Any] = None __A : List[str] = None if self.use_labels: __A : List[str] = ids_tensor([self.batch_size] , self.num_labels ) __A : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __A : Any = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCAmelCase_ ( self ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A ): __A : Union[str, Any] = MobileViTVaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A ): __A : List[Any] = self.num_labels __A : Union[str, Any] = MobileViTVaForImageClassification(_A ) model.to(_A ) model.eval() __A : List[str] = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A ): __A : Dict = self.num_labels __A : Dict = MobileViTVaForSemanticSegmentation(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __A : Optional[int] = model(_A , labels=_A ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.prepare_config_and_inputs() __A , __A , __A , __A : Optional[int] = config_and_inputs __A : List[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : int = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) UpperCamelCase : int = ( { '''feature-extraction''': MobileViTVaModel, '''image-classification''': MobileViTVaForImageClassification, '''image-segmentation''': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False UpperCamelCase : Tuple = False UpperCamelCase : str = False def UpperCAmelCase_ ( self ): __A : Optional[int] = MobileViTVaModelTester(self ) __A : int = MobileViTVaConfigTester(self , config_class=_A , has_text_modality=_A ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='MobileViTV2 does not use inputs_embeds' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='MobileViTV2 does not support input and output embeddings' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='MobileViTV2 does not output attentions' ) def UpperCAmelCase_ ( self ): pass @require_torch_multi_gpu @unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.' ) def UpperCAmelCase_ ( self ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : Optional[int] = model_class(_A ) __A : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A : Tuple = [*signature.parameters.keys()] __A : Tuple = ['pixel_values'] self.assertListEqual(arg_names[:1] , _A ) def UpperCAmelCase_ ( self ): __A : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): def check_hidden_states_output(_A , _A , _A ): __A : Optional[int] = model_class(_A ) model.to(_A ) model.eval() with torch.no_grad(): __A : Dict = model(**self._prepare_for_class(_A , _A ) ) __A : Optional[int] = outputs.hidden_states __A : Any = 5 self.assertEqual(len(_A ) , _A ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __A : Optional[Any] = 2 for i in range(len(_A ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __A , __A : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : List[str] = True check_hidden_states_output(_A , _A , _A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A : Optional[Any] = True check_hidden_states_output(_A , _A , _A ) def UpperCAmelCase_ ( self ): __A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_A ) @slow def UpperCAmelCase_ ( self ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A : List[str] = MobileViTVaModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def _SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: __A : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class _A( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase_ ( self ): return ( MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256' ) if is_vision_available() else None ) @slow def UpperCAmelCase_ ( self ): __A : Dict = MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256' ).to( _A ) __A : Tuple = self.default_image_processor __A : Union[str, Any] = prepare_img() __A : int = image_processor(images=_A , return_tensors='pt' ).to(_A ) # forward pass with torch.no_grad(): __A : str = model(**_A ) # verify the logits __A : Dict = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _A ) __A : Dict = torch.tensor([-1.6_3_3_6e0_0, -7.3_2_0_4e-0_2, -5.1_8_8_3e-0_1] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): __A : List[str] = MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) __A : Union[str, Any] = model.to(_A ) __A : int = MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) __A : Union[str, Any] = prepare_img() __A : Dict = image_processor(images=_A , return_tensors='pt' ).to(_A ) # forward pass with torch.no_grad(): __A : int = model(**_A ) __A : Optional[int] = outputs.logits # verify the logits __A : List[str] = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _A ) __A : Dict = torch.tensor( [ [[7.0_8_6_3, 7.1_5_2_5, 6.8_2_0_1], [6.6_9_3_1, 6.8_7_7_0, 6.8_9_3_3], [6.2_9_7_8, 7.0_3_6_6, 6.9_6_3_6]], [[-3.7_1_3_4, -3.6_7_1_2, -3.6_6_7_5], [-3.5_8_2_5, -3.3_5_4_9, -3.4_7_7_7], [-3.3_4_3_5, -3.3_9_7_9, -3.2_8_5_7]], [[-2.9_3_2_9, -2.8_0_0_3, -2.7_3_6_9], [-3.0_5_6_4, -2.4_7_8_0, -2.0_2_0_7], [-2.6_8_8_9, -1.9_2_9_8, -1.7_6_4_0]], ] , device=_A , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _A , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) __A : str = model.to(_A ) __A : Union[str, Any] = MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) __A : Union[str, Any] = prepare_img() __A : List[Any] = image_processor(images=_A , return_tensors='pt' ).to(_A ) # forward pass with torch.no_grad(): __A : str = model(**_A ) __A : Dict = outputs.logits.detach().cpu() __A : Optional[int] = image_processor.post_process_semantic_segmentation(outputs=_A , target_sizes=[(50, 60)] ) __A : Dict = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _A ) __A : List[str] = image_processor.post_process_semantic_segmentation(outputs=_A ) __A : str = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _A )
77
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
1
def _SCREAMING_SNAKE_CASE ( a ) -> float: __A : str = 0 while len(a ) > 1: __A : Optional[Any] = 0 # Consider two files with minimum cost to be merged for _ in range(2 ): __A : List[str] = files.index(min(a ) ) temp += files[min_index] files.pop(a ) files.append(a ) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
77
import numpy as np from PIL import Image def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : Union[str, Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : List[Any] = 0 __A : Optional[Any] = 0 __A : List[Any] = 0 __A : Dict = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __A : Tuple = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : List[str] = 0 __A : Union[str, Any] = 0 return updated_arr def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : List[Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : Dict = 0 __A : str = 0 __A : Tuple = 0 __A : Optional[int] = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __A : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : Dict = 0 __A : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image UpperCAmelCase : int = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
77
1
def _SCREAMING_SNAKE_CASE ( a , a ) -> str: __A : list[list[str]] = [[] for _ in range(a )] __A : Optional[Any] = key - 1 if key <= 0: raise ValueError('Height of grid can\'t be 0 or negative' ) if key == 1 or len(a ) <= key: return input_string for position, character in enumerate(a ): __A : Any = position % (lowest * 2) # puts it in bounds __A : Any = min(a , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(a ) __A : Any = [''.join(a ) for row in temp_grid] __A : List[Any] = ''.join(a ) return output_string def _SCREAMING_SNAKE_CASE ( a , a ) -> str: __A : Dict = [] __A : Union[str, Any] = key - 1 if key <= 0: raise ValueError('Height of grid can\'t be 0 or negative' ) if key == 1: return input_string __A : list[list[str]] = [[] for _ in range(a )] # generates template for position in range(len(a ) ): __A : Optional[int] = position % (lowest * 2) # puts it in bounds __A : Any = min(a , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append('*' ) __A : List[Any] = 0 for row in temp_grid: # fills in the characters __A : str = input_string[counter : counter + len(a )] grid.append(list(a ) ) counter += len(a ) __A : str = '' # reads as zigzag for position in range(len(a ) ): __A : Dict = position % (lowest * 2) # puts it in bounds __A : Any = min(a , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def _SCREAMING_SNAKE_CASE ( a ) -> dict[int, str]: __A : int = {} for key_guess in range(1 , len(a ) ): # tries every key __A : str = decrypt(a , a ) return results if __name__ == "__main__": import doctest doctest.testmod()
77
from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float: __A : Any = x_start __A : List[str] = fnc(a ) __A : Optional[Any] = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area __A : Any = (x_end - x_start) / steps + xa __A : List[str] = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __A : Any = xa __A : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( a ) -> int: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') UpperCAmelCase : Tuple = 10 while i <= 10_00_00: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
77
1
from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if len(a ) != 2 or len(a[0] ) != 2 or len(a ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __A : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> str: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a ) -> tuple[list, list, list, list]: if len(a ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __A : str = len(a ) __A : List[Any] = matrix_length // 2 __A : List[str] = [[a[i][j] for j in range(a , a )] for i in range(a )] __A : Dict = [ [a[i][j] for j in range(a , a )] for i in range(a , a ) ] __A : int = [[a[i][j] for j in range(a )] for i in range(a )] __A : Any = [[a[i][j] for j in range(a )] for i in range(a , a )] return top_left, top_right, bot_left, bot_right def _SCREAMING_SNAKE_CASE ( a ) -> tuple[int, int]: return len(a ), len(matrix[0] ) def _SCREAMING_SNAKE_CASE ( a ) -> None: print('\n'.join(str(a ) for line in matrix ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a ) == (2, 2): return default_matrix_multiplication(a , a ) __A , __A , __A , __A : str = split_matrix(a ) __A , __A , __A , __A : List[Any] = split_matrix(a ) __A : Any = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Tuple = actual_strassen(matrix_addition(a , a ) , a ) __A : List[str] = actual_strassen(matrix_addition(a , a ) , a ) __A : Optional[int] = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Any = actual_strassen(matrix_addition(a , a ) , matrix_addition(a , a ) ) __A : Any = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = matrix_addition(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) __A : Union[str, Any] = matrix_addition(a , a ) __A : str = matrix_addition(a , a ) __A : Dict = matrix_subtraction(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) # construct the new matrix from our 4 quadrants __A : List[Any] = [] for i in range(len(a ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(a ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a )[1] != matrix_dimensions(a )[0]: __A : Dict = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"""Matrix A: {matrixa}\n""" F"""Matrix B: {matrixa}""" ) raise Exception(a ) __A : int = matrix_dimensions(a ) __A : Any = matrix_dimensions(a ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __A : List[Any] = max(*a , *a ) __A : Optional[Any] = int(math.pow(2 , math.ceil(math.loga(a ) ) ) ) __A : Union[str, Any] = matrixa __A : Optional[int] = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __A : str = actual_strassen(a , a ) # Removing the additional zeros for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] UpperCAmelCase : Optional[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
77
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def _SCREAMING_SNAKE_CASE ( ) -> None: print('Making key files...' ) make_key_files('rsa' , 10_24 ) print('Key files generation successful.' ) def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]: print('Generating prime p...' ) __A : Optional[Any] = rabinMiller.generate_large_prime(a ) print('Generating prime q...' ) __A : Union[str, Any] = rabinMiller.generate_large_prime(a ) __A : Tuple = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...' ) while True: __A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1: break print('Calculating d that is mod inverse of e...' ) __A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) ) __A : Dict = (n, e) __A : Dict = (n, d) return (public_key, private_key) def _SCREAMING_SNAKE_CASE ( a , a ) -> None: if os.path.exists(F"""{name}_pubkey.txt""" ) or os.path.exists(F"""{name}_privkey.txt""" ): print('\nWARNING:' ) print( F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n""" 'Use a different name or delete these files and re-run this program.' ) sys.exit() __A , __A : Optional[int] = generate_key(a ) print(F"""\nWriting public key to file {name}_pubkey.txt...""" ) with open(F"""{name}_pubkey.txt""" , 'w' ) as out_file: out_file.write(F"""{key_size},{public_key[0]},{public_key[1]}""" ) print(F"""Writing private key to file {name}_privkey.txt...""" ) with open(F"""{name}_privkey.txt""" , 'w' ) as out_file: out_file.write(F"""{key_size},{private_key[0]},{private_key[1]}""" ) if __name__ == "__main__": main()
77
1
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Tuple = {'''configuration_mmbt''': ['''MMBTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = ['''MMBTForClassification''', '''MMBTModel''', '''ModalEmbeddings'''] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys UpperCAmelCase : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ProphetNetTokenizer UpperCamelCase : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() __A : Any = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = 'UNwant\u00E9d,running' __A : List[str] = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class(self.vocab_file ) __A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase_ ( self ): __A : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCAmelCase_ ( self ): __A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __A : Optional[int] = {} for i, token in enumerate(_A ): __A : Tuple = i __A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __A : str = tokenizer(_A , padding=_A , return_tensors='pt' ) self.assertIsInstance(_A , _A ) __A : List[str] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A ) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A ) __A : str = tokenizer.build_inputs_with_special_tokens(_A ) __A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
77
1
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 : Union[str, 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 : Dict = ['''OwlViTFeatureExtractor'''] UpperCAmelCase : Union[str, Any] = ['''OwlViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, 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 : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Optional[int] = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } UpperCAmelCase : List[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = BertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : Any = getattr(_A , normalizer_state.pop('type' ) ) __A : Union[str, Any] = do_lower_case __A : Optional[int] = strip_accents __A : List[Any] = tokenize_chinese_chars __A : int = normalizer_class(**_A ) __A : Union[str, Any] = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : Tuple = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[Any] = [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : int = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
1