code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS enable_full_determinism() class __UpperCamelCase ( unittest.TestCase ): __snake_case :Union[str, Any] = StableDiffusionLDMaDPipeline __snake_case :List[str] = TEXT_TO_IMAGE_PARAMS __snake_case :List[str] = TEXT_TO_IMAGE_BATCH_PARAMS __snake_case :str = TEXT_TO_IMAGE_IMAGE_PARAMS def _a ( self : Tuple ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __lowercase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) __lowercase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=_lowerCAmelCase , set_alpha_to_one=_lowerCAmelCase , ) torch.manual_seed(0 ) __lowercase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=6 , out_channels=6 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) __lowercase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) __lowercase = CLIPTextModel(_lowerCAmelCase ) __lowercase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __lowercase = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self : str , _lowerCAmelCase : Any , _lowerCAmelCase : Dict=0 ) -> List[Any]: """simple docstring""" if str(_lowerCAmelCase ).startswith("""mps""" ): __lowercase = torch.manual_seed(_lowerCAmelCase ) else: __lowercase = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase ) __lowercase = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self : List[Any] ) -> List[Any]: """simple docstring""" __lowercase = """cpu""" # ensure determinism for the device-dependent torch.Generator __lowercase = self.get_dummy_components() __lowercase = StableDiffusionLDMaDPipeline(**_lowerCAmelCase ) __lowercase = ldmad_pipe.to(_lowerCAmelCase ) ldmad_pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __lowercase = self.get_dummy_inputs(_lowerCAmelCase ) __lowercase = ldmad_pipe(**_lowerCAmelCase ) __lowercase , __lowercase = output.rgb, output.depth __lowercase = rgb[0, -3:, -3:, -1] __lowercase = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) __lowercase = np.array( [0.37_338_176, 0.70_247, 0.74_203_193, 0.51_643_604, 0.58_256_793, 0.60_932_136, 0.4_181_095, 0.48_355_877, 0.46_535_262] ) __lowercase = np.array([103.46_727, 85.812_004, 87.849_236] ) assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1e-2 assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1e-2 def _a ( self : Tuple ) -> Optional[Any]: """simple docstring""" __lowercase = self.get_dummy_components() __lowercase = StableDiffusionLDMaDPipeline(**_lowerCAmelCase ) __lowercase = ldmad_pipe.to(_lowerCAmelCase ) ldmad_pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __lowercase = self.get_dummy_inputs(_lowerCAmelCase ) __lowercase = 3 * [inputs["""prompt"""]] # forward __lowercase = ldmad_pipe(**_lowerCAmelCase ) __lowercase , __lowercase = output.rgb, output.depth __lowercase = rgb_slice_a[0, -3:, -3:, -1] __lowercase = depth_slice_a[0, -3:, -1] __lowercase = self.get_dummy_inputs(_lowerCAmelCase ) __lowercase = 3 * [inputs.pop("""prompt""" )] __lowercase = ldmad_pipe.tokenizer( _lowerCAmelCase , padding="""max_length""" , max_length=ldmad_pipe.tokenizer.model_max_length , truncation=_lowerCAmelCase , return_tensors="""pt""" , ) __lowercase = text_inputs["""input_ids"""].to(_lowerCAmelCase ) __lowercase = ldmad_pipe.text_encoder(_lowerCAmelCase )[0] __lowercase = prompt_embeds # forward __lowercase = ldmad_pipe(**_lowerCAmelCase ) __lowercase , __lowercase = output.rgb, output.depth __lowercase = rgb_slice_a[0, -3:, -3:, -1] __lowercase = depth_slice_a[0, -3:, -1] assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1e-4 assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1e-4 def _a ( self : Any ) -> Optional[int]: """simple docstring""" __lowercase = """cpu""" # ensure determinism for the device-dependent torch.Generator __lowercase = self.get_dummy_components() __lowercase = PNDMScheduler(skip_prk_steps=_lowerCAmelCase ) __lowercase = StableDiffusionLDMaDPipeline(**_lowerCAmelCase ) __lowercase = ldmad_pipe.to(_lowerCAmelCase ) ldmad_pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __lowercase = self.get_dummy_inputs(_lowerCAmelCase ) __lowercase = """french fries""" __lowercase = ldmad_pipe(**_lowerCAmelCase , negative_prompt=_lowerCAmelCase ) __lowercase , __lowercase = output.rgb, output.depth __lowercase = rgb[0, -3:, -3:, -1] __lowercase = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) __lowercase = np.array( [0.37_044, 0.71_811_503, 0.7_223_251, 0.48_603_675, 0.5_638_391, 0.6_364_948, 0.42_833_704, 0.4_901_315, 0.47_926_217] ) __lowercase = np.array([107.84_738, 84.62_802, 89.962_135] ) assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1e-2 assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1e-2 @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def _a ( self : int ) -> Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self : Optional[int] , _lowerCAmelCase : int , _lowerCAmelCase : List[Any]="cpu" , _lowerCAmelCase : int=torch.floataa , _lowerCAmelCase : int=0 ) -> Optional[int]: """simple docstring""" __lowercase = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase ) __lowercase = np.random.RandomState(_lowerCAmelCase ).standard_normal((1, 4, 64, 64) ) __lowercase = torch.from_numpy(_lowerCAmelCase ).to(device=_lowerCAmelCase , dtype=_lowerCAmelCase ) __lowercase = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _a ( self : List[Any] ) -> Dict: """simple docstring""" __lowercase = StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d""" ) __lowercase = ldmad_pipe.to(_lowerCAmelCase ) ldmad_pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __lowercase = self.get_inputs(_lowerCAmelCase ) __lowercase = ldmad_pipe(**_lowerCAmelCase ) __lowercase , __lowercase = output.rgb, output.depth __lowercase = rgb[0, -3:, -3:, -1].flatten() __lowercase = rgb[0, -3:, -1].flatten() assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512) __lowercase = np.array( [0.53_805_465, 0.56_707_305, 0.5_486_515, 0.57_012_236, 0.5_814_511, 0.56_253_487, 0.54_843_014, 0.55_092_263, 0.6_459_706] ) __lowercase = np.array( [0.9_263_781, 0.6_678_672, 0.5_486_515, 0.92_202_145, 0.67_831_135, 0.56_253_487, 0.9_241_694, 0.7_551_478, 0.6_459_706] ) assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3e-3 assert np.abs(depth_slice - expected_slice_depth ).max() < 3e-3 @nightly @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): def _a ( self : int ) -> Tuple: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self : Any , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Optional[Any]="cpu" , _lowerCAmelCase : Dict=torch.floataa , _lowerCAmelCase : Optional[int]=0 ) -> Tuple: """simple docstring""" __lowercase = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase ) __lowercase = np.random.RandomState(_lowerCAmelCase ).standard_normal((1, 4, 64, 64) ) __lowercase = torch.from_numpy(_lowerCAmelCase ).to(device=_lowerCAmelCase , dtype=_lowerCAmelCase ) __lowercase = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 50, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _a ( self : Optional[Any] ) -> int: """simple docstring""" __lowercase = StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d""" ).to(_lowerCAmelCase ) ldmad_pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __lowercase = self.get_inputs(_lowerCAmelCase ) __lowercase = ldmad_pipe(**_lowerCAmelCase ) __lowercase , __lowercase = output.rgb, output.depth __lowercase = 0.495_586 __lowercase = 0.33_795_515 __lowercase = 112.48_518 __lowercase = 98.489_746 assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3 assert np.abs(expected_depth_std - depth.std() ) < 1e-3 def _a ( self : Tuple ) -> Dict: """simple docstring""" __lowercase = StableDiffusionLDMaDPipeline.from_pretrained("""Intel/ldm3d-4c""" ).to(_lowerCAmelCase ) ldmad_pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __lowercase = self.get_inputs(_lowerCAmelCase ) __lowercase = ldmad_pipe(**_lowerCAmelCase ) __lowercase , __lowercase = output.rgb, output.depth __lowercase = 0.4_194_127 __lowercase = 0.35_375_586 __lowercase = 0.5_638_502 __lowercase = 0.34_686_103 assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512, 1) assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3 assert np.abs(expected_depth_std - depth.std() ) < 1e-3
80
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
0
import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL _snake_case : str = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11") def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=False , ): output_path.parent.mkdir(parents=__lowerCamelCase , exist_ok=__lowerCamelCase ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( __lowerCamelCase , __lowerCamelCase , f=output_path.as_posix() , input_names=__lowerCamelCase , output_names=__lowerCamelCase , dynamic_axes=__lowerCamelCase , do_constant_folding=__lowerCamelCase , use_external_data_format=__lowerCamelCase , enable_onnx_checker=__lowerCamelCase , opset_version=__lowerCamelCase , ) else: export( __lowerCamelCase , __lowerCamelCase , f=output_path.as_posix() , input_names=__lowerCamelCase , output_names=__lowerCamelCase , dynamic_axes=__lowerCamelCase , do_constant_folding=__lowerCamelCase , opset_version=__lowerCamelCase , ) @torch.no_grad() def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = False ): __snake_case : Any = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): __snake_case : Union[str, Any] = "cuda" elif fpaa and not torch.cuda.is_available(): raise ValueError("`float16` model export is only supported on GPUs with CUDA" ) else: __snake_case : str = "cpu" __snake_case : List[Any] = Path(__lowerCamelCase ) # VAE DECODER __snake_case : Tuple = AutoencoderKL.from_pretrained(model_path + "/vae" ) __snake_case : str = vae_decoder.config.latent_channels # forward only through the decoder part __snake_case : Tuple = vae_decoder.decode onnx_export( __lowerCamelCase , model_args=( torch.randn(1 , __lowerCamelCase , 2_5 , 2_5 ).to(device=__lowerCamelCase , dtype=__lowerCamelCase ), False, ) , output_path=output_path / "vae_decoder" / "model.onnx" , ordered_input_names=["latent_sample", "return_dict"] , output_names=["sample"] , dynamic_axes={ "latent_sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, } , opset=__lowerCamelCase , ) del vae_decoder if __name__ == "__main__": _snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument( "--model_path", type=str, required=True, help="Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).", ) parser.add_argument("--output_path", type=str, required=True, help="Path to the output model.") parser.add_argument( "--opset", default=14, type=int, help="The version of the ONNX operator set to use.", ) parser.add_argument("--fp16", action="store_true", default=False, help="Export the models in `float16` mode") _snake_case : Optional[int] = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print("SD: Done: ONNX")
81
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 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 (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [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 _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , 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( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = 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 _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 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 _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 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""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
0
"""simple docstring""" def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = set() # To detect a back edge, keep track of vertices currently in the recursion stack UpperCAmelCase_ = set() return any( node not in visited and depth_first_search(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for node in graph ) def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): visited.add(lowerCAmelCase__ ) rec_stk.add(lowerCAmelCase__ ) for node in graph[vertex]: if node not in visited: if depth_first_search(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(lowerCAmelCase__ ) return False if __name__ == "__main__": from doctest import testmod testmod()
82
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
0
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class __snake_case ( _lowercase): snake_case__ : int = "philschmid/bart-large-cnn-samsum" snake_case__ : List[Any] = ( "This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, " "and returns a summary of the text." ) snake_case__ : int = "summarizer" snake_case__ : Dict = AutoTokenizer snake_case__ : Union[str, Any] = AutoModelForSeqaSeqLM snake_case__ : List[str] = ["text"] snake_case__ : Union[str, Any] = ["text"] def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : str ): """simple docstring""" return self.pre_processor(__lowerCAmelCase , return_tensors='''pt''' , truncation=__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Optional[Any] ): """simple docstring""" return self.model.generate(**__lowerCAmelCase )[0] def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" return self.pre_processor.decode(__lowerCAmelCase , skip_special_tokens=__lowerCAmelCase , clean_up_tokenization_spaces=__lowerCAmelCase )
83
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
0
import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __lowerCamelCase , unittest.TestCase ): '''simple docstring''' _UpperCamelCase : List[str] = LongformerTokenizer _UpperCamelCase : Any = True _UpperCamelCase : Optional[Any] = LongformerTokenizerFast _UpperCamelCase : Union[str, Any] = True def SCREAMING_SNAKE_CASE__ ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowercase = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] lowercase = dict(zip(snake_case , range(len(snake_case ) ) ) ) lowercase = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] lowercase = {'unk_token': '<unk>'} lowercase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowercase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(snake_case ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(snake_case ) ) def SCREAMING_SNAKE_CASE__ ( self , **snake_case ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **snake_case ) def SCREAMING_SNAKE_CASE__ ( self , **snake_case ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **snake_case ) def SCREAMING_SNAKE_CASE__ ( self , snake_case ): lowercase = 'lower newer' lowercase = 'lower newer' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowercase = 'lower newer' lowercase = ['l', 'o', 'w', 'er', '\u0120', 'n', 'e', 'w', 'er'] lowercase = tokenizer.tokenize(snake_case ) # , add_prefix_space=True) self.assertListEqual(snake_case , snake_case ) lowercase = tokens + [tokenizer.unk_token] lowercase = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case ) , snake_case ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.get_tokenizer() self.assertListEqual(tokenizer.encode('Hello world!' , add_special_tokens=snake_case ) , [0, 3_1414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode('Hello world! cécé herlolip 418' , add_special_tokens=snake_case ) , [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2] , ) @slow def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.tokenizer_class.from_pretrained('allenai/longformer-base-4096' ) lowercase = tokenizer.encode('sequence builders' , add_special_tokens=snake_case ) lowercase = tokenizer.encode('multi-sequence build' , add_special_tokens=snake_case ) lowercase = tokenizer.encode( 'sequence builders' , add_special_tokens=snake_case , add_prefix_space=snake_case ) lowercase = tokenizer.encode( 'sequence builders' , 'multi-sequence build' , add_special_tokens=snake_case , add_prefix_space=snake_case ) lowercase = tokenizer.build_inputs_with_special_tokens(snake_case ) lowercase = tokenizer.build_inputs_with_special_tokens(snake_case , snake_case ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.get_tokenizer() lowercase = 'Encode this sequence.' lowercase = tokenizer.byte_encoder[' '.encode('utf-8' )[0]] # Testing encoder arguments lowercase = tokenizer.encode(snake_case , add_special_tokens=snake_case , add_prefix_space=snake_case ) lowercase = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(snake_case , snake_case ) lowercase = tokenizer.encode(snake_case , add_special_tokens=snake_case , add_prefix_space=snake_case ) lowercase = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(snake_case , snake_case ) tokenizer.add_special_tokens({'bos_token': '<s>'} ) lowercase = tokenizer.encode(snake_case , add_special_tokens=snake_case ) lowercase = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(snake_case , snake_case ) # Testing spaces after special tokens lowercase = '<mask>' tokenizer.add_special_tokens( {'mask_token': AddedToken(snake_case , lstrip=snake_case , rstrip=snake_case )} ) # mask token has a left space lowercase = tokenizer.convert_tokens_to_ids(snake_case ) lowercase = 'Encode <mask> sequence' lowercase = 'Encode <mask>sequence' lowercase = tokenizer.encode(snake_case ) lowercase = encoded.index(snake_case ) lowercase = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(snake_case , snake_case ) lowercase = tokenizer.encode(snake_case ) lowercase = encoded.index(snake_case ) lowercase = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(snake_case , snake_case ) def SCREAMING_SNAKE_CASE__ ( self ): pass def SCREAMING_SNAKE_CASE__ ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase = self.rust_tokenizer_class.from_pretrained(snake_case , **snake_case ) lowercase = self.tokenizer_class.from_pretrained(snake_case , **snake_case ) lowercase = 'A, <mask> AllenNLP sentence.' lowercase = tokenizer_r.encode_plus(snake_case , add_special_tokens=snake_case , return_token_type_ids=snake_case ) lowercase = tokenizer_p.encode_plus(snake_case , add_special_tokens=snake_case , return_token_type_ids=snake_case ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['token_type_ids'] ) , sum(tokens_p['token_type_ids'] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['attention_mask'] ) / len(tokens_r['attention_mask'] ) , sum(tokens_p['attention_mask'] ) / len(tokens_p['attention_mask'] ) , ) lowercase = tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids'] ) lowercase = tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids'] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['input_ids'] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r['input_ids'] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( snake_case , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] ) self.assertSequenceEqual( snake_case , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] ) def SCREAMING_SNAKE_CASE__ ( self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): lowercase = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=snake_case , add_prefix_space=snake_case , trim_offsets=snake_case ) lowercase = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) lowercase = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state['add_prefix_space'] , snake_case ) self.assertEqual(post_processor_state['add_prefix_space'] , snake_case ) self.assertEqual(post_processor_state['trim_offsets'] , snake_case ) def SCREAMING_SNAKE_CASE__ ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` lowercase = F'''{text_of_1_token} {text_of_1_token}''' lowercase = self.rust_tokenizer_class.from_pretrained( snake_case , use_fast=snake_case , add_prefix_space=snake_case , trim_offsets=snake_case ) lowercase = tokenizer_r(snake_case , return_offsets_mapping=snake_case , add_special_tokens=snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, len(snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (len(snake_case ) + 1, len(snake_case ) + 1 + len(snake_case )) , ) lowercase = self.rust_tokenizer_class.from_pretrained( snake_case , use_fast=snake_case , add_prefix_space=snake_case , trim_offsets=snake_case ) lowercase = tokenizer_r(snake_case , return_offsets_mapping=snake_case , add_special_tokens=snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, len(snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (len(snake_case ) + 1, len(snake_case ) + 1 + len(snake_case )) , ) lowercase = self.rust_tokenizer_class.from_pretrained( snake_case , use_fast=snake_case , add_prefix_space=snake_case , trim_offsets=snake_case ) lowercase = tokenizer_r(snake_case , return_offsets_mapping=snake_case , add_special_tokens=snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, len(snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (len(snake_case ), len(snake_case ) + 1 + len(snake_case )) , ) lowercase = self.rust_tokenizer_class.from_pretrained( snake_case , use_fast=snake_case , add_prefix_space=snake_case , trim_offsets=snake_case ) lowercase = tokenizer_r(snake_case , return_offsets_mapping=snake_case , add_special_tokens=snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, len(snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (len(snake_case ), len(snake_case ) + 1 + len(snake_case )) , ) lowercase = F''' {text}''' # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) lowercase = self.rust_tokenizer_class.from_pretrained( snake_case , use_fast=snake_case , add_prefix_space=snake_case , trim_offsets=snake_case ) lowercase = tokenizer_r(snake_case , return_offsets_mapping=snake_case , add_special_tokens=snake_case ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(snake_case ) + 1, 1 + len(snake_case ) + 1 + len(snake_case )) , ) lowercase = self.rust_tokenizer_class.from_pretrained( snake_case , use_fast=snake_case , add_prefix_space=snake_case , trim_offsets=snake_case ) lowercase = tokenizer_r(snake_case , return_offsets_mapping=snake_case , add_special_tokens=snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(snake_case ), 1 + len(snake_case ) + 1 + len(snake_case )) , ) lowercase = self.rust_tokenizer_class.from_pretrained( snake_case , use_fast=snake_case , add_prefix_space=snake_case , trim_offsets=snake_case ) lowercase = tokenizer_r(snake_case , return_offsets_mapping=snake_case , add_special_tokens=snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(snake_case ), 1 + len(snake_case ) + 1 + len(snake_case )) , )
84
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : 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=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
0
def _a ( lowercase__ : str ): '''simple docstring''' if n_term == "": return [] SCREAMING_SNAKE_CASE__ : list = [] for temp in range(int(lowercase__ ) ): series.append(f'''1/{temp + 1}''' if series else '1' ) return series if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
85
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __a :Optional[int] = { 'configuration_git': ['GIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GitConfig', 'GitVisionConfig'], 'processing_git': ['GitProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a :List[Any] = [ 'GIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'GitForCausalLM', 'GitModel', 'GitPreTrainedModel', 'GitVisionModel', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys __a :int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
86
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[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(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
0
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str=13 , UpperCAmelCase__ : List[str]=7 , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Any=99 , UpperCAmelCase__ : Optional[int]=32 , UpperCAmelCase__ : Any=5 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : Union[str, Any]=37 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : Optional[Any]=512 , UpperCAmelCase__ : Any=16 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : Dict=0.02 , UpperCAmelCase__ : Dict=4 , ) ->Optional[Any]: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_attention_mask A__ = use_token_type_ids A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = type_vocab_size A__ = type_sequence_label_size A__ = initializer_range A__ = num_choices def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->List[str]: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A__ = None if self.use_attention_mask: A__ = random_attention_mask([self.batch_size, self.seq_length]) A__ = None if self.use_token_type_ids: A__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) A__ = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def SCREAMING_SNAKE_CASE ( self : Tuple) ->int: '''simple docstring''' A__ = self.prepare_config_and_inputs() A__ , A__ , A__ , A__ = config_and_inputs A__ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Optional[Any]: '''simple docstring''' A__ = self.prepare_config_and_inputs() A__ , A__ , A__ , A__ = config_and_inputs A__ = True A__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) A__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = True UpperCAmelCase__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Optional[int]: '''simple docstring''' A__ = FlaxRobertaPreLayerNormModelTester(self) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->str: '''simple docstring''' for model_class_name in self.all_model_classes: A__ = model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=UpperCAmelCase__) A__ = model(np.ones((1, 1))) self.assertIsNotNone(UpperCAmelCase__) @require_flax class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE ( self : str) ->Optional[int]: '''simple docstring''' A__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=UpperCAmelCase__) A__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa) A__ = model(UpperCAmelCase__)[0] A__ = [1, 11, 50_265] self.assertEqual(list(output.shape) , UpperCAmelCase__) # compare the actual values for a slice. A__ = np.array( [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]] , dtype=np.floataa) self.assertTrue(np.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4)) @slow def SCREAMING_SNAKE_CASE ( self : str) ->Any: '''simple docstring''' A__ = FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=UpperCAmelCase__) A__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa) A__ = model(UpperCAmelCase__)[0] # compare the actual values for a slice. A__ = np.array( [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]] , dtype=np.floataa) self.assertTrue(np.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4))
87
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
0
"""simple docstring""" 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 lowercase__ ( unittest.TestCase ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=224 , SCREAMING_SNAKE_CASE=30 , SCREAMING_SNAKE_CASE=400 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> int: _lowerCamelCase : int = size if size is not None else {"""height""": 18, """width""": 18} _lowerCamelCase : int = parent _lowerCamelCase : Any = batch_size _lowerCamelCase : Union[str, Any] = num_channels _lowerCamelCase : Optional[int] = image_size _lowerCamelCase : Optional[int] = min_resolution _lowerCamelCase : Any = max_resolution _lowerCamelCase : Any = do_resize _lowerCamelCase : Tuple = size _lowerCamelCase : Tuple = do_normalize _lowerCamelCase : int = image_mean _lowerCamelCase : Union[str, Any] = image_std def UpperCamelCase_ ( self) -> List[str]: 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 lowercase__ ( A_ ,unittest.TestCase ): __UpperCAmelCase = ViTImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Optional[int] = EfficientFormerImageProcessorTester(self) @property def UpperCamelCase_ ( self) -> List[Any]: return self.image_proc_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """image_mean""")) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """image_std""")) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """do_normalize""")) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """do_resize""")) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """size""")) def UpperCamelCase_ ( self) -> str: pass def UpperCamelCase_ ( self) -> int: # Initialize image_processor _lowerCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images _lowerCamelCase : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=SCREAMING_SNAKE_CASE) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE , Image.Image) # Test not batched input _lowerCamelCase : 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 _lowerCamelCase : str = image_processor(SCREAMING_SNAKE_CASE , 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) -> int: # Initialize image_processor _lowerCamelCase : List[str] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors _lowerCamelCase : Optional[int] = prepare_image_inputs(self.image_proc_tester , equal_resolution=SCREAMING_SNAKE_CASE , numpify=SCREAMING_SNAKE_CASE) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE , np.ndarray) # Test not batched input _lowerCamelCase : Optional[int] = 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 _lowerCamelCase : List[Any] = image_processor(SCREAMING_SNAKE_CASE , 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) -> str: # Initialize image_processor _lowerCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors _lowerCamelCase : int = prepare_image_inputs(self.image_proc_tester , equal_resolution=SCREAMING_SNAKE_CASE , torchify=SCREAMING_SNAKE_CASE) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE , torch.Tensor) # Test not batched input _lowerCamelCase : 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 _lowerCamelCase : Union[str, Any] = image_processor(SCREAMING_SNAKE_CASE , 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"""], ) , )
88
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Tuple = { "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class _lowerCamelCase( _a ): lowercase_ : Dict = """blip_2_vision_model""" def __init__( self, lowerCamelCase=14_08, lowerCamelCase=61_44, lowerCamelCase=39, lowerCamelCase=16, lowerCamelCase=2_24, lowerCamelCase=14, lowerCamelCase="gelu", lowerCamelCase=0.0_0_0_0_1, lowerCamelCase=0.0, lowerCamelCase=1E-10, lowerCamelCase=True, **lowerCamelCase, ) -> List[Any]: """simple docstring""" super().__init__(**lowerCamelCase) _lowercase : Optional[int] = hidden_size _lowercase : Dict = intermediate_size _lowercase : Dict = num_hidden_layers _lowercase : Optional[int] = num_attention_heads _lowercase : Tuple = patch_size _lowercase : str = image_size _lowercase : Optional[int] = initializer_range _lowercase : Any = attention_dropout _lowercase : List[str] = layer_norm_eps _lowercase : Dict = hidden_act _lowercase : Tuple = qkv_bias @classmethod def UpperCamelCase ( cls, lowerCamelCase, **lowerCamelCase) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(lowerCamelCase) _lowercase , _lowercase : str = cls.get_config_dict(lowerCamelCase, **lowerCamelCase) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type') == "blip-2": _lowercase : Tuple = config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls, 'model_type') and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''') return cls.from_dict(lowerCamelCase, **lowerCamelCase) class _lowerCamelCase( _a ): lowercase_ : Union[str, Any] = """blip_2_qformer""" def __init__( self, lowerCamelCase=3_05_22, lowerCamelCase=7_68, lowerCamelCase=12, lowerCamelCase=12, lowerCamelCase=30_72, lowerCamelCase="gelu", lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=5_12, lowerCamelCase=0.0_2, lowerCamelCase=1E-12, lowerCamelCase=0, lowerCamelCase="absolute", lowerCamelCase=2, lowerCamelCase=14_08, **lowerCamelCase, ) -> Optional[Any]: """simple docstring""" super().__init__(pad_token_id=lowerCamelCase, **lowerCamelCase) _lowercase : Union[str, Any] = vocab_size _lowercase : Dict = hidden_size _lowercase : List[Any] = num_hidden_layers _lowercase : Optional[Any] = num_attention_heads _lowercase : str = hidden_act _lowercase : Optional[Any] = intermediate_size _lowercase : int = hidden_dropout_prob _lowercase : List[Any] = attention_probs_dropout_prob _lowercase : List[Any] = max_position_embeddings _lowercase : int = initializer_range _lowercase : Optional[int] = layer_norm_eps _lowercase : Union[str, Any] = position_embedding_type _lowercase : str = cross_attention_frequency _lowercase : List[str] = encoder_hidden_size @classmethod def UpperCamelCase ( cls, lowerCamelCase, **lowerCamelCase) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(lowerCamelCase) _lowercase , _lowercase : List[str] = cls.get_config_dict(lowerCamelCase, **lowerCamelCase) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type') == "blip-2": _lowercase : str = config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls, 'model_type') and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''') return cls.from_dict(lowerCamelCase, **lowerCamelCase) class _lowerCamelCase( _a ): lowercase_ : Dict = """blip-2""" lowercase_ : Optional[int] = True def __init__( self, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase=32, **lowerCamelCase) -> Optional[int]: """simple docstring""" super().__init__(**lowerCamelCase) if vision_config is None: _lowercase : int = {} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.') if qformer_config is None: _lowercase : Any = {} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.') if text_config is None: _lowercase : Tuple = {} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).') _lowercase : Dict = BlipaVisionConfig(**lowerCamelCase) _lowercase : List[Any] = BlipaQFormerConfig(**lowerCamelCase) _lowercase : Union[str, Any] = text_config['model_type'] if 'model_type' in text_config else 'opt' _lowercase : List[Any] = CONFIG_MAPPING[text_model_type](**lowerCamelCase) _lowercase : Optional[int] = self.text_config.tie_word_embeddings _lowercase : Dict = self.text_config.is_encoder_decoder _lowercase : List[str] = num_query_tokens _lowercase : List[str] = self.vision_config.hidden_size _lowercase : List[str] = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES _lowercase : Optional[int] = 1.0 _lowercase : Union[str, Any] = 0.0_2 @classmethod def UpperCamelCase ( cls, lowerCamelCase, lowerCamelCase, lowerCamelCase, **lowerCamelCase, ) -> Union[str, Any]: """simple docstring""" return cls( vision_config=vision_config.to_dict(), qformer_config=qformer_config.to_dict(), text_config=text_config.to_dict(), **lowerCamelCase, ) def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : Optional[Any] = copy.deepcopy(self.__dict__) _lowercase : int = self.vision_config.to_dict() _lowercase : Optional[int] = self.qformer_config.to_dict() _lowercase : Union[str, Any] = self.text_config.to_dict() _lowercase : List[str] = self.__class__.model_type return output
89
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
0
'''simple docstring''' from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers __UpperCAmelCase = [ '''python''', '''tqdm''', '''regex''', '''requests''', '''packaging''', '''filelock''', '''numpy''', '''tokenizers''', '''huggingface-hub''', '''safetensors''', '''accelerate''', '''pyyaml''', ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""") def _snake_case ( A , A=None ) -> Optional[int]: require_version(deps[pkg] , A )
90
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
0
"""simple docstring""" from itertools import product def _snake_case ( snake_case__ : int , snake_case__ : int ): A = sides_number A = max_face_number * dice_number A = [0] * (max_total + 1) A = 1 A = range(snake_case__ , max_face_number + 1 ) for dice_numbers in product(snake_case__ , repeat=snake_case__ ): A = sum(snake_case__ ) totals_frequencies[total] += 1 return totals_frequencies def _snake_case ( ): A = total_frequency_distribution( sides_number=4 , dice_number=9 ) A = total_frequency_distribution( sides_number=6 , dice_number=6 ) A = 0 A = 9 A = 4 * 9 A = 6 for peter_total in range(snake_case__ , max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) A = (4**9) * (6**6) A = peter_wins_count / total_games_number A = round(snake_case__ , ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(F"""{solution() = }""")
91
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
0
'''simple docstring''' from __future__ import annotations from statistics import mean def _lowerCAmelCase ( __magic_name__ : list[int] , __magic_name__ : list[int] , __magic_name__ : int ) -> list[int]: lowercase : List[str] =[0] * no_of_processes lowercase : int =[0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(__magic_name__ ): lowercase : Union[str, Any] =burst_time[i] lowercase : list[int] =[] lowercase : str =0 lowercase : int =0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: lowercase : str =[] lowercase : Tuple =-1 for i in range(__magic_name__ ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(__magic_name__ ) if len(__magic_name__ ) > 0: lowercase : int =ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: lowercase : Tuple =i total_time += burst_time[target_process] completed += 1 lowercase : int =0 lowercase : List[str] =( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def _lowerCAmelCase ( __magic_name__ : list[int] , __magic_name__ : int , __magic_name__ : list[int] ) -> list[int]: lowercase : Optional[int] =[0] * no_of_processes for i in range(__magic_name__ ): lowercase : List[Any] =burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("""[TEST CASE 01]""") UpperCamelCase_ = 4 UpperCamelCase_ = [2, 5, 3, 7] UpperCamelCase_ = [0, 0, 0, 0] UpperCamelCase_ = calculate_waitingtime(arrival_time, burst_time, no_of_processes) UpperCamelCase_ = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("""PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time""") for i, process_id in enumerate(list(range(1, 5))): print( f'''{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t''' f'''{waiting_time[i]}\t\t\t\t{turn_around_time[i]}''' ) print(f'''\nAverage waiting time = {mean(waiting_time):.5f}''') print(f'''Average turnaround time = {mean(turn_around_time):.5f}''')
92
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
0
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def __A (_SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = 0 lowerCAmelCase__ :Union[str, Any] = number while duplicate > 0: lowerCAmelCase__ , lowerCAmelCase__ :List[str] = divmod(_SCREAMING_SNAKE_CASE , 10 ) fact_sum += factorial(_SCREAMING_SNAKE_CASE ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") __A = int(input("""Enter number: """).strip()) print( F'''{number} is {"" if krishnamurthy(number) else "not "}a Krishnamurthy Number.''' )
93
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig SCREAMING_SNAKE_CASE = [ 'openmmlab/upernet-convnext-tiny', # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring SCREAMING_SNAKE_CASE = 'UperNetConfig' class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : Union[int, Tuple[int, int]] , UpperCAmelCase : Union[int, Tuple[int, int], str] = 0 , UpperCAmelCase : bool = False , UpperCAmelCase : Union[int, Tuple[int, int]] = 1 , ) -> None: '''simple docstring''' super().__init__() lowercase : List[Any] =nn.Convad( in_channels=UpperCAmelCase , out_channels=UpperCAmelCase , kernel_size=UpperCAmelCase , padding=UpperCAmelCase , bias=UpperCAmelCase , dilation=UpperCAmelCase , ) lowercase : Dict =nn.BatchNormad(UpperCAmelCase ) lowercase : Any =nn.ReLU() def A__ ( self : List[Any] , UpperCAmelCase : torch.Tensor ) -> torch.Tensor: '''simple docstring''' lowercase : Tuple =self.conv(UpperCAmelCase ) lowercase : Tuple =self.batch_norm(UpperCAmelCase ) lowercase : Any =self.activation(UpperCAmelCase ) return output class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : int ) -> None: '''simple docstring''' super().__init__() lowercase : int =[ nn.AdaptiveAvgPoolad(UpperCAmelCase ), UperNetConvModule(UpperCAmelCase , UpperCAmelCase , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(UpperCAmelCase ) , UpperCAmelCase ) def A__ ( self : Union[str, Any] , UpperCAmelCase : torch.Tensor ) -> torch.Tensor: '''simple docstring''' lowercase : Tuple =input for layer in self.layers: lowercase : int =layer(UpperCAmelCase ) return hidden_state class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self : Dict , UpperCAmelCase : Tuple[int, ...] , UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : bool ) -> None: '''simple docstring''' super().__init__() lowercase : List[str] =pool_scales lowercase : Optional[Any] =align_corners lowercase : List[str] =in_channels lowercase : Dict =channels lowercase : List[str] =[] for i, pool_scale in enumerate(UpperCAmelCase ): lowercase : List[str] =UperNetPyramidPoolingBlock(pool_scale=UpperCAmelCase , in_channels=UpperCAmelCase , channels=UpperCAmelCase ) self.blocks.append(UpperCAmelCase ) self.add_module(str(UpperCAmelCase ) , UpperCAmelCase ) def A__ ( self : List[Any] , UpperCAmelCase : torch.Tensor ) -> List[torch.Tensor]: '''simple docstring''' lowercase : Optional[int] =[] for ppm in self.blocks: lowercase : Optional[Any] =ppm(UpperCAmelCase ) lowercase : Any =nn.functional.interpolate( UpperCAmelCase , size=x.size()[2:] , mode='''bilinear''' , align_corners=self.align_corners ) ppm_outs.append(UpperCAmelCase ) return ppm_outs class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase : Tuple , UpperCAmelCase : Union[str, Any] ) -> List[str]: '''simple docstring''' super().__init__() lowercase : Dict =config lowercase : str =config.pool_scales # e.g. (1, 2, 3, 6) lowercase : Optional[int] =in_channels lowercase : Tuple =config.hidden_size lowercase : int =False lowercase : List[str] =nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module lowercase : Tuple =UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) lowercase : Optional[Any] =UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module lowercase : Tuple =nn.ModuleList() lowercase : Any =nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer lowercase : List[Any] =UperNetConvModule(UpperCAmelCase , self.channels , kernel_size=1 ) lowercase : Optional[int] =UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(UpperCAmelCase ) self.fpn_convs.append(UpperCAmelCase ) lowercase : str =UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def A__ ( self : str ) -> str: '''simple docstring''' self.apply(self._init_weights ) def A__ ( self : List[Any] , UpperCAmelCase : List[Any] ) -> List[str]: '''simple docstring''' if isinstance(UpperCAmelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def A__ ( self : List[Any] , UpperCAmelCase : Any ) -> Any: '''simple docstring''' lowercase : Optional[Any] =inputs[-1] lowercase : Tuple =[x] psp_outs.extend(self.psp_modules(UpperCAmelCase ) ) lowercase : List[Any] =torch.cat(UpperCAmelCase , dim=1 ) lowercase : str =self.bottleneck(UpperCAmelCase ) return output def A__ ( self : Optional[Any] , UpperCAmelCase : torch.Tensor ) -> torch.Tensor: '''simple docstring''' lowercase : Union[str, Any] =[lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(UpperCAmelCase ) ) # build top-down path lowercase : Any =len(UpperCAmelCase ) for i in range(used_backbone_levels - 1 , 0 , -1 ): lowercase : Optional[int] =laterals[i - 1].shape[2:] lowercase : Tuple =laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=UpperCAmelCase , mode='''bilinear''' , align_corners=self.align_corners ) # build outputs lowercase : Optional[Any] =[self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): lowercase : Optional[int] =nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode='''bilinear''' , align_corners=self.align_corners ) lowercase : Union[str, Any] =torch.cat(UpperCAmelCase , dim=1 ) lowercase : str =self.fpn_bottleneck(UpperCAmelCase ) lowercase : int =self.classifier(UpperCAmelCase ) return output class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self : int , UpperCAmelCase : str , UpperCAmelCase : int = 2 , UpperCAmelCase : int = 3 , UpperCAmelCase : Union[int, Tuple[int, int]] = 1 ) -> None: '''simple docstring''' super().__init__() lowercase : int =config lowercase : Any =config.auxiliary_in_channels lowercase : int =config.auxiliary_channels lowercase : Dict =config.auxiliary_num_convs lowercase : List[Any] =config.auxiliary_concat_input lowercase : List[str] =in_index lowercase : Dict =(kernel_size // 2) * dilation lowercase : Union[str, Any] =[] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=UpperCAmelCase , padding=UpperCAmelCase , dilation=UpperCAmelCase ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=UpperCAmelCase , padding=UpperCAmelCase , dilation=UpperCAmelCase ) ) if self.num_convs == 0: lowercase : int =nn.Identity() else: lowercase : Optional[Any] =nn.Sequential(*UpperCAmelCase ) if self.concat_input: lowercase : Tuple =UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=UpperCAmelCase , padding=kernel_size // 2 ) lowercase : List[Any] =nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def A__ ( self : List[str] ) -> Tuple: '''simple docstring''' self.apply(self._init_weights ) def A__ ( self : Tuple , UpperCAmelCase : str ) -> Dict: '''simple docstring''' if isinstance(UpperCAmelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def A__ ( self : List[str] , UpperCAmelCase : torch.Tensor ) -> torch.Tensor: '''simple docstring''' lowercase : Dict =encoder_hidden_states[self.in_index] lowercase : List[str] =self.convs(UpperCAmelCase ) if self.concat_input: lowercase : str =self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) lowercase : List[str] =self.classifier(UpperCAmelCase ) return output class UpperCAmelCase_ ( __A ): """simple docstring""" UpperCamelCase_ = UperNetConfig UpperCamelCase_ = '''pixel_values''' UpperCamelCase_ = True def A__ ( self : List[Any] , UpperCAmelCase : List[Any] ) -> Any: '''simple docstring''' if isinstance(UpperCAmelCase , UpperCAmelCase ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def A__ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def A__ ( self : Tuple , UpperCAmelCase : Any , UpperCAmelCase : Optional[Any]=False ) -> List[str]: '''simple docstring''' if isinstance(UpperCAmelCase , UpperCAmelCase ): lowercase : List[Any] =value SCREAMING_SNAKE_CASE = r'\n Parameters:\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' SCREAMING_SNAKE_CASE = r'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n `attentions` under returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( '''UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.''' , __A , ) class UpperCAmelCase_ ( __A ): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase : str ) -> Optional[int]: '''simple docstring''' super().__init__(UpperCAmelCase ) lowercase : Optional[int] =AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) lowercase : Optional[Any] =UperNetHead(UpperCAmelCase , in_channels=self.backbone.channels ) lowercase : Optional[int] =UperNetFCNHead(UpperCAmelCase ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format('''batch_size, sequence_length''' ) ) @replace_return_docstrings(output_type=UpperCAmelCase , config_class=_CONFIG_FOR_DOC ) def A__ ( self : Dict , UpperCAmelCase : Optional[torch.Tensor] = None , UpperCAmelCase : Optional[bool] = None , UpperCAmelCase : Optional[bool] = None , UpperCAmelCase : Optional[torch.Tensor] = None , UpperCAmelCase : Optional[bool] = None , ) -> Union[tuple, SemanticSegmenterOutput]: '''simple docstring''' lowercase : Tuple =return_dict if return_dict is not None else self.config.use_return_dict lowercase : List[str] =( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowercase : Any =output_attentions if output_attentions is not None else self.config.output_attentions lowercase : Union[str, Any] =self.backbone.forward_with_filtered_kwargs( UpperCAmelCase , output_hidden_states=UpperCAmelCase , output_attentions=UpperCAmelCase ) lowercase : List[Any] =outputs.feature_maps lowercase : Dict =self.decode_head(UpperCAmelCase ) lowercase : List[Any] =nn.functional.interpolate(UpperCAmelCase , size=pixel_values.shape[2:] , mode='''bilinear''' , align_corners=UpperCAmelCase ) lowercase : str =None if self.auxiliary_head is not None: lowercase : Optional[Any] =self.auxiliary_head(UpperCAmelCase ) lowercase : int =nn.functional.interpolate( UpperCAmelCase , size=pixel_values.shape[2:] , mode='''bilinear''' , align_corners=UpperCAmelCase ) lowercase : Optional[int] =None if labels is not None: if self.config.num_labels == 1: raise ValueError('''The number of labels should be greater than one''' ) else: # compute weighted loss lowercase : Optional[Any] =CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) lowercase : List[Any] =loss_fct(UpperCAmelCase , UpperCAmelCase ) lowercase : Any =loss_fct(UpperCAmelCase , UpperCAmelCase ) lowercase : List[str] =main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: lowercase : Tuple =(logits,) + outputs[1:] else: lowercase : Tuple =(logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=UpperCAmelCase , logits=UpperCAmelCase , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
94
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
0
"""simple docstring""" from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar lowerCamelCase_ = TypeVar('''T''') lowerCamelCase_ = TypeVar('''U''') class UpperCamelCase_ (Generic[T, U] ): def __init__( self : Tuple , lowerCAmelCase_ : T | None , lowerCAmelCase_ : U | None ) -> List[Any]: UpperCAmelCase_ : Optional[Any] = key UpperCAmelCase_ : Optional[int] = val UpperCAmelCase_ : DoubleLinkedListNode[T, U] | None = None UpperCAmelCase_ : DoubleLinkedListNode[T, U] | None = None def __repr__( self : List[str] ) -> str: return ( f"""Node: key: {self.key}, val: {self.val}, """ f"""has next: {bool(self.next )}, has prev: {bool(self.prev )}""" ) class UpperCamelCase_ (Generic[T, U] ): def __init__( self : str ) -> None: UpperCAmelCase_ : DoubleLinkedListNode[T, U] = DoubleLinkedListNode(lowerCAmelCase_ , lowerCAmelCase_ ) UpperCAmelCase_ : DoubleLinkedListNode[T, U] = DoubleLinkedListNode(lowerCAmelCase_ , lowerCAmelCase_ ) UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = self.rear, self.head def __repr__( self : Optional[Any] ) -> str: UpperCAmelCase_ : Tuple = ["DoubleLinkedList"] UpperCAmelCase_ : List[Any] = self.head while node.next is not None: rep.append(str(lowerCAmelCase_ ) ) UpperCAmelCase_ : Tuple = node.next rep.append(str(self.rear ) ) return ",\n ".join(lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase_ : DoubleLinkedListNode[T, U] ) -> None: UpperCAmelCase_ : Dict = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None UpperCAmelCase_ : List[Any] = node UpperCAmelCase_ : Any = previous UpperCAmelCase_ : List[Any] = node UpperCAmelCase_ : Dict = self.rear def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: if node.prev is None or node.next is None: return None UpperCAmelCase_ : List[Any] = node.next UpperCAmelCase_ : Optional[Any] = node.prev UpperCAmelCase_ : List[str] = None UpperCAmelCase_ : str = None return node class UpperCamelCase_ (Generic[T, U] ): __magic_name__ = {} def __init__( self : Optional[Any] , lowerCAmelCase_ : int ) -> List[Any]: UpperCAmelCase_ : DoubleLinkedList[T, U] = DoubleLinkedList() UpperCAmelCase_ : List[str] = capacity UpperCAmelCase_ : Tuple = 0 UpperCAmelCase_ : List[str] = 0 UpperCAmelCase_ : List[str] = 0 UpperCAmelCase_ : dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__( self : int ) -> str: return ( f"""CacheInfo(hits={self.hits}, misses={self.miss}, """ f"""capacity={self.capacity}, current size={self.num_keys})""" ) def __contains__( self : List[Any] , lowerCAmelCase_ : T ) -> bool: return key in self.cache def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : T ) -> U | None: # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 UpperCAmelCase_ : DoubleLinkedListNode[T, U] = self.cache[key] UpperCAmelCase_ : int = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(lowerCAmelCase_ ) return node.val self.miss += 1 return None def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase_ : T , lowerCAmelCase_ : U ) -> None: if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity UpperCAmelCase_ : str = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(lowerCAmelCase_ ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 UpperCAmelCase_ : List[Any] = DoubleLinkedListNode(lowerCAmelCase_ , lowerCAmelCase_ ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value UpperCAmelCase_ : Optional[Any] = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list UpperCAmelCase_ : str = value self.list.add(lowerCAmelCase_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int , lowerCAmelCase_ : int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: def cache_decorator_inner(lowerCAmelCase_ : Callable[[T], U] ) -> Callable[..., U]: def cache_decorator_wrapper(*lowerCAmelCase_ : T ) -> U: if func not in cls.decorator_function_to_instance_map: UpperCAmelCase_ : Any = LRUCache(lowerCAmelCase_ ) UpperCAmelCase_ : List[Any] = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: UpperCAmelCase_ : str = func(*lowerCAmelCase_ ) cls.decorator_function_to_instance_map[func].put(args[0] , lowerCAmelCase_ ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(lowerCAmelCase_ , "cache_info" , lowerCAmelCase_ ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
95
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
0
"""simple docstring""" import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class __A ( unittest.TestCase ): def lowerCamelCase__ ( self : str ) -> List[Any]: __magic_name__: Dict = logging.get_logger() # the current default level is logging.WARNING __magic_name__: List[Any] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(__snake_case ) def lowerCamelCase__ ( self : Any ) -> str: __magic_name__: str = logging.get_verbosity() __magic_name__: int = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) __magic_name__: int = """Testing 1, 2, 3""" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(__snake_case ) as cl: logger.warning(__snake_case ) self.assertEqual(cl.out , msg + """\n""" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(__snake_case ) as cl: logger.warning(__snake_case ) self.assertEqual(cl.out , """""" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(__snake_case ) as cl: logger.warning(__snake_case ) self.assertEqual(cl.out , msg + """\n""" ) # restore to the original level logging.set_verbosity(__snake_case ) @mockenv(TRANSFORMERS_VERBOSITY="""error""" ) def lowerCamelCase__ ( self : Optional[int] ) -> Any: # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() # this action activates the env var __magic_name__: str = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) __magic_name__: List[str] = os.getenv("""TRANSFORMERS_VERBOSITY""" , __snake_case ) __magic_name__: Any = logging.log_levels[env_level_str] __magic_name__: Optional[Any] = logging.get_verbosity() self.assertEqual( __snake_case , __snake_case , F'TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}' , ) # restore to the original level __magic_name__: Optional[Any] = """""" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="""super-error""" ) def lowerCamelCase__ ( self : str ) -> Optional[int]: # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() __magic_name__: Tuple = logging.logging.getLogger() with CaptureLogger(__snake_case ) as cl: # this action activates the env var logging.get_logger("""transformers.models.bart.tokenization_bart""" ) self.assertIn("""Unknown option TRANSFORMERS_VERBOSITY=super-error""" , cl.out ) # no need to restore as nothing was changed def lowerCamelCase__ ( self : Tuple ) -> int: # testing `logger.warning_advice()` transformers.utils.logging._reset_library_root_logger() __magic_name__: Union[str, Any] = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) __magic_name__: Any = """Testing 1, 2, 3""" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""1""" ): # nothing should be logged as env var disables this method with CaptureLogger(__snake_case ) as cl: logger.warning_advice(__snake_case ) self.assertEqual(cl.out , """""" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""""" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(__snake_case ) as cl: logger.warning_advice(__snake_case ) self.assertEqual(cl.out , msg + """\n""" ) def a ( ) -> Any: disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
96
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
0
import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device 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 ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class lowercase__( UpperCAmelCase ): """simple docstring""" def __init__( self : Any , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str=1_3 , SCREAMING_SNAKE_CASE_ : Tuple=7 , SCREAMING_SNAKE_CASE_ : Optional[Any]=True , SCREAMING_SNAKE_CASE_ : int=True , SCREAMING_SNAKE_CASE_ : str=True , SCREAMING_SNAKE_CASE_ : Dict=True , SCREAMING_SNAKE_CASE_ : Optional[Any]=9_9 , SCREAMING_SNAKE_CASE_ : List[str]=3_2 , SCREAMING_SNAKE_CASE_ : Any=5 , SCREAMING_SNAKE_CASE_ : List[str]=4 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE_ : int="gelu" , SCREAMING_SNAKE_CASE_ : Any=0.1 , SCREAMING_SNAKE_CASE_ : Any=0.1 , SCREAMING_SNAKE_CASE_ : str=5_1_2 , SCREAMING_SNAKE_CASE_ : str=1_6 , SCREAMING_SNAKE_CASE_ : List[Any]=2 , SCREAMING_SNAKE_CASE_ : Tuple=0.02 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=False , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Optional[Any]="None" , SCREAMING_SNAKE_CASE_ : str=3 , SCREAMING_SNAKE_CASE_ : Dict=4 , SCREAMING_SNAKE_CASE_ : Any=None , ) -> List[Any]: lowercase_ = parent lowercase_ = batch_size lowercase_ = seq_length lowercase_ = is_training lowercase_ = use_input_mask lowercase_ = use_token_type_ids lowercase_ = use_labels lowercase_ = vocab_size lowercase_ = hidden_size lowercase_ = num_hidden_layers lowercase_ = num_attention_heads lowercase_ = intermediate_size lowercase_ = hidden_act lowercase_ = hidden_dropout_prob lowercase_ = attention_probs_dropout_prob lowercase_ = max_position_embeddings lowercase_ = type_vocab_size lowercase_ = type_sequence_label_size lowercase_ = initializer_range lowercase_ = num_labels lowercase_ = num_choices lowercase_ = relative_attention lowercase_ = position_biased_input lowercase_ = pos_att_type lowercase_ = scope def _lowercase ( self : Dict ) -> List[Any]: lowercase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase_ = None if self.use_input_mask: lowercase_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) lowercase_ = None if self.use_token_type_ids: lowercase_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase_ = None lowercase_ = None lowercase_ = None if self.use_labels: lowercase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase_ = ids_tensor([self.batch_size] , self.num_choices ) lowercase_ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self : List[str] ) -> Tuple: return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def _lowercase ( self : int , SCREAMING_SNAKE_CASE_ : Any ) -> Tuple: self.parent.assertListEqual(list(result.loss.size() ) , [] ) def _lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Optional[int]: lowercase_ = DebertaVaModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowercase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ )[0] lowercase_ = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ )[0] lowercase_ = model(SCREAMING_SNAKE_CASE_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[Any]: lowercase_ = DebertaVaForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowercase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: lowercase_ = self.num_labels lowercase_ = DebertaVaForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowercase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Any , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Dict: lowercase_ = self.num_labels lowercase_ = DebertaVaForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowercase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Any ) -> str: lowercase_ = DebertaVaForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowercase_ = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict ) -> Union[str, Any]: lowercase_ = DebertaVaForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowercase_ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase_ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase_ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase_ = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase ( self : Tuple ) -> Dict: lowercase_ = self.prepare_config_and_inputs() ( ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ) = config_and_inputs lowercase_ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowercase__( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): """simple docstring""" a :Optional[int] = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) a :List[Any] = ( { 'feature-extraction': DebertaVaModel, 'fill-mask': DebertaVaForMaskedLM, 'question-answering': DebertaVaForQuestionAnswering, 'text-classification': DebertaVaForSequenceClassification, 'token-classification': DebertaVaForTokenClassification, 'zero-shot': DebertaVaForSequenceClassification, } if is_torch_available() else {} ) a :Optional[Any] = True a :Tuple = False a :Optional[int] = False a :Optional[Any] = False a :Union[str, Any] = False def _lowercase ( self : List[str] ) -> Dict: lowercase_ = DebertaVaModelTester(self ) lowercase_ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=3_7 ) def _lowercase ( self : Union[str, Any] ) -> Optional[int]: self.config_tester.run_common_tests() def _lowercase ( self : Any ) -> Union[str, Any]: lowercase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Dict ) -> str: lowercase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Any ) -> Optional[Any]: lowercase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Optional[int] ) -> Any: lowercase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : List[Any] ) -> List[Any]: lowercase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Any ) -> Optional[int]: lowercase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def _lowercase ( self : List[str] ) -> str: for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase_ = DebertaVaModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch @require_sentencepiece @require_tokenizers class lowercase__( unittest.TestCase ): """simple docstring""" @unittest.skip(reason='''Model not available yet''' ) def _lowercase ( self : Optional[Any] ) -> Optional[Any]: pass @slow def _lowercase ( self : str ) -> List[str]: lowercase_ = DebertaVaModel.from_pretrained('''microsoft/deberta-v2-xlarge''' ) lowercase_ = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) lowercase_ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): lowercase_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )[0] # compare the actual values for a slice. lowercase_ = torch.tensor( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) , f'''{output[:, 1:4, 1:4]}''' )
97
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
0
'''simple docstring''' from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def a__ ( lowercase : bool = True, *lowercase : Tuple, **lowercase : Dict ) -> str: """simple docstring""" if not is_tqdm_available(): raise ImportError('''Accelerate\'s `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.''' ) _UpperCamelCase = False if main_process_only: _UpperCamelCase = PartialState().local_process_index == 0 return _tqdm(*lowercase, **lowercase, disable=lowercase )
98
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : 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 _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
0
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __UpperCAmelCase ( __A , __A , unittest.TestCase ): """simple docstring""" _lowerCamelCase = StableDiffusionDiffEditPipeline _lowerCamelCase = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""height""", """width""", """image"""} | {"""image_latents"""} _lowerCamelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"""image"""} | {"""image_latents"""} _lowerCamelCase = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _lowerCamelCase = frozenset([] ) def snake_case_ ( self ): torch.manual_seed(0 ) __a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__A , ) __a = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__A , set_alpha_to_one=__A , ) __a = DDIMInverseScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__A , set_alpha_to_zero=__A , ) torch.manual_seed(0 ) __a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=512 , ) __a = CLIPTextModel(__A ) __a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __a = { """unet""": unet, """scheduler""": scheduler, """inverse_scheduler""": inverse_scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def snake_case_ ( self , __A , __A=0 ): __a = floats_tensor((1, 16, 16) , rng=random.Random(__A ) ).to(__A ) __a = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(__A ) ).to(__A ) if str(__A ).startswith("""mps""" ): __a = torch.manual_seed(__A ) else: __a = torch.Generator(device=__A ).manual_seed(__A ) __a = { """prompt""": """a dog and a newt""", """mask_image""": mask, """image_latents""": latents, """generator""": generator, """num_inference_steps""": 2, """inpaint_strength""": 1.0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def snake_case_ ( self , __A , __A=0 ): __a = floats_tensor((1, 3, 32, 32) , rng=random.Random(__A ) ).to(__A ) __a = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a = Image.fromarray(np.uinta(__A ) ).convert("""RGB""" ) if str(__A ).startswith("""mps""" ): __a = torch.manual_seed(__A ) else: __a = torch.Generator(device=__A ).manual_seed(__A ) __a = { """image""": image, """source_prompt""": """a cat and a frog""", """target_prompt""": """a dog and a newt""", """generator""": generator, """num_inference_steps""": 2, """num_maps_per_mask""": 2, """mask_encode_strength""": 1.0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def snake_case_ ( self , __A , __A=0 ): __a = floats_tensor((1, 3, 32, 32) , rng=random.Random(__A ) ).to(__A ) __a = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a = Image.fromarray(np.uinta(__A ) ).convert("""RGB""" ) if str(__A ).startswith("""mps""" ): __a = torch.manual_seed(__A ) else: __a = torch.Generator(device=__A ).manual_seed(__A ) __a = { """image""": image, """prompt""": """a cat and a frog""", """generator""": generator, """num_inference_steps""": 2, """inpaint_strength""": 1.0, """guidance_scale""": 6.0, """decode_latents""": True, """output_type""": """numpy""", } return inputs def snake_case_ ( self ): if not hasattr(self.pipeline_class , """_optional_components""" ): return __a = self.get_dummy_components() __a = self.pipeline_class(**__A ) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(__A , __A , __A ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) __a = self.get_dummy_inputs(__A ) __a = pipe(**__A )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(__A ) __a = self.pipeline_class.from_pretrained(__A ) pipe_loaded.to(__A ) pipe_loaded.set_progress_bar_config(disable=__A ) for optional_component in pipe._optional_components: self.assertTrue( getattr(__A , __A ) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) __a = self.get_dummy_inputs(__A ) __a = pipe_loaded(**__A )[0] __a = np.abs(output - output_loaded ).max() self.assertLess(__A , 1E-4 ) def snake_case_ ( self ): __a = """cpu""" __a = self.get_dummy_components() __a = self.pipeline_class(**__A ) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) __a = self.get_dummy_mask_inputs(__A ) __a = pipe.generate_mask(**__A ) __a = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) __a = np.array([0] * 9 ) __a = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(__A , 1E-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def snake_case_ ( self ): __a = """cpu""" __a = self.get_dummy_components() __a = self.pipeline_class(**__A ) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) __a = self.get_dummy_inversion_inputs(__A ) __a = pipe.invert(**__A ).images __a = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) __a = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) __a = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(__A , 1E-3 ) def snake_case_ ( self ): super().test_inference_batch_single_identical(expected_max_diff=5E-3 ) def snake_case_ ( self ): __a = """cpu""" __a = self.get_dummy_components() __a = {"""beta_start""": 0.00085, """beta_end""": 0.012, """beta_schedule""": """scaled_linear"""} __a = DPMSolverMultistepScheduler(**__A ) __a = DPMSolverMultistepInverseScheduler(**__A ) __a = self.pipeline_class(**__A ) pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) __a = self.get_dummy_inversion_inputs(__A ) __a = pipe.invert(**__A ).images __a = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) __a = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) __a = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(__A , 1E-3 ) @require_torch_gpu @slow class __UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def snake_case_ ( cls ): __a = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png""" ) __a = raw_image.convert("""RGB""" ).resize((768, 768) ) __a = raw_image def snake_case_ ( self ): __a = torch.manual_seed(0 ) __a = StableDiffusionDiffEditPipeline.from_pretrained( """stabilityai/stable-diffusion-2-1""" , safety_checker=__A , torch_dtype=torch.floataa ) __a = DDIMScheduler.from_config(pipe.scheduler.config ) __a = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=__A ) __a = """a bowl of fruit""" __a = """a bowl of pears""" __a = pipe.generate_mask( image=self.raw_image , source_prompt=__A , target_prompt=__A , generator=__A , ) __a = pipe.invert( prompt=__A , image=self.raw_image , inpaint_strength=0.7 , generator=__A ).latents __a = pipe( prompt=__A , mask_image=__A , image_latents=__A , generator=__A , negative_prompt=__A , inpaint_strength=0.7 , output_type="""numpy""" , ).images[0] __a = ( np.array( load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/diffedit/pears.png""" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1 def snake_case_ ( self ): __a = torch.manual_seed(0 ) __a = StableDiffusionDiffEditPipeline.from_pretrained( """stabilityai/stable-diffusion-2-1""" , safety_checker=__A , torch_dtype=torch.floataa ) __a = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) __a = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=__A ) __a = """a bowl of fruit""" __a = """a bowl of pears""" __a = pipe.generate_mask( image=self.raw_image , source_prompt=__A , target_prompt=__A , generator=__A , ) __a = pipe.invert( prompt=__A , image=self.raw_image , inpaint_strength=0.7 , generator=__A , num_inference_steps=25 , ).latents __a = pipe( prompt=__A , mask_image=__A , image_latents=__A , generator=__A , negative_prompt=__A , inpaint_strength=0.7 , num_inference_steps=25 , output_type="""numpy""" , ).images[0] __a = ( np.array( load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/diffedit/pears.png""" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1
99
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
0
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _A : Union[str, Any] = logging.get_logger(__name__) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , A_ , A_ , A_ , **A_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = feature_size SCREAMING_SNAKE_CASE__ = sampling_rate SCREAMING_SNAKE_CASE__ = padding_value SCREAMING_SNAKE_CASE__ = kwargs.pop('''padding_side''' , '''right''' ) SCREAMING_SNAKE_CASE__ = kwargs.pop('''return_attention_mask''' , A_ ) super().__init__(**A_ ) def lowercase_ ( self , A_ , A_ = True , A_ = None , A_ = False , A_ = None , A_ = None , A_ = None , ): '''simple docstring''' if isinstance(A_ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): SCREAMING_SNAKE_CASE__ = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( '''You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`''' f''' to this method that includes {self.model_input_names[0]}, but you provided''' f''' {list(processed_features.keys() )}''' ) SCREAMING_SNAKE_CASE__ = processed_features[self.model_input_names[0]] SCREAMING_SNAKE_CASE__ = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(A_ ) == 0: if return_attention_mask: SCREAMING_SNAKE_CASE__ = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch SCREAMING_SNAKE_CASE__ = required_input[0] if isinstance(A_ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. SCREAMING_SNAKE_CASE__ = 0 while len(required_input[index] ) == 0: index += 1 if index < len(A_ ): SCREAMING_SNAKE_CASE__ = required_input[index][0] if return_tensors is None: if is_tf_tensor(A_ ): SCREAMING_SNAKE_CASE__ = '''tf''' elif is_torch_tensor(A_ ): SCREAMING_SNAKE_CASE__ = '''pt''' elif isinstance(A_ , (int, float, list, tuple, np.ndarray) ): SCREAMING_SNAKE_CASE__ = '''np''' else: raise ValueError( f'''type of {first_element} unknown: {type(A_ )}. ''' '''Should be one of a python, numpy, pytorch or tensorflow object.''' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): SCREAMING_SNAKE_CASE__ = to_numpy(A_ ) else: SCREAMING_SNAKE_CASE__ = [to_numpy(A_ ) for v in value] # Convert padding_strategy in PaddingStrategy SCREAMING_SNAKE_CASE__ = self._get_padding_strategies(padding=A_ , max_length=A_ ) SCREAMING_SNAKE_CASE__ = processed_features[self.model_input_names[0]] SCREAMING_SNAKE_CASE__ = len(A_ ) if not all(len(A_ ) == batch_size for v in processed_features.values() ): raise ValueError('''Some items in the output dictionary have a different batch size than others.''' ) SCREAMING_SNAKE_CASE__ = [] for i in range(A_ ): SCREAMING_SNAKE_CASE__ = {k: v[i] for k, v in processed_features.items()} # truncation SCREAMING_SNAKE_CASE__ = self._truncate( A_ , max_length=A_ , pad_to_multiple_of=A_ , truncation=A_ , ) truncated_inputs.append(A_ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length SCREAMING_SNAKE_CASE__ = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) SCREAMING_SNAKE_CASE__ = PaddingStrategy.MAX_LENGTH SCREAMING_SNAKE_CASE__ = {} for i in range(A_ ): # padding SCREAMING_SNAKE_CASE__ = self._pad( truncated_inputs[i] , max_length=A_ , padding_strategy=A_ , pad_to_multiple_of=A_ , return_attention_mask=A_ , ) for key, value in outputs.items(): if key not in batch_outputs: SCREAMING_SNAKE_CASE__ = [] if value.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE__ = value.astype(np.floataa ) batch_outputs[key].append(A_ ) return BatchFeature(A_ , tensor_type=A_ ) def lowercase_ ( self , A_ , A_ = None , A_ = PaddingStrategy.DO_NOT_PAD , A_ = None , A_ = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: SCREAMING_SNAKE_CASE__ = len(A_ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): SCREAMING_SNAKE_CASE__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of SCREAMING_SNAKE_CASE__ = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(A_ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: SCREAMING_SNAKE_CASE__ = np.ones(len(A_ ) , dtype=np.intaa ) if needs_to_be_padded: SCREAMING_SNAKE_CASE__ = max_length - len(A_ ) if self.padding_side == "right": if return_attention_mask: SCREAMING_SNAKE_CASE__ = np.pad( processed_features['''attention_mask'''] , (0, difference) ) SCREAMING_SNAKE_CASE__ = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) SCREAMING_SNAKE_CASE__ = np.pad( A_ , A_ , '''constant''' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: SCREAMING_SNAKE_CASE__ = np.pad( processed_features['''attention_mask'''] , (difference, 0) ) SCREAMING_SNAKE_CASE__ = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) SCREAMING_SNAKE_CASE__ = np.pad( A_ , A_ , '''constant''' , constant_values=self.padding_value ) else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return processed_features def lowercase_ ( self , A_ , A_ = None , A_ = None , A_ = None , ): '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('''When setting ``truncation=True``, make sure that ``max_length`` is defined.''' ) SCREAMING_SNAKE_CASE__ = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): SCREAMING_SNAKE_CASE__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of SCREAMING_SNAKE_CASE__ = len(A_ ) > max_length if needs_to_be_truncated: SCREAMING_SNAKE_CASE__ = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: SCREAMING_SNAKE_CASE__ = processed_features['''attention_mask'''][:max_length] return processed_features def lowercase_ ( self , A_=False , A_=None ): '''simple docstring''' if padding is not False: if padding is True: SCREAMING_SNAKE_CASE__ = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(A_ , A_ ): SCREAMING_SNAKE_CASE__ = PaddingStrategy(A_ ) elif isinstance(A_ , A_ ): SCREAMING_SNAKE_CASE__ = padding else: SCREAMING_SNAKE_CASE__ = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'''When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined''' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( '''Asking to pad but the feature_extractor does not have a padding value. Please select a value to use''' ''' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.''' ) return padding_strategy
100
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "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 a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
0
def a__ ( A__ ): return 1_0 - x * x def a__ ( A__, A__ ): # Bolzano theory in order to find if there is a root between a and b if equation(A__ ) * equation(A__ ) >= 0: raise ValueError('Wrong space!' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = a while (b - a) >= 0.01: # Find middle point SCREAMING_SNAKE_CASE_ : Tuple = (a + b) / 2 # Check if middle point is root if equation(A__ ) == 0.0: break # Decide the side to repeat the steps if equation(A__ ) * equation(A__ ) < 0: SCREAMING_SNAKE_CASE_ : Tuple = c else: SCREAMING_SNAKE_CASE_ : Tuple = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
101
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
0
"""simple docstring""" from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class lowercase__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , _A , _A = None , _A = None , _A = True , _A = None , _A = False , _A = None , _A = True , _A = "arrow" , **_A , ): '''simple docstring''' super().__init__( split=_A , features=_A , cache_dir=_A , keep_in_memory=_A , streaming=_A , **_A , ) UpperCamelCase : Optional[Any] = load_from_cache_file UpperCamelCase : List[str] = file_format UpperCamelCase : Optional[Any] = Spark( df=_A , features=_A , cache_dir=_A , working_dir=_A , **_A , ) def _a ( self ): '''simple docstring''' if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) UpperCamelCase : Dict = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=_A , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
102
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
0
"""simple docstring""" import argparse import os import re import packaging.version snake_case = '''examples/''' snake_case = { '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(r'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(r'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), r'''\1version="VERSION",'''), '''doc''': (re.compile(r'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } snake_case = { '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } snake_case = '''README.md''' def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> List[str]: with open(lowerCAmelCase_ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: _snake_case = f.read() _snake_case , _snake_case = REPLACE_PATTERNS[pattern] _snake_case = replace.replace('''VERSION''' , lowerCAmelCase_ ) _snake_case = re_pattern.sub(lowerCAmelCase_ , lowerCAmelCase_ ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(lowerCAmelCase_ ) def snake_case ( lowerCAmelCase_ ) -> int: for folder, directories, fnames in os.walk(lowerCAmelCase_ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) , lowerCAmelCase_ , pattern='''examples''' ) def snake_case ( lowerCAmelCase_ , lowerCAmelCase_=False ) -> Optional[int]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if not patch: update_version_in_examples(lowerCAmelCase_ ) def snake_case ( ) -> int: _snake_case = '''🤗 Transformers currently provides the following architectures''' _snake_case = '''1. Want to contribute a new model?''' with open(lowerCAmelCase_ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: _snake_case = f.readlines() # Find the start of the list. _snake_case = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 _snake_case = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): _snake_case = lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' , '''https://huggingface.co/docs/transformers/model_doc''' , ) index += 1 with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lowerCAmelCase_ ) def snake_case ( ) -> Optional[int]: with open(REPLACE_FILES['''init'''] , '''r''' ) as f: _snake_case = f.read() _snake_case = REPLACE_PATTERNS['''init'''][0].search(lowerCAmelCase_ ).groups()[0] return packaging.version.parse(lowerCAmelCase_ ) def snake_case ( lowerCAmelCase_=False ) -> Union[str, Any]: _snake_case = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: _snake_case = default_version.base_version elif patch: _snake_case = f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: _snake_case = f"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. _snake_case = input(f"""Which version are you releasing? [{default_version}]""" ) if len(lowerCAmelCase_ ) == 0: _snake_case = default_version print(f"""Updating version to {version}.""" ) global_version_update(lowerCAmelCase_ , patch=lowerCAmelCase_ ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def snake_case ( ) -> Dict: _snake_case = get_version() _snake_case = f"""{current_version.major}.{current_version.minor + 1}.0.dev0""" _snake_case = current_version.base_version # Check with the user we got that right. _snake_case = input(f"""Which version are we developing now? [{dev_version}]""" ) if len(lowerCAmelCase_ ) == 0: _snake_case = dev_version print(f"""Updating version to {version}.""" ) global_version_update(lowerCAmelCase_ ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": snake_case = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') snake_case = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
103
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 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 (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [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 _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , 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( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = 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 _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 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 _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 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""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
0
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _lowerCamelCase ( UpperCAmelCase_ : str, UpperCAmelCase_ : Dict=0.999, UpperCAmelCase_ : Tuple="cosine", ) -> List[str]: """simple docstring""" if alpha_transform_type == "cosine": def alpha_bar_fn(UpperCAmelCase_ : Tuple ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(UpperCAmelCase_ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) A__ = [] for i in range(UpperCAmelCase_ ): A__ = i / num_diffusion_timesteps A__ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(UpperCAmelCase_ ) / alpha_bar_fn(UpperCAmelCase_ ), UpperCAmelCase_ ) ) return torch.tensor(UpperCAmelCase_, dtype=torch.floataa ) class UpperCamelCase__ ( _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" A__ : Optional[Any] = [e.name for e in KarrasDiffusionSchedulers] A__ : str = 2 @register_to_config def __init__( self , SCREAMING_SNAKE_CASE__ = 1000 , SCREAMING_SNAKE_CASE__ = 0.0_0_0_8_5 , SCREAMING_SNAKE_CASE__ = 0.0_1_2 , SCREAMING_SNAKE_CASE__ = "linear" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "epsilon" , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = 1.0 , SCREAMING_SNAKE_CASE__ = "linspace" , SCREAMING_SNAKE_CASE__ = 0 , ) -> Optional[int]: if trained_betas is not None: A__ = torch.tensor(SCREAMING_SNAKE_CASE__ , dtype=torch.floataa ) elif beta_schedule == "linear": A__ = torch.linspace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A__ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , SCREAMING_SNAKE_CASE__ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A__ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE__ , alpha_transform_type="cosine" ) elif beta_schedule == "exp": A__ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE__ , alpha_transform_type="exp" ) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" ) A__ = 1.0 - self.betas A__ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ = use_karras_sigmas def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ) -> Optional[int]: if schedule_timesteps is None: A__ = self.timesteps A__ = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: A__ = 1 if len(SCREAMING_SNAKE_CASE__ ) > 1 else 0 else: A__ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE__ ) else timestep A__ = self._index_counter[timestep_int] return indices[pos].item() @property def snake_case__ ( self ) -> Any: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) -> torch.FloatTensor: A__ = self.index_for_timestep(SCREAMING_SNAKE_CASE__ ) A__ = self.sigmas[step_index] A__ = sample / ((sigma**2 + 1) ** 0.5) return sample def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ) -> Dict: A__ = num_inference_steps A__ = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": A__ = np.linspace(0 , num_train_timesteps - 1 , SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ )[::-1].copy() elif self.config.timestep_spacing == "leading": A__ = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A__ = (np.arange(0 , SCREAMING_SNAKE_CASE__ ) * step_ratio).round()[::-1].copy().astype(SCREAMING_SNAKE_CASE__ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": A__ = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A__ = (np.arange(SCREAMING_SNAKE_CASE__ , 0 , -step_ratio )).round().copy().astype(SCREAMING_SNAKE_CASE__ ) timesteps -= 1 else: raise ValueError( f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) A__ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) A__ = np.log(SCREAMING_SNAKE_CASE__ ) A__ = np.interp(SCREAMING_SNAKE_CASE__ , np.arange(0 , len(SCREAMING_SNAKE_CASE__ ) ) , SCREAMING_SNAKE_CASE__ ) if self.config.use_karras_sigmas: A__ = self._convert_to_karras(in_sigmas=SCREAMING_SNAKE_CASE__ , num_inference_steps=self.num_inference_steps ) A__ = np.array([self._sigma_to_t(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for sigma in sigmas] ) A__ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) A__ = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(device=SCREAMING_SNAKE_CASE__ ) A__ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) A__ = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) A__ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): # mps does not support float64 A__ = timesteps.to(SCREAMING_SNAKE_CASE__ , dtype=torch.floataa ) else: A__ = timesteps.to(device=SCREAMING_SNAKE_CASE__ ) # empty dt and derivative A__ = None A__ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter A__ = defaultdict(SCREAMING_SNAKE_CASE__ ) def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[str]: # get log sigma A__ = np.log(SCREAMING_SNAKE_CASE__ ) # get distribution A__ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range A__ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) A__ = low_idx + 1 A__ = log_sigmas[low_idx] A__ = log_sigmas[high_idx] # interpolate sigmas A__ = (low - log_sigma) / (low - high) A__ = np.clip(SCREAMING_SNAKE_CASE__ , 0 , 1 ) # transform interpolation to time range A__ = (1 - w) * low_idx + w * high_idx A__ = t.reshape(sigma.shape ) return t def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> torch.FloatTensor: A__ = in_sigmas[-1].item() A__ = in_sigmas[0].item() A__ = 7.0 # 7.0 is the value used in the paper A__ = np.linspace(0 , 1 , SCREAMING_SNAKE_CASE__ ) A__ = sigma_min ** (1 / rho) A__ = sigma_max ** (1 / rho) A__ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def snake_case__ ( self ) -> Optional[Any]: return self.dt is None def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = True , ) -> Union[SchedulerOutput, Tuple]: A__ = self.index_for_timestep(SCREAMING_SNAKE_CASE__ ) # advance index counter by 1 A__ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE__ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: A__ = self.sigmas[step_index] A__ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method A__ = self.sigmas[step_index - 1] A__ = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API A__ = 0 A__ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": A__ = sigma_hat if self.state_in_first_order else sigma_next A__ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": A__ = sigma_hat if self.state_in_first_order else sigma_next A__ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": A__ = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: A__ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order A__ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep A__ = sigma_next - sigma_hat # store for 2nd order step A__ = derivative A__ = dt A__ = sample else: # 2. 2nd order / Heun's method A__ = (sample - pred_original_sample) / sigma_next A__ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample A__ = self.dt A__ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" A__ = None A__ = None A__ = None A__ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE__ ) def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples A__ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(SCREAMING_SNAKE_CASE__ ): # mps does not support float64 A__ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) A__ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: A__ = self.timesteps.to(original_samples.device ) A__ = timesteps.to(original_samples.device ) A__ = [self.index_for_timestep(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for t in timesteps] A__ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): A__ = sigma.unsqueeze(-1 ) A__ = original_samples + noise * sigma return noisy_samples def __len__( self ) -> Tuple: return self.config.num_train_timesteps
104
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
0
import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase__ : Tuple = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_sentencepiece_available(): import sentencepiece as sp UpperCamelCase__ : int = 5 UpperCamelCase__ : Tuple = 10 @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( lowerCamelCase_ , unittest.TestCase ): __a : List[str] = SpeechaTextTokenizer __a : Dict = False __a : str = True def snake_case ( self ): super().setUp() SCREAMING_SNAKE_CASE_ : Optional[Any] = sp.SentencePieceProcessor() spm_model.Load(snake_case__ ) SCREAMING_SNAKE_CASE_ : str = ['<s>', '<pad>', '</s>', '<unk>'] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(snake_case__ ) )] SCREAMING_SNAKE_CASE_ : Dict = dict(zip(snake_case__ ,range(len(snake_case__ ) ) ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = Path(self.tmpdirname ) save_json(snake_case__ ,save_dir / VOCAB_FILES_NAMES['vocab_file'] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(snake_case__ ,save_dir / VOCAB_FILES_NAMES['spm_file'] ) SCREAMING_SNAKE_CASE_ : Optional[int] = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = '<pad>' SCREAMING_SNAKE_CASE_ : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case__ ) ,snake_case__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case__ ) ,snake_case__ ) def snake_case ( self ): SCREAMING_SNAKE_CASE_ : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'<s>' ) self.assertEqual(vocab_keys[1] ,'<pad>' ) self.assertEqual(vocab_keys[-1] ,'j' ) self.assertEqual(len(snake_case__ ) ,1001 ) def snake_case ( self ): self.assertEqual(self.get_tokenizer().vocab_size ,1001 ) def snake_case ( self ): SCREAMING_SNAKE_CASE_ : Tuple = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE_ : List[str] = tokenizer.tokenize('This is a test' ) self.assertListEqual(snake_case__ ,['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(snake_case__ ) ,[289, 50, 14, 174, 386] ,) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( snake_case__ ,[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', 'é', '.'] ,) SCREAMING_SNAKE_CASE_ : int = tokenizer.convert_tokens_to_ids(snake_case__ ) self.assertListEqual(snake_case__ ,[12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8] ) SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.convert_ids_to_tokens(snake_case__ ) self.assertListEqual( snake_case__ ,[SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] ,) @slow def snake_case ( self ): # fmt: off SCREAMING_SNAKE_CASE_ : Dict = {'input_ids': [[3791, 797, 31, 11, 64, 797, 31, 2429, 433, 12, 1176, 12, 20, 786, 915, 142, 2413, 240, 37, 3238, 797, 31, 11, 35, 93, 915, 142, 2413, 240, 37, 5540, 567, 1276, 93, 37, 610, 40, 62, 455, 657, 1042, 123, 780, 177, 37, 309, 241, 1298, 514, 20, 292, 2737, 114, 2469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3388, 511, 459, 4, 3555, 40, 321, 302, 705, 4, 3388, 511, 583, 326, 5, 5, 5, 62, 3310, 560, 177, 2680, 217, 1508, 32, 31, 853, 418, 64, 583, 511, 1605, 62, 35, 93, 560, 177, 2680, 217, 1508, 1521, 64, 583, 511, 519, 62, 20, 1515, 764, 20, 149, 261, 5625, 7972, 20, 5540, 567, 1276, 93, 3925, 1675, 11, 15, 802, 7972, 576, 217, 1508, 11, 35, 93, 1253, 2441, 15, 289, 652, 31, 416, 321, 3842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2681, 1153, 3434, 20, 5540, 37, 567, 126, 1253, 2441, 3376, 449, 210, 431, 1563, 177, 767, 5540, 11, 1203, 472, 11, 2953, 685, 285, 364, 706, 1153, 20, 6799, 20, 2869, 20, 4464, 126, 40, 2429, 20, 1040, 866, 2664, 418, 20, 318, 20, 1726, 186, 20, 265, 522, 35, 93, 2191, 4634, 20, 1040, 12, 6799, 15, 228, 2356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2575, 2666, 684, 1582, 1176, 12, 627, 149, 619, 20, 4902, 563, 11, 20, 149, 261, 3420, 2356, 174, 142, 4714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=snake_case__ ,model_name='facebook/s2t-small-mustc-en-de-st' ,revision='a14f04cf0776c02f62a8cb800cf7909e15ea23ad' ,) @require_sentencepiece class lowerCAmelCase_ ( unittest.TestCase ): __a : Tuple = "valhalla/s2t_mustc_multilinguial_medium" __a : List[Any] = "C'est trop cool" __a : Dict = "Esto es genial" @classmethod def snake_case ( cls ): SCREAMING_SNAKE_CASE_ : SpeechaTextTokenizer = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def snake_case ( self ): self.assertEqual(self.tokenizer.lang_code_to_id['pt'] ,4 ) self.assertEqual(self.tokenizer.lang_code_to_id['ru'] ,6 ) self.assertEqual(self.tokenizer.lang_code_to_id['it'] ,9 ) self.assertEqual(self.tokenizer.lang_code_to_id['de'] ,11 ) def snake_case ( self ): self.assertEqual(self.tokenizer.vocab_size ,10000 ) def snake_case ( self ): self.assertIn(snake_case__ ,self.tokenizer.all_special_ids ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ES_CODE, 4, 1601, 47, 7647, 2] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.tokenizer.decode(snake_case__ ,skip_special_tokens=snake_case__ ) SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer.decode(generated_ids[1:] ,skip_special_tokens=snake_case__ ) self.assertEqual(snake_case__ ,snake_case__ ) self.assertNotIn(self.tokenizer.eos_token ,snake_case__ ) def snake_case ( self ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = 'fr' SCREAMING_SNAKE_CASE_ : List[str] = self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0] ,snake_case__ ) self.assertEqual(encoded[-1] ,self.tokenizer.eos_token_id ) def snake_case ( self ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = 'fr' self.assertListEqual(self.tokenizer.prefix_tokens ,[FR_CODE] ) SCREAMING_SNAKE_CASE_ : Any = 'es' self.assertListEqual(self.tokenizer.prefix_tokens ,[ES_CODE] )
105
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
0
__snake_case :Any =256 # Modulus to hash a string __snake_case :Optional[int] =1000003 def lowerCamelCase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> bool: '''simple docstring''' A = len(lowerCAmelCase__ ) A = len(lowerCAmelCase__ ) if p_len > t_len: return False A = 0 A = 0 A = 1 # Calculating the hash of pattern and substring of text for i in range(lowerCAmelCase__ ): A = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus A = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue A = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash A = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def lowerCamelCase_ ( ) -> None: '''simple docstring''' A = 'abc1abc12' A = 'alskfjaldsabc1abc1abc12k23adsfabcabc' A = 'alskfjaldsk23adsfabcabc' assert rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) and not rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) # Test 2) A = 'ABABX' A = 'ABABZABABYABABX' assert rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) # Test 3) A = 'AAAB' A = 'ABAAAAAB' assert rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) # Test 4) A = 'abcdabcy' A = 'abcxabcdabxabcdabcdabcy' assert rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) # Test 5) A = 'Lü' A = 'Lüsai' assert rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) A = 'Lue' assert not rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) print('Success.' ) if __name__ == "__main__": test_rabin_karp()
106
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : 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=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCAmelCase : List[str] = { '''configuration_data2vec_audio''': ['''DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecAudioConfig'''], '''configuration_data2vec_text''': [ '''DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecTextConfig''', '''Data2VecTextOnnxConfig''', ], '''configuration_data2vec_vision''': [ '''DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecVisionConfig''', '''Data2VecVisionOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : List[str] = [ '''DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecAudioForAudioFrameClassification''', '''Data2VecAudioForCTC''', '''Data2VecAudioForSequenceClassification''', '''Data2VecAudioForXVector''', '''Data2VecAudioModel''', '''Data2VecAudioPreTrainedModel''', ] _UpperCAmelCase : int = [ '''DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecTextForCausalLM''', '''Data2VecTextForMaskedLM''', '''Data2VecTextForMultipleChoice''', '''Data2VecTextForQuestionAnswering''', '''Data2VecTextForSequenceClassification''', '''Data2VecTextForTokenClassification''', '''Data2VecTextModel''', '''Data2VecTextPreTrainedModel''', ] _UpperCAmelCase : str = [ '''DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecVisionForImageClassification''', '''Data2VecVisionForMaskedImageModeling''', '''Data2VecVisionForSemanticSegmentation''', '''Data2VecVisionModel''', '''Data2VecVisionPreTrainedModel''', ] if is_tf_available(): _UpperCAmelCase : Optional[int] = [ '''TFData2VecVisionForImageClassification''', '''TFData2VecVisionForSemanticSegmentation''', '''TFData2VecVisionModel''', '''TFData2VecVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys _UpperCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
107
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
0
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup __a: Dict = '''https://www.indeed.co.in/jobs?q=mobile+app+development&l=''' def _SCREAMING_SNAKE_CASE ( __snake_case = "mumbai" ) -> Generator[tuple[str, str], None, None]: _UpperCAmelCase = BeautifulSoup(requests.get(url + location ).content , """html.parser""" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("""div""" , attrs={"""data-tn-component""": """organicJob"""} ): _UpperCAmelCase = job.find("""a""" , attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() _UpperCAmelCase = job.find("""span""" , {"""class""": """company"""} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('''Bangalore'''), 1): print(F"Job {i:>2} is {job[0]} at {job[1]}")
108
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[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(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a = { "configuration_wav2vec2": ["WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Wav2Vec2Config"], "feature_extraction_wav2vec2": ["Wav2Vec2FeatureExtractor"], "processing_wav2vec2": ["Wav2Vec2Processor"], "tokenization_wav2vec2": ["Wav2Vec2CTCTokenizer", "Wav2Vec2Tokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = [ "WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Wav2Vec2ForAudioFrameClassification", "Wav2Vec2ForCTC", "Wav2Vec2ForMaskedLM", "Wav2Vec2ForPreTraining", "Wav2Vec2ForSequenceClassification", "Wav2Vec2ForXVector", "Wav2Vec2Model", "Wav2Vec2PreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = [ "TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "TFWav2Vec2ForCTC", "TFWav2Vec2Model", "TFWav2Vec2PreTrainedModel", "TFWav2Vec2ForSequenceClassification", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = [ "FlaxWav2Vec2ForCTC", "FlaxWav2Vec2ForPreTraining", "FlaxWav2Vec2Model", "FlaxWav2Vec2PreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys a = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
109
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a__ : Optional[int] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys a__ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
165
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
0
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ ( UpperCamelCase_ ): """simple docstring""" def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE="last" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , ) -> Dict: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_input_lengths __UpperCamelCase = use_token_type_ids __UpperCamelCase = use_labels __UpperCamelCase = gelu_activation __UpperCamelCase = sinusoidal_embeddings __UpperCamelCase = causal __UpperCamelCase = asm __UpperCamelCase = n_langs __UpperCamelCase = vocab_size __UpperCamelCase = n_special __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = type_vocab_size __UpperCamelCase = type_sequence_label_size __UpperCamelCase = initializer_range __UpperCamelCase = num_labels __UpperCamelCase = num_choices __UpperCamelCase = summary_type __UpperCamelCase = use_proj __UpperCamelCase = scope def __lowercase( self ) -> Optional[int]: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase = None if self.use_input_lengths: __UpperCamelCase = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __UpperCamelCase = None if self.use_token_type_ids: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase = ids_tensor([self.batch_size] , 2 ).float() __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def __lowercase( self ) -> List[Any]: return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> Tuple: __UpperCamelCase = FlaubertModel(config=_a ) model.to(_a ) model.eval() __UpperCamelCase = model(_a , lengths=_a , langs=_a ) __UpperCamelCase = model(_a , langs=_a ) __UpperCamelCase = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> Tuple: __UpperCamelCase = FlaubertWithLMHeadModel(_a ) model.to(_a ) model.eval() __UpperCamelCase = 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 __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> Optional[int]: __UpperCamelCase = FlaubertForQuestionAnsweringSimple(_a ) model.to(_a ) model.eval() __UpperCamelCase = model(_a ) __UpperCamelCase = model(_a , start_positions=_a , end_positions=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> Tuple: __UpperCamelCase = FlaubertForQuestionAnswering(_a ) model.to(_a ) model.eval() __UpperCamelCase = model(_a ) __UpperCamelCase = model( _a , start_positions=_a , end_positions=_a , cls_index=_a , is_impossible=_a , p_mask=_a , ) __UpperCamelCase = model( _a , start_positions=_a , end_positions=_a , cls_index=_a , is_impossible=_a , ) (__UpperCamelCase ) = result_with_labels.to_tuple() __UpperCamelCase = model(_a , start_positions=_a , end_positions=_a ) (__UpperCamelCase ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> Optional[int]: __UpperCamelCase = FlaubertForSequenceClassification(_a ) model.to(_a ) model.eval() __UpperCamelCase = model(_a ) __UpperCamelCase = model(_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> Optional[int]: __UpperCamelCase = self.num_labels __UpperCamelCase = FlaubertForTokenClassification(_a ) model.to(_a ) model.eval() __UpperCamelCase = model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> Optional[int]: __UpperCamelCase = self.num_choices __UpperCamelCase = FlaubertForMultipleChoice(config=_a ) model.to(_a ) model.eval() __UpperCamelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCamelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCamelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCamelCase = model( _a , attention_mask=_a , token_type_ids=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowercase( self ) -> Any: __UpperCamelCase = self.prepare_config_and_inputs() ( __UpperCamelCase ) = config_and_inputs __UpperCamelCase = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) UpperCAmelCase__ = ( { """feature-extraction""": FlaubertModel, """fill-mask""": FlaubertWithLMHeadModel, """question-answering""": FlaubertForQuestionAnsweringSimple, """text-classification""": FlaubertForSequenceClassification, """token-classification""": FlaubertForTokenClassification, """zero-shot""": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> List[Any]: __UpperCamelCase = super()._prepare_for_class(_a , _a , return_labels=_a ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": __UpperCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_a ) __UpperCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_a ) return inputs_dict def __lowercase( self ) -> str: __UpperCamelCase = FlaubertModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=_a , emb_dim=37 ) def __lowercase( self ) -> Tuple: self.config_tester.run_common_tests() def __lowercase( self ) -> Optional[int]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*_a ) def __lowercase( self ) -> Tuple: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*_a ) def __lowercase( self ) -> Optional[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*_a ) def __lowercase( self ) -> Optional[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*_a ) def __lowercase( self ) -> Dict: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*_a ) def __lowercase( self ) -> List[str]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*_a ) def __lowercase( self ) -> List[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*_a ) @slow def __lowercase( self ) -> Dict: for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase = FlaubertModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @slow @require_torch_gpu def __lowercase( self ) -> int: __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return __UpperCamelCase = True __UpperCamelCase = model_class(config=_a ) __UpperCamelCase = self._prepare_for_class(_a , _a ) __UpperCamelCase = torch.jit.trace( _a , (inputs_dict['input_ids'].to('cpu' ), inputs_dict['attention_mask'].to('cpu' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(_a , os.path.join(_a , 'traced_model.pt' ) ) __UpperCamelCase = torch.jit.load(os.path.join(_a , 'traced_model.pt' ) , map_location=_a ) loaded(inputs_dict['input_ids'].to(_a ) , inputs_dict['attention_mask'].to(_a ) ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def __lowercase( self ) -> Tuple: __UpperCamelCase = FlaubertModel.from_pretrained('flaubert/flaubert_base_cased' ) __UpperCamelCase = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) with torch.no_grad(): __UpperCamelCase = model(_a )[0] __UpperCamelCase = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _a ) __UpperCamelCase = torch.tensor( [[[-2.6_2_5_1, -1.4_2_9_8, -0.0_2_2_7], [-2.8_5_1_0, -1.6_3_8_7, 0.2_2_5_8], [-2.8_1_1_4, -1.1_8_3_2, -0.3_0_6_6]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1e-4 ) )
383
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
0
import re def a(lowercase__ ): '''simple docstring''' if len(re.findall('[ATCG]' , __lowerCAmelCase ) ) != len(__lowerCAmelCase ): raise ValueError('Invalid Strand' ) return dna.translate(dna.maketrans('ATCG' , 'TAGC' ) ) if __name__ == "__main__": import doctest doctest.testmod()
187
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
0
"""simple docstring""" import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class __A ( UpperCamelCase_ ): UpperCAmelCase__ = """Wav2Vec2FeatureExtractor""" UpperCAmelCase__ = """AutoTokenizer""" def __init__( self : int , __snake_case : Tuple , __snake_case : List[Any] ) -> Tuple: super().__init__(_a , _a ) __magic_name__: int = self.feature_extractor __magic_name__: Union[str, Any] = False @classmethod def lowerCamelCase__ ( cls : List[str] , __snake_case : List[Any] , **__snake_case : Optional[int] ) -> List[str]: try: return super().from_pretrained(_a , **_a ) except OSError: warnings.warn( F'Loading a tokenizer inside {cls.__name__} from a config that does not' """ include a `tokenizer_class` attribute is deprecated and will be """ """removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`""" """ attribute to either your `config.json` or `tokenizer_config.json` """ """file to suppress this warning: """ , _a , ) __magic_name__: List[str] = WavaVecaFeatureExtractor.from_pretrained(_a , **_a ) __magic_name__: Tuple = WavaVecaCTCTokenizer.from_pretrained(_a , **_a ) return cls(feature_extractor=_a , tokenizer=_a ) def __call__( self : Tuple , *__snake_case : List[Any] , **__snake_case : Dict ) -> List[Any]: if self._in_target_context_manager: return self.current_processor(*_a , **_a ) if "raw_speech" in kwargs: warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" ) __magic_name__: Union[str, Any] = kwargs.pop("""raw_speech""" ) else: __magic_name__: Any = kwargs.pop("""audio""" , _a ) __magic_name__: Dict = kwargs.pop("""sampling_rate""" , _a ) __magic_name__: Tuple = kwargs.pop("""text""" , _a ) if len(_a ) > 0: __magic_name__: Optional[Any] = args[0] __magic_name__: Union[str, Any] = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: __magic_name__: List[Any] = self.feature_extractor(_a , *_a , sampling_rate=_a , **_a ) if text is not None: __magic_name__: List[Any] = self.tokenizer(_a , **_a ) if text is None: return inputs elif audio is None: return encodings else: __magic_name__: Optional[Any] = encodings["""input_ids"""] return inputs def lowerCamelCase__ ( self : List[str] , *__snake_case : int , **__snake_case : Optional[Any] ) -> Any: if self._in_target_context_manager: return self.current_processor.pad(*_a , **_a ) __magic_name__: Optional[Any] = kwargs.pop("""input_features""" , _a ) __magic_name__: int = kwargs.pop("""labels""" , _a ) if len(_a ) > 0: __magic_name__: Union[str, Any] = args[0] __magic_name__: List[Any] = args[1:] if input_features is not None: __magic_name__: Optional[int] = self.feature_extractor.pad(_a , *_a , **_a ) if labels is not None: __magic_name__: Tuple = self.tokenizer.pad(_a , **_a ) if labels is None: return input_features elif input_features is None: return labels else: __magic_name__: int = labels["""input_ids"""] return input_features def lowerCamelCase__ ( self : Optional[int] , *__snake_case : Tuple , **__snake_case : List[str] ) -> Tuple: return self.tokenizer.batch_decode(*_a , **_a ) def lowerCamelCase__ ( self : Tuple , *__snake_case : List[Any] , **__snake_case : Union[str, Any] ) -> Tuple: return self.tokenizer.decode(*_a , **_a ) @contextmanager def lowerCamelCase__ ( self : List[Any] ) -> Union[str, Any]: warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your audio inputs, or in a separate call.""" ) __magic_name__: List[str] = True __magic_name__: List[str] = self.tokenizer yield __magic_name__: str = self.feature_extractor __magic_name__: Tuple = False
96
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
0
"""simple docstring""" def __UpperCamelCase ( SCREAMING_SNAKE_CASE ) -> list: """simple docstring""" __snake_case = int(__lowerCAmelCase ) if n_element < 1: __snake_case = ValueError("a should be a positive number" ) raise my_error __snake_case = [1] __snake_case = (0, 0, 0) __snake_case = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _SCREAMING_SNAKE_CASE = input("""Enter the last number (nth term) of the Hamming Number Series: """) print("""Formula of Hamming Number Series => 2^i * 3^j * 5^k""") _SCREAMING_SNAKE_CASE = hamming(int(n)) print("""-----------------------------------------------------""") print(F"""The list with nth numbers is: {hamming_numbers}""") print("""-----------------------------------------------------""")
163
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
0
'''simple docstring''' from manim import * class __lowercase ( UpperCamelCase_ ): def UpperCamelCase__ ( self ) -> str: __a = Rectangle(height=0.5 , width=0.5 ) __a = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __a = [mem.copy() for i in range(6 )] __a = [mem.copy() for i in range(6 )] __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = VGroup(_a , _a ).arrange(_a , buff=0 ) __a = Text('CPU' , font_size=24 ) __a = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_a ) __a = [mem.copy() for i in range(4 )] __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = Text('GPU' , font_size=24 ) __a = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) gpu.move_to([-1, -1, 0] ) self.add(_a ) __a = [mem.copy() for i in range(6 )] __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = Text('Model' , font_size=24 ) __a = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) model.move_to([3, -1.0, 0] ) self.add(_a ) __a = [] for i, rect in enumerate(_a ): rect.set_stroke(_a ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) __a = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_a , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_a ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=_a , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=_a , buff=0.0 ) self.add(_a ) cpu_targs.append(_a ) __a = [mem.copy() for i in range(6 )] __a = VGroup(*_a ).arrange(_a , buff=0 ) __a = Text('Loaded Checkpoint' , font_size=24 ) __a = Group(_a , _a ).arrange(_a , aligned_edge=_a , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) __a = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __a = MarkupText( f"<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_a , _a ) __a = MarkupText( f"<span fgcolor=\'{BLUE}\'>●</span> Checkpoint" , font_size=18 , ) blue_text.next_to(_a , DOWN * 2.4 , aligned_edge=key_text.get_left() ) __a = MarkupText( f"Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>." , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(_a ) , Write(_a ) ) self.play(Write(_a , run_time=1 ) , Create(_a , run_time=1 ) ) __a = [] __a = [] for i, rect in enumerate(_a ): __a = fill.copy().set_fill(_a , opacity=0.7 ) target.move_to(_a ) first_animations.append(GrowFromCenter(_a , run_time=1 ) ) __a = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(_a , run_time=1.5 ) ) self.play(*_a ) self.play(*_a ) self.wait()
539
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
0
import os from datetime import datetime as dt from github import Github lowerCamelCase : List[str] =[ "good first issue", "good second issue", "good difficult issue", "enhancement", "new pipeline/model", "new scheduler", "wip", ] def SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: UpperCamelCase__ : Union[str, Any] = Github(os.environ["GITHUB_TOKEN"] ) UpperCamelCase__ : Optional[int] = g.get_repo("huggingface/diffusers" ) UpperCamelCase__ : List[str] = repo.get_issues(state="open" ) for issue in open_issues: UpperCamelCase__ : Optional[int] = sorted(issue.get_comments() , key=lambda __lowerCAmelCase : i.created_at , reverse=__lowerCAmelCase ) UpperCamelCase__ : int = comments[0] if len(__lowerCAmelCase ) > 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()
228
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : int = logging.get_logger(__name__) lowerCamelCase : List[str] = { "asapp/sew-d-tiny-100k": "https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json", # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class A( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase = """sew-d""" def __init__( self : Union[str, Any] , A_ : Any=32 , A_ : Any=768 , A_ : Tuple=12 , A_ : str=12 , A_ : Any=3072 , A_ : Any=2 , A_ : List[str]=512 , A_ : Tuple=256 , A_ : List[Any]=True , A_ : List[Any]=True , A_ : Optional[int]=("p2c", "c2p") , A_ : Optional[int]="layer_norm" , A_ : List[str]="gelu_python" , A_ : List[Any]=0.1 , A_ : Optional[Any]=0.1 , A_ : int=0.1 , A_ : Tuple=0.0 , A_ : Dict=0.1 , A_ : List[Any]=0.02 , A_ : str=1E-7 , A_ : str=1E-5 , A_ : Optional[Any]="group" , A_ : List[Any]="gelu" , A_ : str=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , A_ : Union[str, Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , A_ : Tuple=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , A_ : List[str]=False , A_ : Dict=128 , A_ : List[str]=16 , A_ : Optional[Any]=True , A_ : Union[str, Any]=0.05 , A_ : Tuple=10 , A_ : Optional[Any]=2 , A_ : int=0.0 , A_ : Optional[Any]=10 , A_ : Dict=0 , A_ : List[str]="mean" , A_ : Optional[Any]=False , A_ : int=False , A_ : str=256 , A_ : Optional[Any]=0 , A_ : int=1 , A_ : Union[str, Any]=2 , **A_ : List[str] , ) -> Optional[Any]: """simple docstring""" super().__init__(**_a , pad_token_id=_a , bos_token_id=_a , eos_token_id=_a ) lowerCamelCase_ = hidden_size lowerCamelCase_ = feat_extract_norm lowerCamelCase_ = feat_extract_activation lowerCamelCase_ = list(_a ) lowerCamelCase_ = list(_a ) lowerCamelCase_ = list(_a ) lowerCamelCase_ = conv_bias lowerCamelCase_ = num_conv_pos_embeddings lowerCamelCase_ = num_conv_pos_embedding_groups lowerCamelCase_ = len(self.conv_dim ) lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = intermediate_size lowerCamelCase_ = squeeze_factor lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = position_buckets lowerCamelCase_ = share_att_key lowerCamelCase_ = relative_attention lowerCamelCase_ = norm_rel_ebd lowerCamelCase_ = list(_a ) lowerCamelCase_ = hidden_act lowerCamelCase_ = num_attention_heads lowerCamelCase_ = hidden_dropout lowerCamelCase_ = attention_dropout lowerCamelCase_ = activation_dropout lowerCamelCase_ = feat_proj_dropout lowerCamelCase_ = final_dropout lowerCamelCase_ = layer_norm_eps lowerCamelCase_ = feature_layer_norm_eps lowerCamelCase_ = initializer_range lowerCamelCase_ = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' f"""but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)""" f"""= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowerCamelCase_ = apply_spec_augment lowerCamelCase_ = mask_time_prob lowerCamelCase_ = mask_time_length lowerCamelCase_ = mask_time_min_masks lowerCamelCase_ = mask_feature_prob lowerCamelCase_ = mask_feature_length lowerCamelCase_ = mask_feature_min_masks # ctc loss lowerCamelCase_ = ctc_loss_reduction lowerCamelCase_ = ctc_zero_infinity # sequence classification lowerCamelCase_ = use_weighted_layer_sum lowerCamelCase_ = classifier_proj_size @property def a__ ( self : Optional[int] ) -> Any: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
70
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
0
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler UpperCamelCase__ = 16 UpperCamelCase__ = 32 def lowerCamelCase ( _snake_case ,_snake_case = 16 ,_snake_case = "bert-base-cased" ): UpperCAmelCase__ : Tuple = AutoTokenizer.from_pretrained(__lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = load_dataset('glue' ,'mrpc' ) def tokenize_function(_snake_case ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase__ : int = tokenizer(examples['sentence1'] ,examples['sentence2'] ,truncation=__lowerCAmelCase ,max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase__ : Optional[int] = datasets.map( __lowerCAmelCase ,batched=__lowerCAmelCase ,remove_columns=['idx', 'sentence1', 'sentence2'] ,load_from_cache_file=__lowerCAmelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase__ : str = tokenized_datasets.rename_column('label' ,'labels' ) def collate_fn(_snake_case ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__lowerCAmelCase ,padding='max_length' ,max_length=128 ,return_tensors='pt' ) return tokenizer.pad(__lowerCAmelCase ,padding='longest' ,return_tensors='pt' ) # Instantiate dataloaders. UpperCAmelCase__ : Tuple = DataLoader( tokenized_datasets['train'] ,shuffle=__lowerCAmelCase ,collate_fn=__lowerCAmelCase ,batch_size=__lowerCAmelCase ) UpperCAmelCase__ : Any = DataLoader( tokenized_datasets['validation'] ,shuffle=__lowerCAmelCase ,collate_fn=__lowerCAmelCase ,batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader def lowerCamelCase ( _snake_case ,_snake_case ,_snake_case ,_snake_case ): model.eval() UpperCAmelCase__ : List[str] = 0 for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase__ : List[str] = model(**__lowerCAmelCase ) UpperCAmelCase__ : Any = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCAmelCase__ : List[str] = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__lowerCAmelCase ) - 1: UpperCAmelCase__ : Tuple = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCAmelCase__ : Optional[Any] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__lowerCAmelCase ,references=__lowerCAmelCase ,) UpperCAmelCase__ : Union[str, Any] = metric.compute() return eval_metric["accuracy"] def lowerCamelCase ( _snake_case ,_snake_case ): # Initialize accelerator UpperCAmelCase__ : Any = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase__ : Optional[int] = config["""lr"""] UpperCAmelCase__ : str = int(config['num_epochs'] ) UpperCAmelCase__ : int = int(config['seed'] ) UpperCAmelCase__ : Optional[Any] = int(config['batch_size'] ) UpperCAmelCase__ : Any = args.model_name_or_path set_seed(__lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = get_dataloaders(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase__ : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(__lowerCAmelCase ,return_dict=__lowerCAmelCase ) # Instantiate optimizer UpperCAmelCase__ : Union[str, Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCAmelCase__ : Any = optimizer_cls(params=model.parameters() ,lr=__lowerCAmelCase ) if accelerator.state.deepspeed_plugin is not None: UpperCAmelCase__ : List[str] = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCAmelCase__ : Any = 1 UpperCAmelCase__ : List[Any] = (len(__lowerCAmelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCAmelCase__ : Union[str, Any] = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase ,num_warmup_steps=0 ,num_training_steps=__lowerCAmelCase ,) else: UpperCAmelCase__ : Optional[Any] = DummyScheduler(__lowerCAmelCase ,total_num_steps=__lowerCAmelCase ,warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCAmelCase__ : Dict = accelerator.prepare( __lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase__ : Optional[int] = 0 # We also need to keep track of the stating epoch so files are named properly UpperCAmelCase__ : List[str] = 0 UpperCAmelCase__ : Union[str, Any] = evaluate.load('glue' ,'mrpc' ) UpperCAmelCase__ : Dict = num_epochs if args.partial_train_epoch is not None: UpperCAmelCase__ : List[str] = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) UpperCAmelCase__ : List[Any] = args.resume_from_checkpoint.split('epoch_' )[1] UpperCAmelCase__ : Tuple = """""" for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break UpperCAmelCase__ : Optional[int] = int(__lowerCAmelCase ) + 1 UpperCAmelCase__ : Union[str, Any] = evaluation_loop(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) accelerator.print('resumed checkpoint performance:' ,__lowerCAmelCase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:' ,lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:' ,optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir ,F'''state_{starting_epoch-1}.json''' ) ,'r' ) as f: UpperCAmelCase__ : str = json.load(__lowerCAmelCase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model UpperCAmelCase__ : Tuple = {} for epoch in range(__lowerCAmelCase ,__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): UpperCAmelCase__ : Optional[int] = model(**__lowerCAmelCase ) UpperCAmelCase__ : Tuple = outputs.loss UpperCAmelCase__ : Optional[Any] = loss / gradient_accumulation_steps accelerator.backward(__lowerCAmelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 UpperCAmelCase__ : Any = F'''epoch_{epoch}''' UpperCAmelCase__ : Optional[int] = os.path.join(args.output_dir ,__lowerCAmelCase ) accelerator.save_state(__lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = evaluation_loop(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) UpperCAmelCase__ : int = accuracy UpperCAmelCase__ : Union[str, Any] = lr_scheduler.get_lr()[0] UpperCAmelCase__ : List[str] = optimizer.param_groups[0]["""lr"""] UpperCAmelCase__ : Optional[Any] = epoch UpperCAmelCase__ : Optional[Any] = overall_step accelerator.print(F'''epoch {epoch}:''' ,__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir ,F'''state_{epoch}.json''' ) ,'w' ) as f: json.dump(__lowerCAmelCase ,__lowerCAmelCase ) def lowerCamelCase ( ): UpperCAmelCase__ : Dict = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' ,type=__lowerCAmelCase ,default='bert-base-cased' ,help='Path to pretrained model or model identifier from huggingface.co/models.' ,required=__lowerCAmelCase ,) parser.add_argument( '--output_dir' ,type=__lowerCAmelCase ,default='.' ,help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' ,) parser.add_argument( '--resume_from_checkpoint' ,type=__lowerCAmelCase ,default=__lowerCAmelCase ,help='If the training should continue from a checkpoint folder.' ,) parser.add_argument( '--partial_train_epoch' ,type=__lowerCAmelCase ,default=__lowerCAmelCase ,help='If passed, the training will stop after this number of epochs.' ,) parser.add_argument( '--num_epochs' ,type=__lowerCAmelCase ,default=2 ,help='Number of train epochs.' ,) UpperCAmelCase__ : List[Any] = parser.parse_args() UpperCAmelCase__ : List[Any] = {"""lr""": 2e-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase ,__lowerCAmelCase ) if __name__ == "__main__": main()
110
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
0
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): """simple docstring""" a : UNetaDModel a : KarrasVeScheduler def __init__( self , snake_case__ , snake_case__ ): """simple docstring""" super().__init__() self.register_modules(unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , snake_case__ = 1 , snake_case__ = 50 , snake_case__ = None , snake_case__ = "pil" , snake_case__ = True , **snake_case__ , ): """simple docstring""" lowerCAmelCase : str = self.unet.config.sample_size lowerCAmelCase : Optional[int] = (batch_size, 3, img_size, img_size) lowerCAmelCase : Any = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) lowerCAmelCase : List[Any] = randn_tensor(_a , generator=_a , device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper lowerCAmelCase : List[Any] = self.scheduler.schedule[t] lowerCAmelCase : Optional[Any] = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat lowerCAmelCase : List[str] = self.scheduler.add_noise_to_input(_a , _a , generator=_a ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. lowerCAmelCase : str = (sigma_hat / 2) * model((sample_hat + 1) / 2 , sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev lowerCAmelCase : Tuple = self.scheduler.step(_a , _a , _a , _a ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. lowerCAmelCase : str = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 , sigma_prev / 2 ).sample lowerCAmelCase : int = self.scheduler.step_correct( _a , _a , _a , _a , step_output.prev_sample , step_output["derivative"] , ) lowerCAmelCase : str = step_output.prev_sample lowerCAmelCase : List[Any] = (sample / 2 + 0.5).clamp(0 , 1 ) lowerCAmelCase : str = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCAmelCase : Optional[Any] = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
645
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
0
import numpy as np def lowerCamelCase_ ( lowerCAmelCase__ : Dict ) -> np.ndarray: '''simple docstring''' return 1 / (1 + np.exp(-vector )) def lowerCamelCase_ ( lowerCAmelCase__ : List[str] ) -> np.ndarray: '''simple docstring''' return vector * sigmoid(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
106
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : 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 _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
0
from random import shuffle import tensorflow as tf from numpy import array def snake_case (UpperCamelCase : Any , UpperCamelCase : Union[str, Any] ): '''simple docstring''' lowerCamelCase__ = int(__lowerCAmelCase ) assert noofclusters < len(__lowerCAmelCase ) # Find out the dimensionality lowerCamelCase__ = len(vectors[0] ) # Will help select random centroids from among the available vectors lowerCamelCase__ = list(range(len(__lowerCAmelCase ) ) ) shuffle(__lowerCAmelCase ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. lowerCamelCase__ = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION lowerCamelCase__ = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points lowerCamelCase__ = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(__lowerCAmelCase ) ] ##These nodes will assign the centroid Variables the appropriate ##values lowerCamelCase__ = tf.placeholder("""float64""" , [dim] ) lowerCamelCase__ = [] for centroid in centroids: cent_assigns.append(tf.assign(__lowerCAmelCase , __lowerCAmelCase ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) lowerCamelCase__ = [tf.Variable(0 ) for i in range(len(__lowerCAmelCase ) )] ##These nodes will assign an assignment Variable the appropriate ##value lowerCamelCase__ = tf.placeholder("""int32""" ) lowerCamelCase__ = [] for assignment in assignments: cluster_assigns.append(tf.assign(__lowerCAmelCase , __lowerCAmelCase ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input lowerCamelCase__ = tf.placeholder("""float""" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors lowerCamelCase__ = tf.reduce_mean(__lowerCAmelCase , 0 ) ##Node for computing Euclidean distances # Placeholders for input lowerCamelCase__ = tf.placeholder("""float""" , [dim] ) lowerCamelCase__ = tf.placeholder("""float""" , [dim] ) lowerCamelCase__ = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(__lowerCAmelCase , __lowerCAmelCase ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input lowerCamelCase__ = tf.placeholder("""float""" , [noofclusters] ) lowerCamelCase__ = tf.argmin(__lowerCAmelCase , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. lowerCamelCase__ = tf.initialize_all_variables() # Initialize all variables sess.run(__lowerCAmelCase ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. lowerCamelCase__ = 100 for _ in range(__lowerCAmelCase ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(__lowerCAmelCase ) ): lowerCamelCase__ = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. lowerCamelCase__ = [ sess.run(__lowerCAmelCase , feed_dict={va: vect, va: sess.run(__lowerCAmelCase )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input lowerCamelCase__ = sess.run( __lowerCAmelCase , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(__lowerCAmelCase ): # Collect all the vectors assigned to this cluster lowerCamelCase__ = [ vectors[i] for i in range(len(__lowerCAmelCase ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location lowerCamelCase__ = sess.run( __lowerCAmelCase , feed_dict={mean_input: array(__lowerCAmelCase )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments lowerCamelCase__ = sess.run(__lowerCAmelCase ) lowerCamelCase__ = sess.run(__lowerCAmelCase ) return centroids, assignments
165
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
0
from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class lowerCAmelCase_ ( UpperCamelCase_ ): """simple docstring""" def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: super().__init__() self.register_modules(unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , **_SCREAMING_SNAKE_CASE , ) -> Union[ImagePipelineOutput, Tuple]: __UpperCamelCase = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=_a , ) __UpperCamelCase = image.to(self.device ) # set step values self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output __UpperCamelCase = self.unet(_a , _a ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 __UpperCamelCase = self.scheduler.step(_a , _a , _a ).prev_sample __UpperCamelCase = (image / 2 + 0.5).clamp(0 , 1 ) __UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __UpperCamelCase = self.numpy_to_pil(_a ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=_a ), "This is a local test"
383
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "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 a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
0
import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging A = logging.get_logger(__name__) A = { "facebook/encodec_24khz": "https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json", "facebook/encodec_48khz": "https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json", } class SCREAMING_SNAKE_CASE ( UpperCamelCase_ ): """simple docstring""" __A = """encodec""" def __init__( self , __UpperCamelCase=[1.5, 3.0, 6.0, 12.0, 24.0] , __UpperCamelCase=2_40_00 , __UpperCamelCase=1 , __UpperCamelCase=False , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=1_28 , __UpperCamelCase=32 , __UpperCamelCase=1 , __UpperCamelCase=[8, 5, 4, 2] , __UpperCamelCase="weight_norm" , __UpperCamelCase=7 , __UpperCamelCase=7 , __UpperCamelCase=3 , __UpperCamelCase=2 , __UpperCamelCase=True , __UpperCamelCase="reflect" , __UpperCamelCase=2 , __UpperCamelCase=2 , __UpperCamelCase=1.0 , __UpperCamelCase=10_24 , __UpperCamelCase=None , __UpperCamelCase=True , **__UpperCamelCase , ): """simple docstring""" snake_case_ = target_bandwidths snake_case_ = sampling_rate snake_case_ = audio_channels snake_case_ = normalize snake_case_ = chunk_length_s snake_case_ = overlap snake_case_ = hidden_size snake_case_ = num_filters snake_case_ = num_residual_layers snake_case_ = upsampling_ratios snake_case_ = norm_type snake_case_ = kernel_size snake_case_ = last_kernel_size snake_case_ = residual_kernel_size snake_case_ = dilation_growth_rate snake_case_ = use_causal_conv snake_case_ = pad_mode snake_case_ = compress snake_case_ = num_lstm_layers snake_case_ = trim_right_ratio snake_case_ = codebook_size snake_case_ = codebook_dim if codebook_dim is not None else hidden_size snake_case_ = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( f"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}""" ) super().__init__(**_a ) @property def __lowerCAmelCase ( self ): """simple docstring""" if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def __lowerCAmelCase ( self ): """simple docstring""" if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def __lowerCAmelCase ( self ): """simple docstring""" return int(10_00 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
187
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
0
"""simple docstring""" import re import string import numpy as np import datasets __lowerCamelCase = "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n" __lowerCamelCase = "\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results[\"exact_match\"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 33.3\n\n" __lowerCamelCase = "\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def lowerCamelCase__ ( self : Optional[Any] ) -> Any: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , reference_urls=[] , ) def lowerCamelCase__ ( self : Tuple , __snake_case : str , __snake_case : Optional[int] , __snake_case : List[Any]=None , __snake_case : Dict=False , __snake_case : Optional[int]=False , __snake_case : Optional[Any]=False , ) -> Tuple: if regexes_to_ignore is not None: for s in regexes_to_ignore: __magic_name__: Optional[int] = np.array([re.sub(_a , """""" , _a ) for x in predictions] ) __magic_name__: Optional[Any] = np.array([re.sub(_a , """""" , _a ) for x in references] ) else: __magic_name__: str = np.asarray(_a ) __magic_name__: str = np.asarray(_a ) if ignore_case: __magic_name__: Optional[int] = np.char.lower(_a ) __magic_name__: Optional[int] = np.char.lower(_a ) if ignore_punctuation: __magic_name__: Optional[int] = string.punctuation.maketrans("""""" , """""" , string.punctuation ) __magic_name__: Any = np.char.translate(_a , table=_a ) __magic_name__: Optional[Any] = np.char.translate(_a , table=_a ) if ignore_numbers: __magic_name__: List[Any] = string.digits.maketrans("""""" , """""" , string.digits ) __magic_name__: Union[str, Any] = np.char.translate(_a , table=_a ) __magic_name__: List[str] = np.char.translate(_a , table=_a ) __magic_name__: Any = predictions == references return {"exact_match": np.mean(_a ) * 1_0_0}
96
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
0
"""simple docstring""" from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __magic_name__ ( UpperCamelCase_ ): _SCREAMING_SNAKE_CASE : List[str] = """dandelin/vilt-b32-finetuned-vqa""" _SCREAMING_SNAKE_CASE : Union[str, Any] = ( """This is a tool that answers a question about an image. It takes an input named `image` which should be the """ """image containing the information, as well as a `question` which should be the question in English. It """ """returns a text that is the answer to the question.""" ) _SCREAMING_SNAKE_CASE : Dict = """image_qa""" _SCREAMING_SNAKE_CASE : str = AutoProcessor _SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForVisualQuestionAnswering _SCREAMING_SNAKE_CASE : List[Any] = ["""image""", """text"""] _SCREAMING_SNAKE_CASE : List[str] = ["""text"""] def __init__( self : List[Any] , *snake_case_ : Union[str, Any] , **snake_case_ : Dict ): requires_backends(self , ["vision"] ) super().__init__(*_a , **_a ) def lowerCAmelCase ( self : str , snake_case_ : Dict , snake_case_ : Optional[Any] ): return self.pre_processor(_a , _a , return_tensors="pt" ) def lowerCAmelCase ( self : int , snake_case_ : List[str] ): with torch.no_grad(): return self.model(**_a ).logits def lowerCAmelCase ( self : Optional[Any] , snake_case_ : Optional[int] ): __snake_case = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
163
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 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 (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [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 _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , 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( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = 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 _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 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 _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 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""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
0
'''simple docstring''' from functools import lru_cache @lru_cache def SCREAMING_SNAKE_CASE ( a_ : int ): if num < 0: raise ValueError('Number should not be negative.' ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
539
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
0
from manim import * class __a ( UpperCamelCase_ ): def __lowercase ( self : Tuple ): '''simple docstring''' UpperCamelCase__ : List[str] = Rectangle(height=0.5 , width=0.5 ) UpperCamelCase__ : int = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) UpperCamelCase__ : Any = [mem.copy() for i in range(6 )] UpperCamelCase__ : List[str] = [mem.copy() for i in range(6 )] UpperCamelCase__ : Tuple = VGroup(*_a ).arrange(_a , buff=0 ) UpperCamelCase__ : Dict = VGroup(*_a ).arrange(_a , buff=0 ) UpperCamelCase__ : Optional[Any] = VGroup(_a , _a ).arrange(_a , buff=0 ) UpperCamelCase__ : Optional[Any] = Text("CPU" , font_size=24 ) UpperCamelCase__ : Any = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_a ) UpperCamelCase__ : Optional[int] = [mem.copy() for i in range(1 )] UpperCamelCase__ : Any = VGroup(*_a ).arrange(_a , buff=0 ) UpperCamelCase__ : List[Any] = Text("GPU" , font_size=24 ) UpperCamelCase__ : List[str] = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) gpu.align_to(_a , _a ) gpu.set_x(gpu.get_x() - 1 ) self.add(_a ) UpperCamelCase__ : Optional[Any] = [mem.copy() for i in range(6 )] UpperCamelCase__ : Any = VGroup(*_a ).arrange(_a , buff=0 ) UpperCamelCase__ : List[str] = Text("Model" , font_size=24 ) UpperCamelCase__ : List[Any] = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) model.move_to([3, -1.0, 0] ) self.play( Create(_a , run_time=1 ) , Create(_a , run_time=1 ) , Create(_a , run_time=1 ) , ) UpperCamelCase__ : str = MarkupText( F'First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.' , font_size=24 , ) UpperCamelCase__ : List[Any] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) UpperCamelCase__ : Optional[int] = MarkupText( F'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(_a , run_time=2.5 ) , Write(_a ) , Write(_a ) ) self.add(_a ) UpperCamelCase__ : Tuple = [] UpperCamelCase__ : Optional[Any] = [] UpperCamelCase__ : List[Any] = [] for i, rect in enumerate(_a ): UpperCamelCase__ : Tuple = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0.0 ).set_fill(_a , opacity=0.7 ) cpu_target.move_to(_a ) cpu_target.generate_target() UpperCamelCase__ : Any = 0.4_6 / 4 UpperCamelCase__ : Union[str, Any] = 0.4_6 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.0_2 , direction=_a ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=_a , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=_a , buff=0.0 ) cpu_targs.append(_a ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(_a ) ) second_animations.append(MoveToTarget(_a , run_time=1.5 ) ) self.play(*_a ) self.play(*_a ) self.wait()
228
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
0
import pprint import requests lowerCamelCase : List[str] = "https://zenquotes.io/api" def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' return requests.get(API_ENDPOINT_URL + '/today' ).json() def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' return requests.get(API_ENDPOINT_URL + '/random' ).json() if __name__ == "__main__": lowerCamelCase : Dict = random_quotes() pprint.pprint(response)
70
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : 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=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
0
"""simple docstring""" import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def lowerCamelCase ( _snake_case=32 ,_snake_case=10 ,_snake_case=100 ,_snake_case=1026 ,_snake_case=True ,_snake_case="data/tokenized_stories_train_wikitext103.jbl" ,_snake_case="igf_context_pairs.jbl" ,): set_seed(3 ) # generate train_data and objective_set UpperCAmelCase__ : List[str] = generate_datasets( __lowerCAmelCase ,__lowerCAmelCase ,number=__lowerCAmelCase ,min_len=1026 ,trim=__lowerCAmelCase ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? UpperCAmelCase__ : Any = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu' ) # load pretrained model UpperCAmelCase__ : int = load_gpta('gpt2' ).to(__lowerCAmelCase ) print('computing perplexity on objective set' ) UpperCAmelCase__ : List[Any] = compute_perplexity(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ).item() print('perplexity on objective set:' ,__lowerCAmelCase ) # collect igf pairs and save to file demo.jbl collect_objective_set(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def lowerCamelCase ( _snake_case ,_snake_case=15 ,_snake_case=128 ,_snake_case=100 ,_snake_case="igf_model.pt" ,): set_seed(42 ) # Load pre-trained model UpperCAmelCase__ : Dict = GPTaLMHeadModel.from_pretrained('gpt2' ) # Initialize secondary learner to use embedding weights of model UpperCAmelCase__ : Optional[int] = SecondaryLearner(__lowerCAmelCase ) # Train secondary learner UpperCAmelCase__ : Optional[Any] = train_secondary_learner( __lowerCAmelCase ,__lowerCAmelCase ,max_epochs=__lowerCAmelCase ,batch_size=__lowerCAmelCase ,eval_freq=100 ,igf_model_path=__lowerCAmelCase ,) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def lowerCamelCase ( _snake_case ,_snake_case ,_snake_case ,_snake_case=32 ,_snake_case=1000 ,_snake_case=16 ,_snake_case=1.0 ,_snake_case=recopy_gpta ,_snake_case=None ,_snake_case=10 ,_snake_case="gpt2_finetuned.pt" ,): UpperCAmelCase__ : Optional[int] = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu' ) UpperCAmelCase__ : str = RandomSampler(__lowerCAmelCase ) UpperCAmelCase__ : List[str] = DataLoader(__lowerCAmelCase ,sampler=__lowerCAmelCase ) UpperCAmelCase__ : int = max_steps // (len(__lowerCAmelCase )) + 1 UpperCAmelCase__ : List[Any] = 0 UpperCAmelCase__ : List[str] = torch.zeros((1, context_len) ,dtype=torch.long ,device=__lowerCAmelCase ) UpperCAmelCase__ : int = recopy_model(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) model.train() if secondary_learner is not None: secondary_learner.to(__lowerCAmelCase ) secondary_learner.eval() UpperCAmelCase__ : List[Any] = [] UpperCAmelCase__ : Union[str, Any] = 0 UpperCAmelCase__ : List[Any] = [] UpperCAmelCase__ : int = [] # Compute the performance of the transformer model at the beginning UpperCAmelCase__ : List[str] = compute_perplexity(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) test_perps.append(__lowerCAmelCase ) print('Test perplexity, step' ,__lowerCAmelCase ,':' ,__lowerCAmelCase ) for epoch in range(int(__lowerCAmelCase ) ): for step, example in enumerate(__lowerCAmelCase ): torch.cuda.empty_cache() UpperCAmelCase__ : List[Any] = random.randint(0 ,example.size(2 ) - context_len - 1 ) UpperCAmelCase__ : Union[str, Any] = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() UpperCAmelCase__ : Union[str, Any] = model(__lowerCAmelCase ,labels=__lowerCAmelCase ) UpperCAmelCase__ : Any = True if secondary_learner is not None: UpperCAmelCase__ : str = secondary_learner.forward( torch.tensor(__lowerCAmelCase ,dtype=torch.long ,device=__lowerCAmelCase ).unsqueeze(0 ) )[0].item() observed_qs.append(float(__lowerCAmelCase ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: UpperCAmelCase__ : str = -1 if predicted_q < threshold: UpperCAmelCase__ : Any = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) UpperCAmelCase__ : Optional[int] = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() UpperCAmelCase__ : List[Any] = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() ,3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: UpperCAmelCase__ : Any = compute_perplexity(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) test_perps.append(__lowerCAmelCase ) print('Test perplexity, step' ,__lowerCAmelCase ,':' ,__lowerCAmelCase ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() ,__lowerCAmelCase ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def lowerCamelCase ( ): UpperCAmelCase__ : Any = argparse.ArgumentParser(description='Fine-tune a transformer model with IGF on a language modeling task' ) # Required parameters parser.add_argument( '--data_dir' ,default=__lowerCAmelCase ,type=__lowerCAmelCase ,required=__lowerCAmelCase ,help='The input data dir. Should contain data files for WikiText.' ,) parser.add_argument( '--model_name_or_path' ,default=__lowerCAmelCase ,type=__lowerCAmelCase ,required=__lowerCAmelCase ,help='Path to pretrained model or model identifier from huggingface.co/models' ,) parser.add_argument( '--data_file' ,type=__lowerCAmelCase ,default=__lowerCAmelCase ,help=( 'A jbl file containing tokenized data which can be split as objective dataset, ' 'train_dataset and test_dataset.' ) ,) parser.add_argument( '--igf_data_file' ,type=__lowerCAmelCase ,default=__lowerCAmelCase ,help='A jbl file containing the context and information gain pairs to train secondary learner.' ,) parser.add_argument( '--output_dir' ,default=__lowerCAmelCase ,type=__lowerCAmelCase ,required=__lowerCAmelCase ,help='The output directory where the final fine-tuned model is stored.' ,) parser.add_argument( '--tokenizer_name' ,default=__lowerCAmelCase ,type=__lowerCAmelCase ,help='Pretrained tokenizer name or path if not the same as model_name' ,) parser.add_argument('--seed' ,type=__lowerCAmelCase ,default=__lowerCAmelCase ,help='A seed for reproducible training.' ) parser.add_argument( '--context_len' ,default=32 ,type=__lowerCAmelCase ,help=( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) ,) parser.add_argument( '--size_objective_set' ,default=100 ,type=__lowerCAmelCase ,help='number of articles that are long enough to be used as our objective set' ,) parser.add_argument( '--eval_freq' ,default=100 ,type=__lowerCAmelCase ,help='secondary model evaluation is triggered at eval_freq' ) parser.add_argument('--max_steps' ,default=1000 ,type=__lowerCAmelCase ,help='To calculate training epochs' ) parser.add_argument( '--secondary_learner_batch_size' ,default=128 ,type=__lowerCAmelCase ,help='batch size of training data for secondary learner' ,) parser.add_argument( '--batch_size' ,default=16 ,type=__lowerCAmelCase ,help='batch size of training data of language model(gpt2) ' ) parser.add_argument( '--eval_interval' ,default=10 ,type=__lowerCAmelCase ,help=( 'decay the selectivity of our secondary learner filter from' '1 standard deviation above average to 1 below average after 10 batches' ) ,) parser.add_argument( '--number' ,default=100 ,type=__lowerCAmelCase ,help='The number of examples split to be used as objective_set/test_data' ) parser.add_argument( '--min_len' ,default=1026 ,type=__lowerCAmelCase ,help='The minimum length of the article to be used as objective set' ) parser.add_argument( '--secondary_learner_max_epochs' ,default=15 ,type=__lowerCAmelCase ,help='number of epochs to train secondary learner' ) parser.add_argument('--trim' ,default=__lowerCAmelCase ,type=__lowerCAmelCase ,help='truncate the example if it exceeds context length' ) parser.add_argument( '--threshold' ,default=1.0 ,type=__lowerCAmelCase ,help=( 'The threshold value used by secondary learner to filter the train_data and allow only' ' informative data as input to the model' ) ,) parser.add_argument('--finetuned_model_name' ,default='gpt2_finetuned.pt' ,type=__lowerCAmelCase ,help='finetuned_model_name' ) parser.add_argument( '--recopy_model' ,default=__lowerCAmelCase ,type=__lowerCAmelCase ,help='Reset the model to the original pretrained GPT-2 weights after each iteration' ,) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 ,max_steps=10 ,size_objective_set=100 ,min_len=1026 ,trim=__lowerCAmelCase ,data_file='data/tokenized_stories_train_wikitext103.jbl' ,igf_data_file='igf_context_pairs.jbl' ,) # Load train data for secondary learner UpperCAmelCase__ : int = joblib.load('data/IGF_values.jbl' ) # Train secondary learner UpperCAmelCase__ : Dict = training_secondary_learner( __lowerCAmelCase ,secondary_learner_max_epochs=15 ,secondary_learner_batch_size=128 ,eval_freq=100 ,igf_model_path='igf_model.pt' ,) # load pretrained gpt2 model UpperCAmelCase__ : Union[str, Any] = GPTaLMHeadModel.from_pretrained('gpt2' ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model UpperCAmelCase__ : List[Any] = generate_datasets( context_len=32 ,file='data/tokenized_stories_train_wikitext103.jbl' ,number=100 ,min_len=1026 ,trim=__lowerCAmelCase ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( __lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,context_len=32 ,max_steps=1000 ,batch_size=16 ,threshold=1.0 ,recopy_model=__lowerCAmelCase ,secondary_learner=__lowerCAmelCase ,eval_interval=10 ,finetuned_model_name='gpt2_finetuned.pt' ,) if __name__ == "__main__": main()
110
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
0
"""simple docstring""" lowerCAmelCase__ = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
645
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[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(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
0
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCamelCase_ ): A_ : Union[str, Any] = (DDPMParallelScheduler,) def __UpperCamelCase ( self : Union[str, Any] , **__UpperCamelCase : Optional[int] ) -> str: A = { """num_train_timesteps""": 1_000, """beta_start""": 0.0_0_0_1, """beta_end""": 0.0_2, """beta_schedule""": """linear""", """variance_type""": """fixed_small""", """clip_sample""": True, } config.update(**_a ) return config def __UpperCamelCase ( self : Optional[Any] ) -> Union[str, Any]: for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_a ) def __UpperCamelCase ( self : Union[str, Any] ) -> List[str]: for beta_start, beta_end in zip([0.0_0_0_1, 0.0_0_1, 0.0_1, 0.1] , [0.0_0_2, 0.0_2, 0.2, 2] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def __UpperCamelCase ( self : List[Any] ) -> int: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_a ) def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_a ) def __UpperCamelCase ( self : Optional[Any] ) -> List[str]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def __UpperCamelCase ( self : Dict ) -> Optional[int]: self.check_over_configs(thresholding=_a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_a , prediction_type=_a , sample_max_value=_a , ) def __UpperCamelCase ( self : int ) -> List[Any]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def __UpperCamelCase ( self : Any ) -> Optional[int]: for t in [0, 500, 999]: self.check_over_forward(time_step=_a ) def __UpperCamelCase ( self : Union[str, Any] ) -> Any: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_0_9_7_9 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.0_2 ) ) < 1e-5 def __UpperCamelCase ( self : Tuple ) -> Optional[Any]: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**_a ) A = len(_a ) A = self.dummy_model() A = self.dummy_sample_deter A = self.dummy_sample_deter + 0.1 A = self.dummy_sample_deter - 0.1 A = samplea.shape[0] A = torch.stack([samplea, samplea, samplea] , dim=0 ) A = torch.arange(_a )[0:3, None].repeat(1 , _a ) A = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) A = scheduler.batch_step_no_noise(_a , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) A = torch.sum(torch.abs(_a ) ) A = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 1_153.1_833 ) < 1e-2 assert abs(result_mean.item() - 0.5_0_0_5 ) < 1e-3 def __UpperCamelCase ( self : int ) -> int: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**_a ) A = len(_a ) A = self.dummy_model() A = self.dummy_sample_deter A = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual A = model(_a , _a ) # 2. predict previous mean of sample x_t-1 A = scheduler.step(_a , _a , _a , generator=_a ).prev_sample A = pred_prev_sample A = torch.sum(torch.abs(_a ) ) A = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 2_5_8.9_6_0_6 ) < 1e-2 assert abs(result_mean.item() - 0.3_3_7_2 ) < 1e-3 def __UpperCamelCase ( self : Optional[Any] ) -> Any: A = self.scheduler_classes[0] A = self.get_scheduler_config(prediction_type='v_prediction' ) A = scheduler_class(**_a ) A = len(_a ) A = self.dummy_model() A = self.dummy_sample_deter A = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual A = model(_a , _a ) # 2. predict previous mean of sample x_t-1 A = scheduler.step(_a , _a , _a , generator=_a ).prev_sample A = pred_prev_sample A = torch.sum(torch.abs(_a ) ) A = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 2_0_2.0_2_9_6 ) < 1e-2 assert abs(result_mean.item() - 0.2_6_3_1 ) < 1e-3 def __UpperCamelCase ( self : Union[str, Any] ) -> Dict: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**_a ) A = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=_a ) A = scheduler.timesteps for i, timestep in enumerate(_a ): if i == len(_a ) - 1: A = -1 else: A = timesteps[i + 1] A = scheduler.previous_timestep(_a ) A = prev_t.item() self.assertEqual(_a , _a ) def __UpperCamelCase ( self : str ) -> str: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**_a ) A = [100, 87, 50, 51, 0] with self.assertRaises(_a , msg='`custom_timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=_a ) def __UpperCamelCase ( self : Any ) -> Dict: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**_a ) A = [100, 87, 50, 1, 0] A = len(_a ) with self.assertRaises(_a , msg='Can only pass one of `num_inference_steps` or `custom_timesteps`.' ): scheduler.set_timesteps(num_inference_steps=_a , timesteps=_a ) def __UpperCamelCase ( self : int ) -> Union[str, Any]: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**_a ) A = [scheduler.config.num_train_timesteps] with self.assertRaises( _a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=_a )
106
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
0
from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
165
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
0
from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def _a ( ) -> Optional[int]: """simple docstring""" __UpperCamelCase = ArgumentParser('Accelerate CLI tool' , usage='accelerate <command> [<args>]' , allow_abbrev=__lowerCAmelCase ) __UpperCamelCase = parser.add_subparsers(help='accelerate command helpers' ) # Register commands get_config_parser(subparsers=__lowerCAmelCase ) env_command_parser(subparsers=__lowerCAmelCase ) launch_command_parser(subparsers=__lowerCAmelCase ) tpu_command_parser(subparsers=__lowerCAmelCase ) test_command_parser(subparsers=__lowerCAmelCase ) # Let's go __UpperCamelCase = parser.parse_args() if not hasattr(__lowerCAmelCase , 'func' ): parser.print_help() exit(1 ) # Run args.func(__lowerCAmelCase ) if __name__ == "__main__": main()
383
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
0
import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def a(lowercase__ ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def a(): '''simple docstring''' with parallel_backend('spark' ): assert ParallelBackendConfig.backend_name == "spark" snake_case_ = [1, 2, 3] with pytest.raises(__lowerCAmelCase ): with parallel_backend('unsupported backend' ): map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=2 ) with pytest.raises(__lowerCAmelCase ): with parallel_backend('unsupported backend' ): map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize('num_proc' , [2, -1] ) def a(lowercase__ ): '''simple docstring''' snake_case_ = [1, 2] snake_case_ = {"""a""": 1, """b""": 2} snake_case_ = {"""a""": [1, 2], """b""": [3, 4]} snake_case_ = {"""a""": {"""1""": 1}, """b""": 2} snake_case_ = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} snake_case_ = [2, 3] snake_case_ = {"""a""": 2, """b""": 3} snake_case_ = {"""a""": [2, 3], """b""": [4, 5]} snake_case_ = {"""a""": {"""1""": 2}, """b""": 3} snake_case_ = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend('spark' ): assert map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=__lowerCAmelCase ) == expected_map_nested_sa assert map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=__lowerCAmelCase ) == expected_map_nested_sa assert map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=__lowerCAmelCase ) == expected_map_nested_sa assert map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=__lowerCAmelCase ) == expected_map_nested_sa assert map_nested(__lowerCAmelCase , __lowerCAmelCase , num_proc=__lowerCAmelCase ) == expected_map_nested_sa
187
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
0
"""simple docstring""" import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncoder, BertModel, BertPreTrainedModel, ) __lowerCamelCase = logging.getLogger(__name__) class __A ( UpperCamelCase_ ): def lowerCamelCase__ ( self : Union[str, Any] , __snake_case : List[str] , __snake_case : Optional[int] , __snake_case : List[str]=None , __snake_case : Tuple=None ) -> List[str]: __magic_name__: Optional[int] = self.layer[current_layer](_a , _a , head_mask[current_layer] ) __magic_name__: Dict = layer_outputs[0] return hidden_states @add_start_docstrings( "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top." ,UpperCamelCase_ ,) class __A ( UpperCamelCase_ ): def __init__( self : Optional[int] , __snake_case : List[str] ) -> Any: super().__init__(_a ) __magic_name__: str = BertEncoderWithPabee(_a ) self.init_weights() __magic_name__: Optional[Any] = 0 __magic_name__: Optional[Any] = 0 __magic_name__: List[str] = 0 __magic_name__: Optional[Any] = 0 def lowerCamelCase__ ( self : Optional[Any] , __snake_case : Tuple ) -> Dict: __magic_name__: Optional[Any] = threshold def lowerCamelCase__ ( self : Tuple , __snake_case : List[Any] ) -> Tuple: __magic_name__: Union[str, Any] = patience def lowerCamelCase__ ( self : List[str] ) -> List[str]: __magic_name__: Optional[int] = 0 __magic_name__: List[str] = 0 def lowerCamelCase__ ( self : Tuple ) -> List[str]: __magic_name__: Tuple = self.inference_layers_num / self.inference_instances_num __magic_name__: List[Any] = ( F'*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up =' F' {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***' ) print(_a ) @add_start_docstrings_to_model_forward(_a ) def lowerCamelCase__ ( self : Any , __snake_case : Optional[int]=None , __snake_case : Dict=None , __snake_case : List[str]=None , __snake_case : Dict=None , __snake_case : Optional[int]=None , __snake_case : str=None , __snake_case : List[Any]=None , __snake_case : Optional[int]=None , __snake_case : Dict=None , __snake_case : Optional[int]=None , __snake_case : str=False , ) -> str: if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: __magic_name__: Union[str, Any] = input_ids.size() elif inputs_embeds is not None: __magic_name__: str = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) __magic_name__: Union[str, Any] = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: __magic_name__: Dict = torch.ones(_a , device=_a ) if token_type_ids is None: __magic_name__: str = torch.zeros(_a , dtype=torch.long , device=_a ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. __magic_name__: torch.Tensor = self.get_extended_attention_mask(_a , _a , _a ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: __magic_name__: str = encoder_hidden_states.size() __magic_name__: int = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: __magic_name__: Dict = torch.ones(_a , device=_a ) __magic_name__: Dict = self.invert_attention_mask(_a ) else: __magic_name__: str = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] __magic_name__: int = self.get_head_mask(_a , self.config.num_hidden_layers ) __magic_name__: int = self.embeddings( input_ids=_a , position_ids=_a , token_type_ids=_a , inputs_embeds=_a ) __magic_name__: int = embedding_output if self.training: __magic_name__: Optional[Any] = [] for i in range(self.config.num_hidden_layers ): __magic_name__: List[Any] = self.encoder.adaptive_forward( _a , current_layer=_a , attention_mask=_a , head_mask=_a ) __magic_name__: int = self.pooler(_a ) __magic_name__: int = output_layers[i](output_dropout(_a ) ) res.append(_a ) elif self.patience == 0: # Use all layers for inference __magic_name__: Union[str, Any] = self.encoder( _a , attention_mask=_a , head_mask=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , ) __magic_name__: List[Any] = self.pooler(encoder_outputs[0] ) __magic_name__: List[str] = [output_layers[self.config.num_hidden_layers - 1](_a )] else: __magic_name__: Optional[Any] = 0 __magic_name__: Dict = None __magic_name__: List[str] = 0 for i in range(self.config.num_hidden_layers ): calculated_layer_num += 1 __magic_name__: List[str] = self.encoder.adaptive_forward( _a , current_layer=_a , attention_mask=_a , head_mask=_a ) __magic_name__: str = self.pooler(_a ) __magic_name__: Dict = output_layers[i](_a ) if regression: __magic_name__: Dict = logits.detach() if patient_result is not None: __magic_name__: Any = patient_result.detach() if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold: patient_counter += 1 else: __magic_name__: Any = 0 else: __magic_name__: str = logits.detach().argmax(dim=1 ) if patient_result is not None: __magic_name__: Dict = patient_result.detach().argmax(dim=1 ) if (patient_result is not None) and torch.all(labels.eq(_a ) ): patient_counter += 1 else: __magic_name__: Any = 0 __magic_name__: Any = logits if patient_counter == self.patience: break __magic_name__: Tuple = [patient_result] self.inference_layers_num += calculated_layer_num self.inference_instances_num += 1 return res @add_start_docstrings( "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. " ,UpperCamelCase_ ,) class __A ( UpperCamelCase_ ): def __init__( self : Tuple , __snake_case : Union[str, Any] ) -> List[Any]: super().__init__(_a ) __magic_name__: Optional[Any] = config.num_labels __magic_name__: Optional[Any] = BertModelWithPabee(_a ) __magic_name__: Tuple = nn.Dropout(config.hidden_dropout_prob ) __magic_name__: Any = nn.ModuleList( [nn.Linear(config.hidden_size , self.config.num_labels ) for _ in range(config.num_hidden_layers )] ) self.init_weights() @add_start_docstrings_to_model_forward(_a ) def lowerCamelCase__ ( self : Optional[Any] , __snake_case : Union[str, Any]=None , __snake_case : str=None , __snake_case : Any=None , __snake_case : Optional[Any]=None , __snake_case : Optional[int]=None , __snake_case : List[str]=None , __snake_case : Optional[Any]=None , ) -> str: __magic_name__: Optional[Any] = self.bert( input_ids=_a , attention_mask=_a , token_type_ids=_a , position_ids=_a , head_mask=_a , inputs_embeds=_a , output_dropout=self.dropout , output_layers=self.classifiers , regression=self.num_labels == 1 , ) __magic_name__: Any = (logits[-1],) if labels is not None: __magic_name__: List[Any] = None __magic_name__: List[Any] = 0 for ix, logits_item in enumerate(_a ): if self.num_labels == 1: # We are doing regression __magic_name__: Dict = MSELoss() __magic_name__: Dict = loss_fct(logits_item.view(-1 ) , labels.view(-1 ) ) else: __magic_name__: Dict = CrossEntropyLoss() __magic_name__: List[Any] = loss_fct(logits_item.view(-1 , self.num_labels ) , labels.view(-1 ) ) if total_loss is None: __magic_name__: Tuple = loss else: total_loss += loss * (ix + 1) total_weights += ix + 1 __magic_name__: Union[str, Any] = (total_loss / total_weights,) + outputs return outputs
96
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
0
"""simple docstring""" def __UpperCamelCase ( SCREAMING_SNAKE_CASE ) -> list[list]: """simple docstring""" __snake_case = current_set.copy() for row_index, row in enumerate(__lowerCAmelCase ): __snake_case = row[0] for column_index, column in enumerate(__lowerCAmelCase ): if magnitude == 0: __snake_case = column continue __snake_case = column / magnitude # Subtract to cancel term __snake_case = current_set[0] __snake_case = [first_row] __snake_case = current_set[1::] for row in current_set: __snake_case = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__lowerCAmelCase ) continue for column_index in range(len(__lowerCAmelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__lowerCAmelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: __snake_case = final_set[0] __snake_case = [] __snake_case = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) __snake_case = simplify(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __lowerCAmelCase ) __snake_case = resultant return final_set def __UpperCamelCase ( SCREAMING_SNAKE_CASE ) -> list: """simple docstring""" if len(__lowerCAmelCase ) == 0: raise IndexError("solve_simultaneous() requires n lists of length n+1" ) __snake_case = len(__lowerCAmelCase ) + 1 if any(len(__lowerCAmelCase ) != _length for item in equations ): raise IndexError("solve_simultaneous() requires n lists of length n+1" ) for row in equations: if any(not isinstance(__lowerCAmelCase , (int, float) ) for column in row ): raise ValueError("solve_simultaneous() requires lists of integers" ) if len(__lowerCAmelCase ) == 1: return [equations[0][-1] / equations[0][0]] __snake_case = equations.copy() if any(0 in row for row in data_set ): __snake_case = data_set.copy() __snake_case = [] for row_index, row in enumerate(__lowerCAmelCase ): if 0 not in row: __snake_case = data_set.pop(__lowerCAmelCase ) break if not full_row: raise ValueError("solve_simultaneous() requires at least 1 full equation" ) data_set.insert(0 , __lowerCAmelCase ) __snake_case = data_set.copy() __snake_case = simplify(__lowerCAmelCase ) __snake_case = simplified[::-1] __snake_case = [] for row in simplified: __snake_case = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue __snake_case = row.copy()[: len(__lowerCAmelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__lowerCAmelCase ) == 0: solutions.append(0 ) continue __snake_case = temp_row[1::] __snake_case = temp_row[::-1] for column_index, column in enumerate(__lowerCAmelCase ): current_solution -= column * solutions[column_index] solutions.append(__lowerCAmelCase ) __snake_case = [] for item in solutions: final.append(float(round(__lowerCAmelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() _SCREAMING_SNAKE_CASE = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
163
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class __lowercase ( metaclass=UpperCamelCase_ ): _a = ["""flax""", """transformers"""] def __init__( self , *UpperCamelCase , **UpperCamelCase ) -> List[str]: requires_backends(self , ['flax', 'transformers'] ) @classmethod def UpperCamelCase__ ( cls , *UpperCamelCase , **UpperCamelCase ) -> Any: requires_backends(cls , ['flax', 'transformers'] ) @classmethod def UpperCamelCase__ ( cls , *UpperCamelCase , **UpperCamelCase ) -> Optional[Any]: requires_backends(cls , ['flax', 'transformers'] ) class __lowercase ( metaclass=UpperCamelCase_ ): _a = ["""flax""", """transformers"""] def __init__( self , *UpperCamelCase , **UpperCamelCase ) -> Dict: requires_backends(self , ['flax', 'transformers'] ) @classmethod def UpperCamelCase__ ( cls , *UpperCamelCase , **UpperCamelCase ) -> Union[str, Any]: requires_backends(cls , ['flax', 'transformers'] ) @classmethod def UpperCamelCase__ ( cls , *UpperCamelCase , **UpperCamelCase ) -> Optional[int]: requires_backends(cls , ['flax', 'transformers'] ) class __lowercase ( metaclass=UpperCamelCase_ ): _a = ["""flax""", """transformers"""] def __init__( self , *UpperCamelCase , **UpperCamelCase ) -> Tuple: requires_backends(self , ['flax', 'transformers'] ) @classmethod def UpperCamelCase__ ( cls , *UpperCamelCase , **UpperCamelCase ) -> Union[str, Any]: requires_backends(cls , ['flax', 'transformers'] ) @classmethod def UpperCamelCase__ ( cls , *UpperCamelCase , **UpperCamelCase ) -> Any: requires_backends(cls , ['flax', 'transformers'] ) class __lowercase ( metaclass=UpperCamelCase_ ): _a = ["""flax""", """transformers"""] def __init__( self , *UpperCamelCase , **UpperCamelCase ) -> Optional[int]: requires_backends(self , ['flax', 'transformers'] ) @classmethod def UpperCamelCase__ ( cls , *UpperCamelCase , **UpperCamelCase ) -> List[str]: requires_backends(cls , ['flax', 'transformers'] ) @classmethod def UpperCamelCase__ ( cls , *UpperCamelCase , **UpperCamelCase ) -> Union[str, Any]: requires_backends(cls , ['flax', 'transformers'] )
539
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
0
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable lowerCamelCase : List[str] ={"configuration_gpt_neox": ["GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXConfig"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[int] =["GPTNeoXTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : str =[ "GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXForCausalLM", "GPTNeoXForQuestionAnswering", "GPTNeoXForSequenceClassification", "GPTNeoXForTokenClassification", "GPTNeoXLayer", "GPTNeoXModel", "GPTNeoXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys lowerCamelCase : Tuple =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
228
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
0
from manim import * class A( UpperCamelCase_ ): '''simple docstring''' def a__ ( self : Dict ) -> str: """simple docstring""" lowerCamelCase_ = Rectangle(height=0.5 , width=0.5 ) lowerCamelCase_ = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) lowerCamelCase_ = Rectangle(height=0.25 , width=0.25 ) lowerCamelCase_ = [mem.copy() for i in range(6 )] lowerCamelCase_ = [mem.copy() for i in range(6 )] lowerCamelCase_ = VGroup(*_a ).arrange(_a , buff=0 ) lowerCamelCase_ = VGroup(*_a ).arrange(_a , buff=0 ) lowerCamelCase_ = VGroup(_a , _a ).arrange(_a , buff=0 ) lowerCamelCase_ = Text('CPU' , font_size=24 ) lowerCamelCase_ = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_a ) lowerCamelCase_ = [mem.copy() for i in range(4 )] lowerCamelCase_ = VGroup(*_a ).arrange(_a , buff=0 ) lowerCamelCase_ = Text('GPU' , font_size=24 ) lowerCamelCase_ = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) gpu.move_to([-1, -1, 0] ) self.add(_a ) lowerCamelCase_ = [mem.copy() for i in range(6 )] lowerCamelCase_ = VGroup(*_a ).arrange(_a , buff=0 ) lowerCamelCase_ = Text('Model' , font_size=24 ) lowerCamelCase_ = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) model.move_to([3, -1.0, 0] ) self.add(_a ) lowerCamelCase_ = [] lowerCamelCase_ = [] for i, rect in enumerate(_a ): lowerCamelCase_ = fill.copy().set_fill(_a , opacity=0.8 ) target.move_to(_a ) model_arr.append(_a ) lowerCamelCase_ = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(_a , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(_a ) self.add(*_a , *_a ) lowerCamelCase_ = [meta_mem.copy() for i in range(6 )] lowerCamelCase_ = [meta_mem.copy() for i in range(6 )] lowerCamelCase_ = VGroup(*_a ).arrange(_a , buff=0 ) lowerCamelCase_ = VGroup(*_a ).arrange(_a , buff=0 ) lowerCamelCase_ = VGroup(_a , _a ).arrange(_a , buff=0 ) lowerCamelCase_ = Text('Disk' , font_size=24 ) lowerCamelCase_ = Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a ) disk.move_to([-4, -1.25, 0] ) self.add(_a , _a ) lowerCamelCase_ = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) lowerCamelCase_ = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_a , _a ) lowerCamelCase_ = MarkupText( f"""<span fgcolor=\'{BLUE}\'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(_a , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(_a ) lowerCamelCase_ = MarkupText( f"""Now watch as an input is passed through the model\nand how the memory is utilized and handled.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(_a ) ) lowerCamelCase_ = Square(0.3 ) input.set_fill(_a , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , _a , buff=0.5 ) self.play(Write(_a ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=_a , buff=0.02 ) self.play(MoveToTarget(_a ) ) self.play(FadeOut(_a ) ) lowerCamelCase_ = Arrow(start=_a , end=_a , color=_a , buff=0.5 ) a.next_to(model_arr[0].get_left() , _a , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) lowerCamelCase_ = MarkupText( f"""As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(_a , run_time=3 ) ) lowerCamelCase_ = {"""run_time""": 1, """fade_in""": True, """fade_out""": True, """buff""": 0.02} self.play( Write(_a ) , Circumscribe(model_arr[0] , color=_a , **_a ) , Circumscribe(model_cpu_arr[0] , color=_a , **_a ) , Circumscribe(gpu_rect[0] , color=_a , **_a ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) lowerCamelCase_ = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.02 , _a , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.02 ) lowerCamelCase_ = AnimationGroup( FadeOut(_a , run_time=0.5 ) , MoveToTarget(_a , run_time=0.5 ) , FadeIn(_a , run_time=0.5 ) , lag_ratio=0.2 ) self.play(_a ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: lowerCamelCase_ = 0.7 self.play( Circumscribe(model_arr[i] , **_a ) , Circumscribe(cpu_left_col_base[i] , **_a ) , Circumscribe(cpu_left_col_base[i + 1] , color=_a , **_a ) , Circumscribe(gpu_rect[0] , color=_a , **_a ) , Circumscribe(model_arr[i + 1] , color=_a , **_a ) , ) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) , MoveToTarget(model_cpu_arr[i + 1] ) , ) else: self.play( MoveToTarget(model_cpu_arr[i] , run_time=0.7 ) , MoveToTarget(model_cpu_arr[i + 1] , run_time=0.7 ) , ) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() , RIGHT + 0.02 , buff=0.2 ) self.play( Circumscribe(model_arr[-1] , color=_a , **_a ) , Circumscribe(cpu_left_col_base[-1] , color=_a , **_a ) , Circumscribe(gpu_rect[0] , color=_a , **_a ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) lowerCamelCase_ = a_c lowerCamelCase_ = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.02 , buff=0.5 ) self.play( FadeOut(_a ) , FadeOut(_a , run_time=0.5 ) , ) lowerCamelCase_ = MarkupText(f"""Inference on a model too large for GPU memory\nis successfully completed.""" , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(_a , run_time=3 ) , MoveToTarget(_a ) ) self.wait()
70
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
0
"""simple docstring""" from random import randint from tempfile import TemporaryFile import numpy as np def lowerCamelCase ( _snake_case ,_snake_case ,_snake_case ): UpperCAmelCase__ : Optional[int] = 0 if start < end: UpperCAmelCase__ : Any = randint(__lowerCAmelCase ,__lowerCAmelCase ) UpperCAmelCase__ : Any = a[end] UpperCAmelCase__ : Union[str, Any] = a[pivot] UpperCAmelCase__ : Optional[int] = temp UpperCAmelCase__ : Optional[int] = _in_place_partition(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) count += _in_place_quick_sort(__lowerCAmelCase ,__lowerCAmelCase ,p - 1 ) count += _in_place_quick_sort(__lowerCAmelCase ,p + 1 ,__lowerCAmelCase ) return count def lowerCamelCase ( _snake_case ,_snake_case ,_snake_case ): UpperCAmelCase__ : str = 0 UpperCAmelCase__ : Dict = randint(__lowerCAmelCase ,__lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = a[end] UpperCAmelCase__ : Dict = a[pivot] UpperCAmelCase__ : Tuple = temp UpperCAmelCase__ : int = start - 1 for index in range(__lowerCAmelCase ,__lowerCAmelCase ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value UpperCAmelCase__ : List[str] = new_pivot_index + 1 UpperCAmelCase__ : List[str] = a[new_pivot_index] UpperCAmelCase__ : Optional[int] = a[index] UpperCAmelCase__ : Any = temp UpperCAmelCase__ : Optional[Any] = a[new_pivot_index + 1] UpperCAmelCase__ : Optional[int] = a[end] UpperCAmelCase__ : Dict = temp return new_pivot_index + 1, count UpperCamelCase__ = TemporaryFile() UpperCamelCase__ = 1_00 # 1000 elements are to be sorted UpperCamelCase__ = 0, 1 # mean and standard deviation UpperCamelCase__ = np.random.normal(mu, sigma, p) np.save(outfile, X) print('The array is') print(X) outfile.seek(0) # using the same array UpperCamelCase__ = np.load(outfile) UpperCamelCase__ = len(M) - 1 UpperCamelCase__ = _in_place_quick_sort(M, 0, r) print( 'No of Comparisons for 100 elements selected from a standard normal distribution' 'is :' ) print(z)
110
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
0
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger lowerCAmelCase__ = "<<<<<<< This should probably be modified because it mentions: " lowerCAmelCase__ = "=======\n>>>>>>>\n" lowerCAmelCase__ = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] lowerCAmelCase__ = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def a__ ( SCREAMING_SNAKE_CASE : Any ): '''simple docstring''' return ConvertCommand(args.tfds_path , args.datasets_directory ) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): """simple docstring""" @staticmethod def lowercase__ ( snake_case__ ): """simple docstring""" lowerCAmelCase : Union[str, Any] = parser.add_parser( "convert" , help="Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset." , ) train_parser.add_argument( "--tfds_path" , type=_a , required=_a , help="Path to a TensorFlow Datasets folder to convert or a single tfds file to convert." , ) train_parser.add_argument( "--datasets_directory" , type=_a , required=_a , help="Path to the HuggingFace Datasets folder." ) train_parser.set_defaults(func=_a ) def __init__( self , snake_case__ , snake_case__ , *snake_case__ ): """simple docstring""" lowerCAmelCase : int = get_logger("datasets-cli/converting" ) lowerCAmelCase : Union[str, Any] = tfds_path lowerCAmelCase : List[Any] = datasets_directory def lowercase__ ( self ): """simple docstring""" if os.path.isdir(self._tfds_path ): lowerCAmelCase : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): lowerCAmelCase : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("--tfds_path is neither a directory nor a file. Please check path." ) lowerCAmelCase : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f"""Converting datasets from {abs_tfds_path} to {abs_datasets_path}""" ) lowerCAmelCase : str = [] lowerCAmelCase : str = [] lowerCAmelCase : List[Any] = {} if os.path.isdir(self._tfds_path ): lowerCAmelCase : Union[str, Any] = os.listdir(_a ) else: lowerCAmelCase : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f"""Looking at file {f_name}""" ) lowerCAmelCase : int = os.path.join(_a , _a ) lowerCAmelCase : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("Skipping file" ) continue with open(_a , encoding="utf-8" ) as f: lowerCAmelCase : List[str] = f.readlines() lowerCAmelCase : Optional[int] = [] lowerCAmelCase : str = False lowerCAmelCase : Optional[int] = False lowerCAmelCase : Dict = [] for line in lines: lowerCAmelCase : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: lowerCAmelCase : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here lowerCAmelCase : Optional[Any] = """""" continue elif "from absl import logging" in out_line: lowerCAmelCase : Any = """from datasets import logging\n""" elif "getLogger" in out_line: lowerCAmelCase : Optional[int] = out_line.replace("getLogger" , "get_logger" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): lowerCAmelCase : Union[str, Any] = True lowerCAmelCase : Tuple = list(filter(lambda snake_case__ : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + "\n" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: lowerCAmelCase : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: lowerCAmelCase : Dict = re.match(r"from\stensorflow_datasets.*import\s([^\.\r\n]+)" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split("," ) ) lowerCAmelCase : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f"""Error converting {out_line.strip()}""" ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: lowerCAmelCase : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset lowerCAmelCase : Union[str, Any] = f_name.replace(".py" , "" ) lowerCAmelCase : List[str] = os.path.join(_a , _a ) lowerCAmelCase : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f"""Adding directory {output_dir}""" ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , "w" , encoding="utf-8" ) as f: f.writelines(_a ) self._logger.info(f"""Converted in {output_file}""" ) for utils_file in utils_files: try: lowerCAmelCase : str = os.path.basename(_a ) lowerCAmelCase : Optional[Any] = imports_to_builder_map[f_name.replace(".py" , "" )] self._logger.info(f"""Moving {dest_folder} to {utils_file}""" ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f"""Cannot find destination folder for {utils_file}. Please copy manually.""" ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f"""You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.""" )
645
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available __snake_case :str ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case :str =[ "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 __snake_case :Tuple =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
106
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : 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 _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
0
import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class lowercase ( enum.Enum ): """simple docstring""" snake_case_ = 0 snake_case_ = 1 snake_case_ = 2 @add_end_docstrings(UpperCamelCase_ ) class lowercase ( UpperCamelCase_ ): """simple docstring""" snake_case_ = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self : List[Any] , *a_ : Optional[int] , **a_ : Optional[Any] ): """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. lowerCamelCase__ = None if self.model.config.prefix is not None: lowerCamelCase__ = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. lowerCamelCase__ = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. lowerCamelCase__ = self._sanitize_parameters(prefix=_a , **self._forward_params ) lowerCamelCase__ = {**self._preprocess_params, **preprocess_params} lowerCamelCase__ = {**self._forward_params, **forward_params} def _UpperCamelCase ( self : Dict , a_ : Dict=None , a_ : Dict=None , a_ : Tuple=None , a_ : int=None , a_ : Union[str, Any]=None , a_ : Union[str, Any]=None , a_ : Optional[Any]=None , a_ : Tuple=None , **a_ : int , ): """simple docstring""" lowerCamelCase__ = {} if prefix is not None: lowerCamelCase__ = prefix if prefix: lowerCamelCase__ = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) lowerCamelCase__ = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( F'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) lowerCamelCase__ = handle_long_generation preprocess_params.update(_a ) lowerCamelCase__ = generate_kwargs lowerCamelCase__ = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) lowerCamelCase__ = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) lowerCamelCase__ = ReturnType.TENSORS if return_type is not None: lowerCamelCase__ = return_type if clean_up_tokenization_spaces is not None: lowerCamelCase__ = clean_up_tokenization_spaces if stop_sequence is not None: lowerCamelCase__ = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) lowerCamelCase__ = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _UpperCamelCase ( self : int , *a_ : Any , **a_ : List[str] ): """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self : Dict , a_ : Tuple , **a_ : Optional[int] ): """simple docstring""" return super().__call__(_a , **_a ) def _UpperCamelCase ( self : Tuple , a_ : Optional[int] , a_ : int="" , a_ : Dict=None , **a_ : Any ): """simple docstring""" lowerCamelCase__ = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) lowerCamelCase__ = prompt_text if handle_long_generation == "hole": lowerCamelCase__ = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: lowerCamelCase__ = generate_kwargs["""max_new_tokens"""] else: lowerCamelCase__ = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: lowerCamelCase__ = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) lowerCamelCase__ = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: lowerCamelCase__ = inputs["""attention_mask"""][:, -keep_length:] return inputs def _UpperCamelCase ( self : Optional[Any] , a_ : List[str] , **a_ : int ): """simple docstring""" lowerCamelCase__ = model_inputs["""input_ids"""] lowerCamelCase__ = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = 1 else: lowerCamelCase__ = input_ids.shape[0] lowerCamelCase__ = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. lowerCamelCase__ = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: lowerCamelCase__ = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: lowerCamelCase__ = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length lowerCamelCase__ = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL lowerCamelCase__ = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) lowerCamelCase__ = generated_sequence.shape[0] if self.framework == "pt": lowerCamelCase__ = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": lowerCamelCase__ = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _UpperCamelCase ( self : Optional[Any] , a_ : Dict , a_ : List[str]=ReturnType.FULL_TEXT , a_ : Optional[Any]=True ): """simple docstring""" lowerCamelCase__ = model_outputs["""generated_sequence"""][0] lowerCamelCase__ = model_outputs["""input_ids"""] lowerCamelCase__ = model_outputs["""prompt_text"""] lowerCamelCase__ = generated_sequence.numpy().tolist() lowerCamelCase__ = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: lowerCamelCase__ = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text lowerCamelCase__ = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: lowerCamelCase__ = 0 else: lowerCamelCase__ = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: lowerCamelCase__ = prompt_text + text[prompt_length:] else: lowerCamelCase__ = text[prompt_length:] lowerCamelCase__ = {"""generated_text""": all_text} records.append(_a ) return records
165
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
0
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class lowerCAmelCase_ : """simple docstring""" def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=0 , ) -> Optional[Any]: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_input_mask __UpperCamelCase = use_token_type_ids __UpperCamelCase = use_labels __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_act __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = type_vocab_size __UpperCamelCase = type_sequence_label_size __UpperCamelCase = initializer_range __UpperCamelCase = num_labels __UpperCamelCase = num_choices __UpperCamelCase = scope __UpperCamelCase = projection_dim def __lowercase( self ) -> Union[str, Any]: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase = None if self.use_token_type_ids: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) __UpperCamelCase = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: __UpperCamelCase = TFDPRContextEncoder(config=_a ) __UpperCamelCase = model(_a , attention_mask=_a , token_type_ids=_a ) __UpperCamelCase = model(_a , token_type_ids=_a ) __UpperCamelCase = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: __UpperCamelCase = TFDPRQuestionEncoder(config=_a ) __UpperCamelCase = model(_a , attention_mask=_a , token_type_ids=_a ) __UpperCamelCase = model(_a , token_type_ids=_a ) __UpperCamelCase = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: __UpperCamelCase = TFDPRReader(config=_a ) __UpperCamelCase = model(_a , attention_mask=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def __lowercase( self ) -> List[str]: __UpperCamelCase = self.prepare_config_and_inputs() ( __UpperCamelCase ) = config_and_inputs __UpperCamelCase = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) UpperCAmelCase__ = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False def __lowercase( self ) -> str: __UpperCamelCase = TFDPRModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=_a , hidden_size=37 ) def __lowercase( self ) -> List[Any]: self.config_tester.run_common_tests() def __lowercase( self ) -> Dict: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def __lowercase( self ) -> str: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def __lowercase( self ) -> int: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def __lowercase( self ) -> Union[str, Any]: for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def __lowercase( self ) -> Union[str, Any]: __UpperCamelCase = TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base' ) __UpperCamelCase = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] __UpperCamelCase = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. __UpperCamelCase = tf.constant( [ [ 0.0_3_2_3_6_2_5_3, 0.1_2_7_5_3_3_3_5, 0.1_6_8_1_8_5_0_9, 0.0_0_2_7_9_7_8_6, 0.3_8_9_6_9_3_3, 0.2_4_2_6_4_9_4_5, 0.2_1_7_8_9_7_1, -0.0_2_3_3_5_2_2_7, -0.0_8_4_8_1_9_5_9, -0.1_4_3_2_4_1_1_7, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1e-4 ) )
383
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "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 a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A = logging.get_logger(__name__) A = { "junnyu/roformer_chinese_small": "https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json", "junnyu/roformer_chinese_base": "https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json", "junnyu/roformer_chinese_char_small": ( "https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json" ), "junnyu/roformer_chinese_char_base": ( "https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json" ), "junnyu/roformer_small_discriminator": ( "https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json" ), "junnyu/roformer_small_generator": ( "https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json" ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class SCREAMING_SNAKE_CASE ( UpperCamelCase_ ): """simple docstring""" __A = """roformer""" def __init__( self , __UpperCamelCase=5_00_00 , __UpperCamelCase=None , __UpperCamelCase=7_68 , __UpperCamelCase=12 , __UpperCamelCase=12 , __UpperCamelCase=30_72 , __UpperCamelCase="gelu" , __UpperCamelCase=0.1 , __UpperCamelCase=0.1 , __UpperCamelCase=15_36 , __UpperCamelCase=2 , __UpperCamelCase=0.02 , __UpperCamelCase=1E-12 , __UpperCamelCase=0 , __UpperCamelCase=False , __UpperCamelCase=True , **__UpperCamelCase , ): """simple docstring""" super().__init__(pad_token_id=_a , **_a ) snake_case_ = vocab_size snake_case_ = hidden_size if embedding_size is None else embedding_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = hidden_act snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = rotary_value snake_case_ = use_cache class SCREAMING_SNAKE_CASE ( UpperCamelCase_ ): """simple docstring""" @property def __lowerCAmelCase ( self ): """simple docstring""" if self.task == "multiple-choice": snake_case_ = {0: """batch""", 1: """choice""", 2: """sequence"""} else: snake_case_ = {0: """batch""", 1: """sequence"""} snake_case_ = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
187
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
0
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 __lowerCamelCase = sys.version_info >= (3, 10) def a ( __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : Union[str, Any]=None ) -> List[Any]: return field(default_factory=lambda: default , metadata=__lowerCAmelCase ) @dataclass class __A : UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 @dataclass class __A : UpperCAmelCase__ = 4_2 UpperCAmelCase__ = field(default="toto" ,metadata={"help": "help message"} ) @dataclass class __A : UpperCAmelCase__ = False UpperCAmelCase__ = True UpperCAmelCase__ = None class __A ( UpperCamelCase_ ): UpperCAmelCase__ = """titi""" UpperCAmelCase__ = """toto""" class __A ( UpperCamelCase_ ): UpperCAmelCase__ = """titi""" UpperCAmelCase__ = """toto""" UpperCAmelCase__ = 4_2 @dataclass class __A : UpperCAmelCase__ = "toto" def lowerCamelCase__ ( self : List[str] ) -> Union[str, Any]: __magic_name__: Optional[int] = BasicEnum(self.foo ) @dataclass class __A : UpperCAmelCase__ = "toto" def lowerCamelCase__ ( self : str ) -> Dict: __magic_name__: str = MixedTypeEnum(self.foo ) @dataclass class __A : UpperCAmelCase__ = None UpperCAmelCase__ = field(default=UpperCamelCase_ ,metadata={"help": "help message"} ) UpperCAmelCase__ = None UpperCAmelCase__ = list_field(default=[] ) UpperCAmelCase__ = list_field(default=[] ) @dataclass class __A : UpperCAmelCase__ = list_field(default=[] ) UpperCAmelCase__ = list_field(default=[1, 2, 3] ) UpperCAmelCase__ = list_field(default=["Hallo", "Bonjour", "Hello"] ) UpperCAmelCase__ = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class __A : UpperCAmelCase__ = field() UpperCAmelCase__ = field() UpperCAmelCase__ = field() def lowerCamelCase__ ( self : str ) -> str: __magic_name__: Dict = BasicEnum(self.required_enum ) @dataclass class __A : UpperCAmelCase__ = 42 UpperCAmelCase__ = field() UpperCAmelCase__ = None UpperCAmelCase__ = field(default="toto" ,metadata={"help": "help message"} ) UpperCAmelCase__ = list_field(default=["Hallo", "Bonjour", "Hello"] ) if is_python_no_less_than_3_10: @dataclass class __A : UpperCAmelCase__ = False UpperCAmelCase__ = True UpperCAmelCase__ = None @dataclass class __A : UpperCAmelCase__ = None UpperCAmelCase__ = field(default=UpperCamelCase_ ,metadata={"help": "help message"} ) UpperCAmelCase__ = None UpperCAmelCase__ = list_field(default=[] ) UpperCAmelCase__ = list_field(default=[] ) class __A ( unittest.TestCase ): def lowerCamelCase__ ( self : Optional[Any] , __snake_case : Union[str, Any] , __snake_case : str ) -> Dict: self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): __magic_name__: Any = {k: v for k, v in vars(_a ).items() if k != """container"""} __magic_name__: Optional[Any] = {k: v for k, v in vars(_a ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , _a ) and yy.get("""choices""" , _a ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](_a ) , yy["""type"""](_a ) ) del xx["type"], yy["type"] self.assertEqual(_a , _a ) def lowerCamelCase__ ( self : List[Any] ) -> List[str]: __magic_name__: Any = HfArgumentParser(_a ) __magic_name__: Dict = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=_a , required=_a ) expected.add_argument("""--bar""" , type=_a , required=_a ) expected.add_argument("""--baz""" , type=_a , required=_a ) expected.add_argument("""--flag""" , type=_a , default=_a , const=_a , nargs="""?""" ) self.argparsersEqual(_a , _a ) __magic_name__: Dict = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] (__magic_name__ ): Optional[int] = parser.parse_args_into_dataclasses(_a , look_for_args_file=_a ) self.assertFalse(example.flag ) def lowerCamelCase__ ( self : List[str] ) -> Union[str, Any]: __magic_name__: List[Any] = HfArgumentParser(_a ) __magic_name__: str = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=4_2 , type=_a ) expected.add_argument("""--baz""" , default="""toto""" , type=_a , help="""help message""" ) self.argparsersEqual(_a , _a ) def lowerCamelCase__ ( self : Dict ) -> Any: __magic_name__: Optional[Any] = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=_a , default=_a , const=_a , nargs="""?""" ) expected.add_argument("""--baz""" , type=_a , default=_a , const=_a , nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=_a , dest="""baz""" ) expected.add_argument("""--opt""" , type=_a , default=_a ) __magic_name__: Tuple = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(_a ) for dataclass_type in dataclass_types: __magic_name__: List[Any] = HfArgumentParser(_a ) self.argparsersEqual(_a , _a ) __magic_name__: Any = parser.parse_args([] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) __magic_name__: Any = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) __magic_name__: Union[str, Any] = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) __magic_name__: Optional[int] = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) __magic_name__: int = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) def lowerCamelCase__ ( self : str ) -> Optional[Any]: __magic_name__: Optional[int] = HfArgumentParser(_a ) __magic_name__: int = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 4_2] , type=make_choice_type_function(["""titi""", """toto""", 4_2] ) , ) self.argparsersEqual(_a , _a ) __magic_name__: Tuple = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) __magic_name__: int = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) __magic_name__: List[Any] = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) __magic_name__: Tuple = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) __magic_name__: Dict = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 4_2 ) __magic_name__: List[str] = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def lowerCamelCase__ ( self : List[str] ) -> Union[str, Any]: @dataclass class __A : UpperCAmelCase__ = "toto" __magic_name__: str = HfArgumentParser(_a ) __magic_name__: Any = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 4_2) , type=make_choice_type_function(["""titi""", """toto""", 4_2] ) , ) self.argparsersEqual(_a , _a ) __magic_name__: Optional[int] = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) __magic_name__: str = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) __magic_name__: Any = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 4_2 ) def lowerCamelCase__ ( self : int ) -> Optional[int]: __magic_name__: Dict = HfArgumentParser(_a ) __magic_name__: int = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=_a ) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=_a ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=_a ) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=_a ) self.argparsersEqual(_a , _a ) __magic_name__: str = parser.parse_args([] ) self.assertEqual( _a , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , ) __magic_name__: Union[str, Any] = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(_a , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) ) def lowerCamelCase__ ( self : Any ) -> Optional[int]: __magic_name__: Union[str, Any] = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=_a , type=_a ) expected.add_argument("""--bar""" , default=_a , type=_a , help="""help message""" ) expected.add_argument("""--baz""" , default=_a , type=_a ) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=_a ) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=_a ) __magic_name__: Union[str, Any] = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(_a ) for dataclass_type in dataclass_types: __magic_name__: Dict = HfArgumentParser(_a ) self.argparsersEqual(_a , _a ) __magic_name__: List[Any] = parser.parse_args([] ) self.assertEqual(_a , Namespace(foo=_a , bar=_a , baz=_a , ces=[] , des=[] ) ) __magic_name__: List[str] = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(_a , Namespace(foo=1_2 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) ) def lowerCamelCase__ ( self : int ) -> Any: __magic_name__: List[Any] = HfArgumentParser(_a ) __magic_name__: Optional[int] = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=_a , required=_a ) expected.add_argument("""--required_str""" , type=_a , required=_a ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=_a , ) self.argparsersEqual(_a , _a ) def lowerCamelCase__ ( self : Optional[Any] ) -> int: __magic_name__: Optional[Any] = HfArgumentParser(_a ) __magic_name__: Optional[int] = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=_a , required=_a ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=_a , ) expected.add_argument("""--opt""" , type=_a , default=_a ) expected.add_argument("""--baz""" , default="""toto""" , type=_a , help="""help message""" ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=_a ) self.argparsersEqual(_a , _a ) def lowerCamelCase__ ( self : Dict ) -> Dict: __magic_name__: Dict = HfArgumentParser(_a ) __magic_name__: Union[str, Any] = { """foo""": 1_2, """bar""": 3.14, """baz""": """42""", """flag""": True, } __magic_name__: List[Any] = parser.parse_dict(_a )[0] __magic_name__: str = BasicExample(**_a ) self.assertEqual(_a , _a ) def lowerCamelCase__ ( self : Dict ) -> Optional[Any]: __magic_name__: Optional[Any] = HfArgumentParser(_a ) __magic_name__: str = { """foo""": 1_2, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 4_2, } self.assertRaises(_a , parser.parse_dict , _a , allow_extra_keys=_a ) def lowerCamelCase__ ( self : Optional[int] ) -> int: __magic_name__: Optional[int] = HfArgumentParser(_a ) __magic_name__: Any = { """foo""": 1_2, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__: str = os.path.join(_a , """temp_json""" ) os.mkdir(_a ) with open(temp_local_path + """.json""" , """w+""" ) as f: json.dump(_a , _a ) __magic_name__: Union[str, Any] = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] __magic_name__: Optional[Any] = BasicExample(**_a ) self.assertEqual(_a , _a ) def lowerCamelCase__ ( self : str ) -> List[str]: __magic_name__: Optional[Any] = HfArgumentParser(_a ) __magic_name__: Any = { """foo""": 1_2, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__: int = os.path.join(_a , """temp_yaml""" ) os.mkdir(_a ) with open(temp_local_path + """.yaml""" , """w+""" ) as f: yaml.dump(_a , _a ) __magic_name__: List[Any] = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] __magic_name__: int = BasicExample(**_a ) self.assertEqual(_a , _a ) def lowerCamelCase__ ( self : Optional[int] ) -> Dict: __magic_name__: str = HfArgumentParser(_a ) self.assertIsNotNone(_a )
96
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
0
"""simple docstring""" from __future__ import annotations _SCREAMING_SNAKE_CASE = 1.60_21E-19 # units = C def __UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> tuple[str, float]: """simple docstring""" if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("You cannot supply more or less than 2 values" ) elif conductivity < 0: raise ValueError("Conductivity cannot be negative" ) elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative" ) elif mobility < 0: raise ValueError("mobility cannot be negative" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
163
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 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 (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [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 _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , 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( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = 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 _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 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 _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 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""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
0
'''simple docstring''' import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "encoder.layer_norm_for_extract": "layer_norm_for_extract", "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", "label_embs_concat": "label_embeddings_concat", "mask_emb": "masked_spec_embed", "spk_proj": "speaker_proj", } UpperCAmelCase_ = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "label_embeddings_concat", "speaker_proj", "layer_norm_for_extract", ] def SCREAMING_SNAKE_CASE ( a_ : Tuple , a_ : Optional[int] , a_ : int , a_ : int , a_ : int ): for attribute in key.split('.' ): __a = getattr(__lowerCAmelCase , __lowerCAmelCase ) if weight_type is not None: __a = getattr(__lowerCAmelCase , __lowerCAmelCase ).shape else: __a = 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 = value elif weight_type == "weight_g": __a = value elif weight_type == "weight_v": __a = value elif weight_type == "bias": __a = value else: __a = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def SCREAMING_SNAKE_CASE ( a_ : str , a_ : List[str] ): __a = [] __a = fairseq_model.state_dict() __a = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): __a = False if "conv_layers" in name: load_conv_layer( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , hf_model.config.feat_extract_norm == 'group' , ) __a = True else: for key, mapped_key in MAPPING.items(): __a = """unispeech_sat.""" + 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]: if "layer_norm_for_extract" in name and (".".join(name.split('.' )[:-1] ) != key): # special case since naming is very similar continue __a = True if "*" in mapped_key: __a = name.split(__lowerCAmelCase )[0].split('.' )[-2] __a = mapped_key.replace('*' , __lowerCAmelCase ) if "weight_g" in name: __a = """weight_g""" elif "weight_v" in name: __a = """weight_v""" elif "bias" in name: __a = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj __a = """weight""" else: __a = None set_recursively(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) continue if not is_used: unused_weights.append(__lowerCAmelCase ) logger.warning(f"Unused weights: {unused_weights}" ) def SCREAMING_SNAKE_CASE ( a_ : Optional[Any] , a_ : Union[str, Any] , a_ : Dict , a_ : Tuple , a_ : Any ): __a = full_name.split('conv_layers.' )[-1] __a = name.split('.' ) __a = int(items[0] ) __a = 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 = 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 = 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[layer_id].layer_norm.bias.data.shape} was found." ) __a = 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[layer_id].layer_norm.weight.data.shape} was found." ) __a = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(__lowerCAmelCase ) @torch.no_grad() def SCREAMING_SNAKE_CASE ( a_ : Any , a_ : Dict , a_ : List[str]=None , a_ : List[str]=None , a_ : str=True ): if config_path is not None: __a = UniSpeechSatConfig.from_pretrained(__lowerCAmelCase ) else: __a = UniSpeechSatConfig() __a = """""" if is_finetuned: __a = UniSpeechSatForCTC(__lowerCAmelCase ) else: __a = UniSpeechSatForPreTraining(__lowerCAmelCase ) __a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) __a = model[0].eval() recursively_load_weights(__lowerCAmelCase , __lowerCAmelCase ) hf_wavavec.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": UpperCAmelCase_ = 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_ = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
539
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
0
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging lowerCamelCase : Any =logging.get_logger(__name__) lowerCamelCase : Optional[Any] ="▁" lowerCamelCase : List[str] ={ "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } lowerCamelCase : Optional[Any] ={ "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } lowerCamelCase : Optional[int] ={ "facebook/m2m100_418M": 1024, } # fmt: off lowerCamelCase : Tuple ={ "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class __a ( UpperCamelCase_ ): _lowerCAmelCase : Any = VOCAB_FILES_NAMES _lowerCAmelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase : Optional[int] = ["""input_ids""", """attention_mask"""] _lowerCAmelCase : List[int] = [] _lowerCAmelCase : List[int] = [] def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Any=None , SCREAMING_SNAKE_CASE : Tuple=None , SCREAMING_SNAKE_CASE : Dict="<s>" , SCREAMING_SNAKE_CASE : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE : str="</s>" , SCREAMING_SNAKE_CASE : Any="<pad>" , SCREAMING_SNAKE_CASE : List[str]="<unk>" , SCREAMING_SNAKE_CASE : Optional[int]="m2m100" , SCREAMING_SNAKE_CASE : List[str] = None , SCREAMING_SNAKE_CASE : Dict=8 , **SCREAMING_SNAKE_CASE : Any , ): '''simple docstring''' UpperCamelCase__ : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs UpperCamelCase__ : List[str] = language_codes UpperCamelCase__ : Dict = FAIRSEQ_LANGUAGE_CODES[language_codes] UpperCamelCase__ : Tuple = {lang_code: F'__{lang_code}__' for lang_code in fairseq_language_code} UpperCamelCase__ : Optional[int] = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(_a ) for lang_code in fairseq_language_code if self.get_lang_token(_a ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=_a , tgt_lang=_a , bos_token=_a , eos_token=_a , sep_token=_a , unk_token=_a , pad_token=_a , language_codes=_a , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=_a , **_a , ) UpperCamelCase__ : List[str] = vocab_file UpperCamelCase__ : List[Any] = load_json(_a ) UpperCamelCase__ : List[Any] = {v: k for k, v in self.encoder.items()} UpperCamelCase__ : str = spm_file UpperCamelCase__ : List[Any] = load_spm(_a , self.sp_model_kwargs ) UpperCamelCase__ : Optional[int] = len(self.encoder ) UpperCamelCase__ : Union[str, Any] = { self.get_lang_token(_a ): self.encoder_size + i for i, lang_code in enumerate(_a ) } UpperCamelCase__ : List[str] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(_a )} UpperCamelCase__ : Dict = {v: k for k, v in self.lang_token_to_id.items()} UpperCamelCase__ : List[Any] = src_lang if src_lang is not None else """en""" UpperCamelCase__ : int = tgt_lang UpperCamelCase__ : List[Any] = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) UpperCamelCase__ : Tuple = num_madeup_words @property def __lowercase ( self : str ): '''simple docstring''' return len(self.encoder ) + len(self.lang_token_to_id ) @property def __lowercase ( self : Any ): '''simple docstring''' return self._src_lang @src_lang.setter def __lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE : List[str] ): '''simple docstring''' UpperCamelCase__ : Optional[Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE : List[str] ): '''simple docstring''' return self.sp_model.encode(_a , out_type=_a ) def __lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE : Union[str, Any] ): '''simple docstring''' if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(_a , self.encoder[self.unk_token] ) def __lowercase ( self : List[str] , SCREAMING_SNAKE_CASE : Dict ): '''simple docstring''' if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(_a , self.unk_token ) def __lowercase ( self : str , SCREAMING_SNAKE_CASE : Optional[Any] ): '''simple docstring''' UpperCamelCase__ : Optional[Any] = [] UpperCamelCase__ : Any = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_a ) + token UpperCamelCase__ : Optional[Any] = [] else: current_sub_tokens.append(_a ) out_string += self.sp_model.decode(_a ) return out_string.strip() def __lowercase ( self : Any , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : List[str] = None , SCREAMING_SNAKE_CASE : Tuple = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) UpperCamelCase__ : Tuple = [1] * len(self.prefix_tokens ) UpperCamelCase__ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(_a )) + suffix_ones return prefix_ones + ([0] * len(_a )) + ([0] * len(_a )) + suffix_ones def __lowercase ( self : int , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any] = None ): '''simple docstring''' if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __lowercase ( self : str ): '''simple docstring''' UpperCamelCase__ : str = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ): '''simple docstring''' UpperCamelCase__ : Optional[int] = self.__dict__.copy() UpperCamelCase__ : Optional[int] = None return state def __setstate__( self : str , SCREAMING_SNAKE_CASE : Optional[Any] ): '''simple docstring''' UpperCamelCase__ : Optional[Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCamelCase__ : List[Any] = {} UpperCamelCase__ : Optional[Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def __lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Dict = None ): '''simple docstring''' UpperCamelCase__ : Tuple = Path(_a ) if not save_dir.is_dir(): raise OSError(F'{save_directory} should be a directory' ) UpperCamelCase__ : Tuple = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""] ) UpperCamelCase__ : List[str] = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""] ) save_json(self.encoder , _a ) if os.path.abspath(self.spm_file ) != os.path.abspath(_a ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , _a ) elif not os.path.isfile(self.spm_file ): with open(_a , "wb" ) as fi: UpperCamelCase__ : int = self.sp_model.serialized_model_proto() fi.write(_a ) return (str(_a ), str(_a )) def __lowercase ( self : Tuple , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : List[str] = "en" , SCREAMING_SNAKE_CASE : List[str] = None , SCREAMING_SNAKE_CASE : List[Any] = "ro" , **SCREAMING_SNAKE_CASE : List[str] , ): '''simple docstring''' UpperCamelCase__ : Optional[int] = src_lang UpperCamelCase__ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(_a , _a , **_a ) def __lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : List[Any] , **SCREAMING_SNAKE_CASE : List[str] ): '''simple docstring''' if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) UpperCamelCase__ : Optional[Any] = src_lang UpperCamelCase__ : int = self(_a , add_special_tokens=_a , **_a ) UpperCamelCase__ : str = self.get_lang_id(_a ) UpperCamelCase__ : Any = tgt_lang_id return inputs def __lowercase ( self : Optional[Any] ): '''simple docstring''' self.set_src_lang_special_tokens(self.src_lang ) def __lowercase ( self : Dict ): '''simple docstring''' self.set_tgt_lang_special_tokens(self.tgt_lang ) def __lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE : List[Any] ): '''simple docstring''' UpperCamelCase__ : Tuple = self.get_lang_token(_a ) UpperCamelCase__ : str = self.lang_token_to_id[lang_token] UpperCamelCase__ : Optional[int] = [self.cur_lang_id] UpperCamelCase__ : Optional[Any] = [self.eos_token_id] def __lowercase ( self : List[str] , SCREAMING_SNAKE_CASE : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ : List[Any] = self.get_lang_token(_a ) UpperCamelCase__ : Any = self.lang_token_to_id[lang_token] UpperCamelCase__ : Dict = [self.cur_lang_id] UpperCamelCase__ : List[Any] = [self.eos_token_id] def __lowercase ( self : int , SCREAMING_SNAKE_CASE : Tuple ): '''simple docstring''' return self.lang_code_to_token[lang] def __lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE : Dict ): '''simple docstring''' UpperCamelCase__ : Optional[int] = self.get_lang_token(_a ) return self.lang_token_to_id[lang_token] def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> sentencepiece.SentencePieceProcessor: UpperCamelCase__ : Dict = sentencepiece.SentencePieceProcessor(**__lowerCAmelCase ) spm.Load(str(__lowerCAmelCase ) ) return spm def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> Union[Dict, List]: with open(__lowerCAmelCase , "r" ) as f: return json.load(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> None: with open(__lowerCAmelCase , "w" ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase , indent=2 )
228
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
0
def _SCREAMING_SNAKE_CASE ( lowercase : Any , lowercase : Dict ): '''simple docstring''' return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def _SCREAMING_SNAKE_CASE ( lowercase : Union[str, Any] , lowercase : Any=0 ): '''simple docstring''' return sorted(__lowerCAmelCase , key=lambda lowercase : x[column] ) def _SCREAMING_SNAKE_CASE ( lowercase : Tuple , lowercase : Tuple , lowercase : Optional[Any]=float('inf' ) ): '''simple docstring''' for i in range(points_counts - 1 ): for j in range(i + 1 , __lowerCAmelCase ): lowerCamelCase_ = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: lowerCamelCase_ = current_dis return min_dis def _SCREAMING_SNAKE_CASE ( lowercase : Tuple , lowercase : Tuple , lowercase : List[str]=float('inf' ) ): '''simple docstring''' for i in range(min(6 , points_counts - 1 ) , __lowerCAmelCase ): for j in range(max(0 , i - 6 ) , __lowerCAmelCase ): lowerCamelCase_ = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: lowerCamelCase_ = current_dis return min_dis def _SCREAMING_SNAKE_CASE ( lowercase : str , lowercase : List[str] , lowercase : str ): '''simple docstring''' if points_counts <= 3: return dis_between_closest_pair(__lowerCAmelCase , __lowerCAmelCase ) # recursion lowerCamelCase_ = points_counts // 2 lowerCamelCase_ = closest_pair_of_points_sqr( __lowerCAmelCase , points_sorted_on_y[:mid] , __lowerCAmelCase ) lowerCamelCase_ = closest_pair_of_points_sqr( __lowerCAmelCase , points_sorted_on_y[mid:] , points_counts - mid ) lowerCamelCase_ = min(__lowerCAmelCase , __lowerCAmelCase ) lowerCamelCase_ = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis: cross_strip.append(__lowerCAmelCase ) lowerCamelCase_ = dis_between_closest_in_strip( __lowerCAmelCase , len(__lowerCAmelCase ) , __lowerCAmelCase ) return min(__lowerCAmelCase , __lowerCAmelCase ) def _SCREAMING_SNAKE_CASE ( lowercase : Optional[Any] , lowercase : int ): '''simple docstring''' lowerCamelCase_ = column_based_sort(__lowerCAmelCase , column=0 ) lowerCamelCase_ = column_based_sort(__lowerCAmelCase , column=1 ) return ( closest_pair_of_points_sqr( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) ) ** 0.5 if __name__ == "__main__": lowerCamelCase : List[str] = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
70
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : 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=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
0
"""simple docstring""" import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all LED models at https://huggingface.co/models?filter=LED UpperCamelCase__ = { "vocab_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", }, "merges_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt", }, "tokenizer_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json", }, } UpperCamelCase__ = { "allenai/led-base-16384": 1_63_84, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def lowerCamelCase ( ): UpperCAmelCase__ : List[Any] = ( list(range(ord('!' ) ,ord('~' ) + 1 ) ) + list(range(ord('¡' ) ,ord('¬' ) + 1 ) ) + list(range(ord('®' ) ,ord('ÿ' ) + 1 ) ) ) UpperCAmelCase__ : Optional[int] = bs[:] UpperCAmelCase__ : List[Any] = 0 for b in range(2**8 ): if b not in bs: bs.append(__lowerCAmelCase ) cs.append(2**8 + n ) n += 1 UpperCAmelCase__ : List[Any] = [chr(__lowerCAmelCase ) for n in cs] return dict(zip(__lowerCAmelCase ,__lowerCAmelCase ) ) def lowerCamelCase ( _snake_case ): UpperCAmelCase__ : int = set() UpperCAmelCase__ : Optional[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCAmelCase__ : Optional[Any] = char return pairs class a ( UpperCamelCase_ ): UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Tuple = ["""input_ids""", """attention_mask"""] def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_="replace" , UpperCamelCase_="<s>" , UpperCamelCase_="</s>" , UpperCamelCase_="</s>" , UpperCamelCase_="<s>" , UpperCamelCase_="<unk>" , UpperCamelCase_="<pad>" , UpperCamelCase_="<mask>" , UpperCamelCase_=False , **UpperCamelCase_ , ): UpperCAmelCase__ : List[Any] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else bos_token UpperCAmelCase__ : Dict = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else eos_token UpperCAmelCase__ : int = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else sep_token UpperCAmelCase__ : List[str] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else cls_token UpperCAmelCase__ : Dict = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else unk_token UpperCAmelCase__ : List[str] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase__ : Optional[Any] = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( errors=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , **_a , ) with open(_a , encoding='utf-8' ) as vocab_handle: UpperCAmelCase__ : int = json.load(_a ) UpperCAmelCase__ : Any = {v: k for k, v in self.encoder.items()} UpperCAmelCase__ : List[Any] = errors # how to handle errors in decoding UpperCAmelCase__ : Union[str, Any] = bytes_to_unicode() UpperCAmelCase__ : List[Any] = {v: k for k, v in self.byte_encoder.items()} with open(_a , encoding='utf-8' ) as merges_handle: UpperCAmelCase__ : Optional[Any] = merges_handle.read().split('\n' )[1:-1] UpperCAmelCase__ : Dict = [tuple(merge.split() ) for merge in bpe_merges] UpperCAmelCase__ : str = dict(zip(_a , range(len(_a ) ) ) ) UpperCAmelCase__ : Union[str, Any] = {} UpperCAmelCase__ : Optional[int] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions UpperCAmelCase__ : Optional[Any] = re.compile(R'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def __snake_case ( self ): return len(self.encoder ) def __snake_case ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def __snake_case ( self , UpperCamelCase_ ): if token in self.cache: return self.cache[token] UpperCAmelCase__ : int = tuple(_a ) UpperCAmelCase__ : Union[str, Any] = get_pairs(_a ) if not pairs: return token while True: UpperCAmelCase__ : Optional[Any] = min(_a , key=lambda UpperCamelCase_ : self.bpe_ranks.get(_a , float('inf' ) ) ) if bigram not in self.bpe_ranks: break UpperCAmelCase__ : int = bigram UpperCAmelCase__ : Optional[Any] = [] UpperCAmelCase__ : List[str] = 0 while i < len(_a ): try: UpperCAmelCase__ : Tuple = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) UpperCAmelCase__ : List[str] = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 UpperCAmelCase__ : str = tuple(_a ) UpperCAmelCase__ : List[str] = new_word if len(_a ) == 1: break else: UpperCAmelCase__ : Optional[Any] = get_pairs(_a ) UpperCAmelCase__ : Any = """ """.join(_a ) UpperCAmelCase__ : Optional[int] = word return word def __snake_case ( self , UpperCamelCase_ ): UpperCAmelCase__ : Union[str, Any] = [] for token in re.findall(self.pat , _a ): UpperCAmelCase__ : Tuple = """""".join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a ).split(' ' ) ) return bpe_tokens def __snake_case ( self , UpperCamelCase_ ): return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def __snake_case ( self , UpperCamelCase_ ): return self.decoder.get(_a ) def __snake_case ( self , UpperCamelCase_ ): UpperCAmelCase__ : int = """""".join(_a ) UpperCAmelCase__ : Tuple = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): if not os.path.isdir(_a ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return UpperCAmelCase__ : Any = os.path.join( _a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) UpperCAmelCase__ : List[Any] = os.path.join( _a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(_a , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + '\n' ) UpperCAmelCase__ : Dict = 0 with open(_a , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda UpperCamelCase_ : kv[1] ): if index != token_index: logger.warning( F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ' Please check that the tokenizer is not corrupted!' ) UpperCAmelCase__ : Optional[Any] = token_index writer.write(' '.join(_a ) + '\n' ) index += 1 return vocab_file, merge_file def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase__ : List[str] = [self.cls_token_id] UpperCAmelCase__ : Any = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = 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 ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): UpperCAmelCase__ : Optional[Any] = [self.sep_token_id] UpperCAmelCase__ : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_=False , **UpperCamelCase_ ): UpperCAmelCase__ : Optional[int] = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_a ) > 0 and not text[0].isspace()): UpperCAmelCase__ : int = """ """ + text return (text, kwargs) def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = PaddingStrategy.DO_NOT_PAD , UpperCamelCase_ = None , UpperCamelCase_ = None , ): UpperCAmelCase__ : Dict = super()._pad( encoded_inputs=_a , max_length=_a , padding_strategy=_a , pad_to_multiple_of=_a , return_attention_mask=_a , ) # Load from model defaults if return_attention_mask is None: UpperCAmelCase__ : Dict = """attention_mask""" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: UpperCAmelCase__ : int = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. UpperCAmelCase__ : List[str] = len(encoded_inputs['global_attention_mask'] ) != len(_a ) if needs_to_be_padded: UpperCAmelCase__ : Union[str, Any] = len(_a ) - len(encoded_inputs['global_attention_mask'] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` UpperCAmelCase__ : List[Any] = ( encoded_inputs["""global_attention_mask"""] + [-1] * difference ) elif self.padding_side == "left": UpperCAmelCase__ : List[str] = [-1] * difference + encoded_inputs[ """global_attention_mask""" ] else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return encoded_inputs
110
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
0
"""simple docstring""" import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) lowerCAmelCase : List[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , ) return model def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Optional[Any] = self.dummy_uncond_unet lowerCAmelCase : List[Any] = PNDMScheduler() lowerCAmelCase : Union[str, Any] = PNDMPipeline(unet=_a , scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) lowerCAmelCase : List[str] = torch.manual_seed(0 ) lowerCAmelCase : Optional[Any] = pndm(generator=_a , num_inference_steps=20 , output_type="numpy" ).images lowerCAmelCase : Optional[int] = torch.manual_seed(0 ) lowerCAmelCase : List[Any] = pndm(generator=_a , num_inference_steps=20 , output_type="numpy" , return_dict=_a )[0] lowerCAmelCase : int = image[0, -3:, -3:, -1] lowerCAmelCase : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCAmelCase : List[Any] = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : List[Any] = """google/ddpm-cifar10-32""" lowerCAmelCase : str = UNetaDModel.from_pretrained(_a ) lowerCAmelCase : Dict = PNDMScheduler() lowerCAmelCase : Any = PNDMPipeline(unet=_a , scheduler=_a ) pndm.to(_a ) pndm.set_progress_bar_config(disable=_a ) lowerCAmelCase : List[str] = torch.manual_seed(0 ) lowerCAmelCase : Any = pndm(generator=_a , output_type="numpy" ).images lowerCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCAmelCase : str = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
645
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[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(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
0
from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class lowerCAmelCase__ ( UpperCamelCase_ ): A_ : Dict = """openai/whisper-base""" A_ : Dict = ( """This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """ """transcribed text.""" ) A_ : List[str] = """transcriber""" A_ : Optional[int] = WhisperProcessor A_ : List[str] = WhisperForConditionalGeneration A_ : Dict = ["""audio"""] A_ : str = ["""text"""] def __UpperCamelCase ( self : List[str] , __UpperCamelCase : Any ) -> int: return self.pre_processor(_a , return_tensors='pt' ).input_features def __UpperCamelCase ( self : Dict , __UpperCamelCase : int ) -> Optional[int]: return self.model.generate(inputs=_a ) def __UpperCamelCase ( self : Optional[Any] , __UpperCamelCase : Optional[Any] ) -> Any: return self.pre_processor.batch_decode(_a , skip_special_tokens=_a )[0]
106
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
0
def snake_case (UpperCamelCase : Optional[int] ): '''simple docstring''' return "".join([hex(__lowerCAmelCase )[2:].zfill(2 ).upper() for byte in list(__lowerCAmelCase )] ) def snake_case (UpperCamelCase : List[str] ): '''simple docstring''' if (len(__lowerCAmelCase ) % 2) != 0: raise ValueError( """Base16 encoded data is invalid: Data does not have an even number of hex digits.""" ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(__lowerCAmelCase ) <= set("""0123456789ABCDEF""" ): raise ValueError( """Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters.""" ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(__lowerCAmelCase ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
165
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
0
def _a ( __lowercase ) -> int: """simple docstring""" assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F"""number_of_steps needs to be positive integer, your input {number_of_steps}""" if number_of_steps == 1: return 1 __UpperCamelCase = 1, 1 for _ in range(number_of_steps - 1 ): __UpperCamelCase = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
383
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
0
import argparse from collections import defaultdict import yaml A = "docs/source/en/_toctree.yml" def a(lowercase__ ): '''simple docstring''' snake_case_ = defaultdict(__lowerCAmelCase ) snake_case_ = [] snake_case_ = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({'local': doc['local'], 'title': doc['title']} ) else: new_doc_list.append(__lowerCAmelCase ) snake_case_ = new_doc_list snake_case_ = [key for key, value in counts.items() if value > 1] snake_case_ = [] for duplicate_key in duplicates: snake_case_ = list({doc['title'] for doc in doc_list if doc['local'] == duplicate_key} ) if len(__lowerCAmelCase ) > 1: raise ValueError( f"""{duplicate_key} is present several times in the documentation table of content at """ '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ' 'others.' ) # Only add this once new_doc.append({'local': duplicate_key, 'title': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if 'local' not in counts or counts[doc['local']] == 1] ) snake_case_ = sorted(__lowerCAmelCase , key=lambda lowercase__ : s["title"].lower() ) # "overview" gets special treatment and is always first if len(__lowerCAmelCase ) > 1: raise ValueError('{doc_list} has two \'overview\' docs which is not allowed.' ) overview_doc.extend(__lowerCAmelCase ) # Sort return overview_doc def a(lowercase__=False ): '''simple docstring''' with open(__lowerCAmelCase , encoding='utf-8' ) as f: snake_case_ = yaml.safe_load(f.read() ) # Get to the API doc snake_case_ = 0 while content[api_idx]["title"] != "API": api_idx += 1 snake_case_ = content[api_idx]["""sections"""] # Then to the model doc snake_case_ = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 snake_case_ = api_doc[scheduler_idx]["""sections"""] snake_case_ = clean_doc_toc(__lowerCAmelCase ) snake_case_ = False if new_scheduler_doc != scheduler_doc: snake_case_ = True if overwrite: snake_case_ = new_scheduler_doc if diff: if overwrite: snake_case_ = api_doc with open(__lowerCAmelCase , 'w' , encoding='utf-8' ) as f: f.write(yaml.dump(__lowerCAmelCase , allow_unicode=__lowerCAmelCase ) ) else: raise ValueError( 'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' ) def a(lowercase__=False ): '''simple docstring''' with open(__lowerCAmelCase , encoding='utf-8' ) as f: snake_case_ = yaml.safe_load(f.read() ) # Get to the API doc snake_case_ = 0 while content[api_idx]["title"] != "API": api_idx += 1 snake_case_ = content[api_idx]["""sections"""] # Then to the model doc snake_case_ = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 snake_case_ = False snake_case_ = api_doc[pipeline_idx]["""sections"""] snake_case_ = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: snake_case_ = pipeline_doc["""section"""] snake_case_ = clean_doc_toc(__lowerCAmelCase ) if overwrite: snake_case_ = new_sub_pipeline_doc new_pipeline_docs.append(__lowerCAmelCase ) # sort overall pipeline doc snake_case_ = clean_doc_toc(__lowerCAmelCase ) if new_pipeline_docs != pipeline_docs: snake_case_ = True if overwrite: snake_case_ = new_pipeline_docs if diff: if overwrite: snake_case_ = api_doc with open(__lowerCAmelCase , 'w' , encoding='utf-8' ) as f: f.write(yaml.dump(__lowerCAmelCase , allow_unicode=__lowerCAmelCase ) ) else: raise ValueError( 'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' ) if __name__ == "__main__": A = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') A = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
187
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
0
"""simple docstring""" import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers __lowerCamelCase = float('nan') class __A : def __init__( self : Union[str, Any] , __snake_case : Optional[Any] ) -> int: __magic_name__: Optional[int] = sys.stdout __magic_name__: int = open(_a , """a""" ) def __getattr__( self : str , __snake_case : Union[str, Any] ) -> List[Any]: return getattr(self.stdout , _a ) def lowerCamelCase__ ( self : Tuple , __snake_case : Any ) -> Optional[int]: self.stdout.write(_a ) # strip tqdm codes self.file.write(re.sub(R"""^.*\r""" , """""" , _a , 0 , re.M ) ) def a ( __UpperCAmelCase : List[str]=8_0 , __UpperCAmelCase : List[Any]=False ) -> Dict: __magic_name__: str = [] # deal with critical env vars __magic_name__: Tuple = ["""CUDA_VISIBLE_DEVICES"""] for key in env_keys: __magic_name__: Tuple = os.environ.get(__lowerCAmelCase , __lowerCAmelCase ) if val is not None: cmd.append(f'{key}={val}' ) # python executable (not always needed if the script is executable) __magic_name__: int = sys.executable if full_python_path else sys.executable.split("""/""" )[-1] cmd.append(__lowerCAmelCase ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes __magic_name__: List[Any] = [] __magic_name__: Dict = """""" while len(__lowerCAmelCase ) > 0: current_line += f'{cmd.pop(0 )} ' if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(__lowerCAmelCase ) __magic_name__: List[str] = """""" return "\\\n".join(__lowerCAmelCase ) def a ( __UpperCAmelCase : List[str] , __UpperCAmelCase : Union[str, Any] ) -> Optional[int]: # unwrap multi-line input __magic_name__: Union[str, Any] = re.sub(R"""[\\\n]+""" , """ """ , args.base_cmd ) # remove --output_dir if any and set our own __magic_name__: int = re.sub("""--output_dir\s+[^\s]+""" , """""" , args.base_cmd ) args.base_cmd += f' --output_dir {output_dir}' # ensure we have --overwrite_output_dir __magic_name__: str = re.sub("""--overwrite_output_dir\s+""" , """""" , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def a ( __UpperCAmelCase : Dict , __UpperCAmelCase : Any , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[Any] ) -> Any: # Enable to debug everything but the run itself, to do it fast and see the progress. # This is useful for debugging the output formatting quickly - we can remove it later once # everybody is happy with the output if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 1_0_0 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 1_00.2, 55.66_66, 2_22.22_22_22_22] )} , ) __magic_name__: List[str] = subprocess.run(__lowerCAmelCase , capture_output=__lowerCAmelCase , text=__lowerCAmelCase ) if verbose: print("""STDOUT""" , result.stdout ) print("""STDERR""" , result.stderr ) # save the streams __magic_name__: Any = variation.replace(""" """ , """-""" ) with open(Path(__lowerCAmelCase ) / f'log.{prefix}.stdout.txt' , """w""" ) as f: f.write(result.stdout ) with open(Path(__lowerCAmelCase ) / f'log.{prefix}.stderr.txt' , """w""" ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print("""failed""" ) return {target_metric_key: nan} with io.open(f'{output_dir}/all_results.json' , """r""" , encoding="""utf-8""" ) as f: __magic_name__: Optional[Any] = json.load(__lowerCAmelCase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def a ( __UpperCAmelCase : List[str] , __UpperCAmelCase : int , __UpperCAmelCase : Dict , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : int , __UpperCAmelCase : Tuple , __UpperCAmelCase : int , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[int] , ) -> List[str]: __magic_name__: int = [] __magic_name__: int = [] __magic_name__: Optional[Any] = f'{id}: {variation:<{longest_variation_len}}' __magic_name__: Any = f'{preamble}: ' __magic_name__: Optional[Any] = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(__lowerCAmelCase ) , desc=__lowerCAmelCase , leave=__lowerCAmelCase ): __magic_name__: Tuple = process_run_single( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __magic_name__: List[str] = single_run_metrics[target_metric_key] if not math.isnan(__lowerCAmelCase ): metrics.append(__lowerCAmelCase ) results.append(__lowerCAmelCase ) outcome += "✓" else: outcome += "✘" __magic_name__: List[Any] = f'\33[2K\r{outcome}' if len(__lowerCAmelCase ) > 0: __magic_name__: Optional[int] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} __magic_name__: Dict = round(mean_metrics[target_metric_key] , 2 ) __magic_name__: Optional[int] = f'{outcome} {mean_target}' if len(__lowerCAmelCase ) > 1: results_str += f' {tuple(round(__lowerCAmelCase , 2 ) for x in results )}' print(__lowerCAmelCase ) __magic_name__: List[str] = variation return mean_metrics else: print(__lowerCAmelCase ) return {variation_key: variation, target_metric_key: nan} def a ( ) -> str: __magic_name__: List[str] = torch.cuda.get_device_properties(torch.device("""cuda""" ) ) return f'\nDatetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**3_0:0.2f}GB\n' def a ( __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : str ) -> Union[str, Any]: __magic_name__: Dict = pd.DataFrame(__lowerCAmelCase ) __magic_name__: List[Any] = """variation""" __magic_name__: Dict = """diff_%""" __magic_name__: int = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan __magic_name__: Tuple = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(__lowerCAmelCase ): # as a fallback, use the minimal value as the sentinel __magic_name__: Union[str, Any] = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(__lowerCAmelCase ): __magic_name__: int = df.apply( lambda __UpperCAmelCase : round(1_0_0 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis="""columns""" , ) # re-order columns __magic_name__: Optional[Any] = [variation_key, target_metric_key, diff_key, *report_metric_keys] __magic_name__: Any = df.reindex(__lowerCAmelCase , axis="""columns""" ) # reorder cols # capitalize __magic_name__: Optional[int] = df.rename(str.capitalize , axis="""columns""" ) # make the cols as narrow as possible __magic_name__: List[Any] = df.rename(lambda __UpperCAmelCase : c.replace("""_""" , """<br>""" ) , axis="""columns""" ) __magic_name__: int = df.rename(lambda __UpperCAmelCase : c.replace("""_""" , """\n""" ) , axis="""columns""" ) __magic_name__: int = ["""""", """Copy between the cut-here-lines and paste as is to github or a forum"""] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=__lowerCAmelCase , floatfmt=""".2f""" )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=__lowerCAmelCase , floatfmt=""".2f""" )] print("""\n\n""".join(__lowerCAmelCase ) ) def a ( ) -> Any: __magic_name__: List[str] = argparse.ArgumentParser() parser.add_argument( """--base-cmd""" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="""Base cmd""" , ) parser.add_argument( """--variations""" , default=__lowerCAmelCase , type=__lowerCAmelCase , nargs="""+""" , required=__lowerCAmelCase , help="""Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'""" , ) parser.add_argument( """--base-variation""" , default=__lowerCAmelCase , type=__lowerCAmelCase , help="""Baseline variation to compare to. if None the minimal target value will be used to compare against""" , ) parser.add_argument( """--target-metric-key""" , default=__lowerCAmelCase , type=__lowerCAmelCase , required=__lowerCAmelCase , help="""Target metric key in output_dir/all_results.json, e.g., train_samples_per_second""" , ) parser.add_argument( """--report-metric-keys""" , default="""""" , type=__lowerCAmelCase , help="""Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., 'train_loss train_samples""" , ) parser.add_argument( """--repeat-times""" , default=1 , type=__lowerCAmelCase , help="""How many times to re-run each variation - an average will be reported""" , ) parser.add_argument( """--output_dir""" , default="""output_benchmark""" , type=__lowerCAmelCase , help="""The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked""" , ) parser.add_argument( """--verbose""" , default=__lowerCAmelCase , action="""store_true""" , help="""Whether to show the outputs of each run or just the benchmark progress""" , ) __magic_name__: List[Any] = parser.parse_args() __magic_name__: Tuple = args.output_dir Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) __magic_name__: Optional[int] = get_base_command(__lowerCAmelCase , __lowerCAmelCase ) # split each dimension into its --foo variations __magic_name__: Dict = [list(map(str.strip , re.split(R"""\|""" , __lowerCAmelCase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty __magic_name__: Union[str, Any] = list(map(str.strip , map(""" """.join , itertools.product(*__lowerCAmelCase ) ) ) ) __magic_name__: str = max(len(__lowerCAmelCase ) for x in variations ) # split wanted keys __magic_name__: Union[str, Any] = args.report_metric_keys.split() # capture prints into a log file for convenience __magic_name__: Dict = f'benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt' print(f'\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt' ) print(f'and this script\'s output is also piped into {report_fn}' ) __magic_name__: Optional[Any] = Tee(__lowerCAmelCase ) print(f'\n*** Running {len(__lowerCAmelCase )} benchmarks:' ) print(f'Base command: {" ".join(__lowerCAmelCase )}' ) __magic_name__: Union[str, Any] = """variation""" __magic_name__: Dict = [] for id, variation in enumerate(tqdm(__lowerCAmelCase , desc="""Total completion: """ , leave=__lowerCAmelCase ) ): __magic_name__: Dict = base_cmd + variation.split() results.append( process_run( id + 1 , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , args.target_metric_key , __lowerCAmelCase , args.repeat_times , __lowerCAmelCase , args.verbose , ) ) process_results(__lowerCAmelCase , args.target_metric_key , __lowerCAmelCase , args.base_variation , __lowerCAmelCase ) if __name__ == "__main__": main()
96
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
0
"""simple docstring""" import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch _SCREAMING_SNAKE_CASE = "sshleifer/bart-tiny-random" _SCREAMING_SNAKE_CASE = "patrickvonplaten/t5-tiny-random" @require_torch class __magic_name__ ( unittest.TestCase ): @cached_property def lowerCAmelCase ( self : List[Any] ): return AutoConfig.from_pretrained(_a ) def lowerCAmelCase ( self : Optional[int] ): __snake_case = create_student_by_copying_alternating_layers(_a , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.num_hidden_layers , 1 ) def lowerCAmelCase ( self : Optional[int] ): __snake_case = create_student_by_copying_alternating_layers(_a , tempfile.mkdtemp() , e=1 , d=_a ) def lowerCAmelCase ( self : Tuple ): __snake_case = create_student_by_copying_alternating_layers(_a , tempfile.mkdtemp() , e=1 , d=_a ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers ) def lowerCAmelCase ( self : Any ): __snake_case = create_student_by_copying_alternating_layers(_a , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , 1 ) def lowerCAmelCase ( self : Any ): with self.assertRaises(_a ): create_student_by_copying_alternating_layers(_a , tempfile.mkdtemp() , e=_a , d=_a )
163
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() a :Any = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) a :str = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.weight', f'encoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.encoder.layers.{i}.self_attn.out_proj.bias', f'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.weight', f'encoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear1.bias', f'encoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.weight', f'encoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.linear2.bias', f'encoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.encoder.layers.{i}.norm1.weight', f'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.encoder.layers.{i}.norm1.bias', f'encoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.weight', f'encoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.encoder.layers.{i}.norm2.bias', f'encoder.layers.{i}.final_layer_norm.bias')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.weight', f'decoder.layers.{i}.self_attn.out_proj.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.self_attn.out_proj.bias', f'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', f'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( f'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', f'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.weight', f'decoder.layers.{i}.fc1.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear1.bias', f'decoder.layers.{i}.fc1.bias')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.weight', f'decoder.layers.{i}.fc2.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.linear2.bias', f'decoder.layers.{i}.fc2.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm1.weight', f'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm1.bias', f'decoder.layers.{i}.self_attn_layer_norm.bias')) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.weight', f'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (f'transformer.decoder.layers.{i}.norm2.bias', f'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.weight', f'decoder.layers.{i}.final_layer_norm.weight')) rename_keys.append((f'transformer.decoder.layers.{i}.norm3.bias', f'decoder.layers.{i}.final_layer_norm.bias')) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.encoder.norm.weight", "encoder.layernorm.weight"), ("transformer.encoder.norm.bias", "encoder.layernorm.bias"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : str = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" ) SCREAMING_SNAKE_CASE__ : Dict = value else: SCREAMING_SNAKE_CASE__ : Tuple = value return new_state_dict def _lowercase ( __lowerCAmelCase ) -> int: SCREAMING_SNAKE_CASE__ : str = """""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000 SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: logger.info("""Converting model...""" ) # load original state dict SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" ) # rename keys for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE__ : Optional[int] = """model.""" for key in state_dict.copy().keys(): if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = val # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerConfig( backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 15 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""} SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()} else: SCREAMING_SNAKE_CASE__ : Tuple = 125 SCREAMING_SNAKE_CASE__ : str = 6 SCREAMING_SNAKE_CASE__ : List[Any] = { 0: """table""", 1: """table column""", 2: """table row""", 3: """table column header""", 4: """table projected row header""", 5: """table spanning cell""", } SCREAMING_SNAKE_CASE__ : Any = idalabel SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor( format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 ) SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png""" SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase ) if "detection" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Push model to HF hub logger.info("""Pushing model to the hub...""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ( """microsoft/table-transformer-detection""" if """detection""" in checkpoint_url else """microsoft/table-transformer-structure-recognition""" ) model.push_to_hub(__lowerCAmelCase ) image_processor.push_to_hub(__lowerCAmelCase ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", type=str, choices=[ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth", "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth", ], help="URL of the Table Transformer checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a :int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
680
0
'''simple docstring''' def SCREAMING_SNAKE_CASE ( a_ : Union[str, Any] = 200_0000 ): __a = [0 for i in range(n + 1 )] __a = 1 __a = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): __a = 1 __a = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f"""{solution() = }""")
539
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __a : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=0 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : str = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : int = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Any = scope SCREAMING_SNAKE_CASE__ : int = projection_dim def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Any = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) SCREAMING_SNAKE_CASE__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFDPRQuestionEncoder(config=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : List[str] = model(_a , token_type_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(_a ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _a ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFDPRReader(config=_a ) SCREAMING_SNAKE_CASE__ : Tuple = model(_a , attention_mask=_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) _SCREAMING_SNAKE_CASE :int = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Dict = False def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=_a , hidden_size=37 ) def _a ( self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*_a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*_a ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*_a ) @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFDPRContextEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(_a ) self.assertIsNotNone(_a ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = TFDPRReader.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_tf class __a (unittest.TestCase): '''simple docstring''' @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]] ) # [CLS] hello, is my dog cute? [SEP] SCREAMING_SNAKE_CASE__ : Tuple = model(_a )[0] # embedding shape = (1, 768) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ : Any = tf.constant( [ [ 0.03_236_253, 0.12_753_335, 0.16_818_509, 0.00_279_786, 0.3_896_933, 0.24_264_945, 0.2_178_971, -0.02_335_227, -0.08_481_959, -0.14_324_117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
680
0
import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> tuple: return (data["data"], data["target"]) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> XGBClassifier: UpperCamelCase__ : Optional[int] = XGBClassifier() classifier.fit(__lowerCAmelCase , __lowerCAmelCase ) return classifier def SCREAMING_SNAKE_CASE ( ) -> None: UpperCamelCase__ : int = load_iris() UpperCamelCase__ : Union[str, Any] = data_handling(__lowerCAmelCase ) UpperCamelCase__ : Optional[int] = train_test_split( __lowerCAmelCase , __lowerCAmelCase , test_size=0.2_5 ) UpperCamelCase__ : Optional[Any] = iris["""target_names"""] # Create an XGBoost Classifier from the training data UpperCamelCase__ : Tuple = xgboost(__lowerCAmelCase , __lowerCAmelCase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , display_labels=__lowerCAmelCase , cmap="Blues" , normalize="true" , ) plt.title("Normalized Confusion Matrix - IRIS Dataset" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
228
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :torch.FloatTensor _SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=0.999 , __lowerCAmelCase="cosine" , ) -> Union[str, Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCAmelCase ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCAmelCase ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for i in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE__ : int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCAmelCase ) / alpha_bar_fn(__lowerCAmelCase ) , __lowerCAmelCase ) ) return torch.tensor(__lowerCAmelCase , dtype=torch.floataa ) class __a (UpperCamelCase_ , UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = 1 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_001 , _a = 0.02 , _a = "linear" , _a = None , _a = True , _a = True , _a = 0 , _a = "epsilon" , _a = 1.0 , **_a , ) -> Dict: """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _a ) is not None: SCREAMING_SNAKE_CASE__ : Tuple = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _a , standard_warn=_a ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs["""set_alpha_to_one"""] if trained_betas is not None: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE__ : Optional[int] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE__ : Tuple = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1.0 - self.betas SCREAMING_SNAKE_CASE__ : List[Any] = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. SCREAMING_SNAKE_CASE__ : Any = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE__ : Tuple = 1.0 # setable values SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : List[str] = torch.from_numpy(np.arange(0 , _a ).copy().astype(np.intaa ) ) def _a ( self , _a , _a = None ) -> torch.FloatTensor: """simple docstring""" return sample def _a ( self , _a , _a = None ) -> Optional[int]: """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) SCREAMING_SNAKE_CASE__ : List[str] = num_inference_steps SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE__ : str = (np.arange(0 , _a ) * step_ratio).round().copy().astype(np.intaa ) SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(_a ).to(_a ) self.timesteps += self.config.steps_offset def _a ( self , _a , _a , _a , _a = 0.0 , _a = False , _a = None , _a = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process SCREAMING_SNAKE_CASE__ : Optional[int] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Optional[int] = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) SCREAMING_SNAKE_CASE__ : Any = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : int = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 SCREAMING_SNAKE_CASE__ : List[Any] = model_output elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE__ : Dict = model_output SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE__ : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_a , pred_original_sample=_a ) def __len__( self ) -> Dict: """simple docstring""" return self.config.num_train_timesteps
680
0
class A: '''simple docstring''' def __init__( self : List[str] , A_ : Optional[int] ) -> None: """simple docstring""" lowerCamelCase_ = len(_a ) lowerCamelCase_ = [0] * len_array if len_array > 0: lowerCamelCase_ = array[0] for i in range(1 , _a ): lowerCamelCase_ = self.prefix_sum[i - 1] + array[i] def a__ ( self : Dict , A_ : int , A_ : Any ) -> int: """simple docstring""" if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def a__ ( self : Optional[Any] , A_ : Dict ) -> bool: """simple docstring""" lowerCamelCase_ = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(_a ) return False if __name__ == "__main__": import doctest doctest.testmod()
70
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) a :Union[str, Any] = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys a :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = {"vocab_file": "sentencepiece.bpe.model"} UpperCamelCase__ = { "vocab_file": { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model", } } UpperCamelCase__ = { "camembert-base": 5_12, } UpperCamelCase__ = "▁" class a ( UpperCamelCase_ ): UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Union[str, Any] = ["""input_ids""", """attention_mask"""] def __init__( self , UpperCamelCase_ , UpperCamelCase_="<s>" , UpperCamelCase_="</s>" , UpperCamelCase_="</s>" , UpperCamelCase_="<s>" , UpperCamelCase_="<unk>" , UpperCamelCase_="<pad>" , UpperCamelCase_="<mask>" , UpperCamelCase_=["<s>NOTUSED", "</s>NOTUSED"] , UpperCamelCase_ = None , **UpperCamelCase_ , ): UpperCAmelCase__ : Tuple = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token UpperCAmelCase__ : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , additional_special_tokens=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) UpperCAmelCase__ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) UpperCAmelCase__ : Any = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> UpperCAmelCase__ : Optional[Any] = {"""<s>NOTUSED""": 0, """<pad>""": 1, """</s>NOTUSED""": 2, """<unk>""": 3} UpperCAmelCase__ : str = len(self.fairseq_tokens_to_ids ) UpperCAmelCase__ : Any = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) UpperCAmelCase__ : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase__ : Union[str, Any] = [self.cls_token_id] UpperCAmelCase__ : Optional[int] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = 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 ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): UpperCAmelCase__ : Optional[int] = [self.sep_token_id] UpperCAmelCase__ : 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] @property def __snake_case ( self ): return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def __snake_case ( self ): UpperCAmelCase__ : Optional[int] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __snake_case ( self , UpperCamelCase_ ): return self.sp_model.encode(_a , out_type=_a ) def __snake_case ( self , UpperCamelCase_ ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(_a ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(_a ) def __snake_case ( self , UpperCamelCase_ ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __snake_case ( self , UpperCamelCase_ ): UpperCAmelCase__ : str = [] UpperCAmelCase__ : Optional[int] = """""" UpperCAmelCase__ : Optional[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : str = [] else: current_sub_tokens.append(_a ) UpperCAmelCase__ : List[str] = False out_string += self.sp_model.decode(_a ) return out_string.strip() def __getstate__( self ): UpperCAmelCase__ : Tuple = self.__dict__.copy() UpperCAmelCase__ : Tuple = None return state def __setstate__( self , UpperCamelCase_ ): UpperCAmelCase__ : List[str] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): UpperCAmelCase__ : Dict = {} UpperCAmelCase__ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): if not os.path.isdir(_a ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return UpperCAmelCase__ : Optional[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 ) 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: UpperCAmelCase__ : Optional[int] = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
110
"""simple docstring""" import math import os import sys def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Union[str, Any] = """""" try: with open(__lowerCAmelCase , """rb""" ) as binary_file: SCREAMING_SNAKE_CASE__ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> None: lexicon.pop(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = last_match_id if math.loga(__lowerCAmelCase ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE__ : Dict = """0""" + lexicon[curr_key] SCREAMING_SNAKE_CASE__ : str = bin(__lowerCAmelCase )[2:] def _lowercase ( __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Dict = {"""0""": """0""", """1""": """1"""} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = """""", """""" SCREAMING_SNAKE_CASE__ : Any = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) index += 1 SCREAMING_SNAKE_CASE__ : List[str] = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE__ : List[Any] = lexicon[curr_string] result += last_match_id return result def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__ : Any = os.path.getsize(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = bin(__lowerCAmelCase )[2:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(__lowerCAmelCase ) return "0" * (length_length - 1) + file_length_binary + compressed def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Optional[int] = 8 try: with open(__lowerCAmelCase , """wb""" ) as opened_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ to_write[i : i + byte_length] for i in range(0 , len(__lowerCAmelCase ) , __lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: SCREAMING_SNAKE_CASE__ : Dict = read_file_binary(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = compress_data(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = add_file_length(__lowerCAmelCase , __lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
680
0
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow lowerCAmelCase__ = False class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" def lowercase__ ( self , snake_case__=32 ): """simple docstring""" set_seed(0 ) lowerCAmelCase : Any = UNetaDModel(sample_size=_a , in_channels=3 , out_channels=3 ) lowerCAmelCase : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.0001 ) return model, optimizer @slow def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : int = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable lowerCAmelCase : int = DDPMScheduler( num_train_timesteps=1_000 , beta_start=0.0001 , beta_end=0.02 , beta_schedule="linear" , clip_sample=_a , ) lowerCAmelCase : Optional[int] = DDIMScheduler( num_train_timesteps=1_000 , beta_start=0.0001 , beta_end=0.02 , beta_schedule="linear" , clip_sample=_a , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) lowerCAmelCase : Any = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(_a ) for _ in range(4 )] lowerCAmelCase : Dict = [torch.randn((4, 3, 32, 32) ).to(_a ) for _ in range(4 )] lowerCAmelCase : Any = [torch.randint(0 , 1_000 , (4,) ).long().to(_a ) for _ in range(4 )] # train with a DDPM scheduler lowerCAmelCase : Optional[Any] = self.get_model_optimizer(resolution=32 ) model.train().to(_a ) for i in range(4 ): optimizer.zero_grad() lowerCAmelCase : List[Any] = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCAmelCase : Optional[int] = model(_a , timesteps[i] ).sample lowerCAmelCase : Union[str, Any] = torch.nn.functional.mse_loss(_a , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM lowerCAmelCase : Any = self.get_model_optimizer(resolution=32 ) model.train().to(_a ) for i in range(4 ): optimizer.zero_grad() lowerCAmelCase : Optional[Any] = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCAmelCase : List[Any] = model(_a , timesteps[i] ).sample lowerCAmelCase : List[str] = torch.nn.functional.mse_loss(_a , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(_a , _a , atol=1e-5 ) ) self.assertTrue(torch.allclose(_a , _a , atol=1e-5 ) )
645
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Tuple = SamImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Dict = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : str = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Any = processor.post_process_masks(_a , _a , _a ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = processor.post_process_masks( _a , torch.tensor(_a ) , torch.tensor(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Dict = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Dict = [[1, 0], [0, 1]] with self.assertRaises(_a ): SCREAMING_SNAKE_CASE__ : Tuple = processor.post_process_masks(_a , np.array(_a ) , np.array(_a ) ) @require_vision @require_tf class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Any = image_processor(_a , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _a ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks(_a , _a , _a , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , tf.convert_to_tensor(_a ) , tf.convert_to_tensor(_a ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np SCREAMING_SNAKE_CASE__ : Optional[int] = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) SCREAMING_SNAKE_CASE__ : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ : str = processor.post_process_masks( _a , np.array(_a ) , np.array(_a ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Dict = SamImageProcessor() SCREAMING_SNAKE_CASE__ : Dict = SamProcessor(_a ) processor.save_pretrained(self.tmpdirname ) def _a ( self , **_a ) -> Any: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def _a ( self ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = [tf.convert_to_tensor(_a )] SCREAMING_SNAKE_CASE__ : Dict = [torch.tensor(_a )] SCREAMING_SNAKE_CASE__ : Optional[int] = [[1_764, 2_646]] SCREAMING_SNAKE_CASE__ : List[str] = [[683, 1_024]] SCREAMING_SNAKE_CASE__ : List[Any] = processor.post_process_masks( _a , _a , _a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : List[str] = processor.post_process_masks( _a , _a , _a , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[Any] = SamProcessor(image_processor=_a ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = image_processor(_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Any = processor(images=_a , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(_a , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ : str = processor(images=_a , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) ) self.assertTrue(np.allclose(_a , _a ) )
680
0
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device __snake_case :Optional[Any] =False class lowerCAmelCase__ ( unittest.TestCase ): pass @nightly @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def __UpperCamelCase ( self : Optional[int] ) -> Union[str, Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self : Any ) -> Any: A = VersatileDiffusionTextToImagePipeline.from_pretrained('shi-labs/versatile-diffusion' ) # remove text_unet pipe.remove_unused_weights() pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) A = """A painting of a squirrel eating a burger """ A = torch.manual_seed(0 ) A = pipe( prompt=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_a ) A = VersatileDiffusionTextToImagePipeline.from_pretrained(_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) A = generator.manual_seed(0 ) A = pipe( prompt=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: A = VersatileDiffusionTextToImagePipeline.from_pretrained( 'shi-labs/versatile-diffusion' , torch_dtype=torch.floataa ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) A = """A painting of a squirrel eating a burger """ A = torch.manual_seed(0 ) A = pipe( prompt=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' ).images A = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) A = np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
106
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :List[Any] = LayoutLMTokenizer _SCREAMING_SNAKE_CASE :Optional[int] = LayoutLMTokenizerFast _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[int] = True def _a ( self ) -> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ : 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 _a ( self , **_a ) -> Optional[int]: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def _a ( self , _a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = """UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE__ : Optional[Any] = """unwanted, running""" return input_text, output_text def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def _a ( self ) -> Optional[int]: """simple docstring""" pass
680
0
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging a__ : int = logging.get_logger(__name__) a__ : Any = {"vocab_file": "spiece.model"} a__ : Optional[Any] = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", } } a__ : str = { "xlnet-base-cased": None, "xlnet-large-cased": None, } # Segments (not really needed) a__ : Any = 0 a__ : Optional[int] = 1 a__ : Union[str, Any] = 2 a__ : str = 3 a__ : Union[str, Any] = 4 class lowercase ( UpperCamelCase_ ): """simple docstring""" snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = """left""" def __init__( self : Optional[Any] , a_ : int , a_ : str=False , a_ : List[str]=True , a_ : List[Any]=False , a_ : str="<s>" , a_ : Optional[int]="</s>" , a_ : Optional[int]="<unk>" , a_ : Tuple="<sep>" , a_ : Any="<pad>" , a_ : str="<cls>" , a_ : Union[str, Any]="<mask>" , a_ : List[str]=["<eop>", "<eod>"] , a_ : List[str] = None , **a_ : List[str] , ): """simple docstring""" lowerCamelCase__ = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token lowerCamelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , additional_special_tokens=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) lowerCamelCase__ = 3 lowerCamelCase__ = do_lower_case lowerCamelCase__ = remove_space lowerCamelCase__ = keep_accents lowerCamelCase__ = vocab_file lowerCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) @property def _UpperCamelCase ( self : List[str] ): """simple docstring""" return len(self.sp_model ) def _UpperCamelCase ( self : List[Any] ): """simple docstring""" lowerCamelCase__ = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ): """simple docstring""" lowerCamelCase__ = self.__dict__.copy() lowerCamelCase__ = None return state def __setstate__( self : str , a_ : Tuple ): """simple docstring""" lowerCamelCase__ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowerCamelCase__ = {} lowerCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self : Union[str, Any] , a_ : Optional[Any] ): """simple docstring""" if self.remove_space: lowerCamelCase__ = """ """.join(inputs.strip().split() ) else: lowerCamelCase__ = inputs lowerCamelCase__ = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: lowerCamelCase__ = unicodedata.normalize("""NFKD""" , _a ) lowerCamelCase__ = """""".join([c for c in outputs if not unicodedata.combining(_a )] ) if self.do_lower_case: lowerCamelCase__ = outputs.lower() return outputs def _UpperCamelCase ( self : List[Any] , a_ : Optional[int] ): """simple docstring""" lowerCamelCase__ = self.preprocess_text(_a ) lowerCamelCase__ = self.sp_model.encode(_a , out_type=_a ) lowerCamelCase__ = [] for piece in pieces: if len(_a ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): lowerCamelCase__ = self.sp_model.EncodeAsPieces(piece[:-1].replace(_a , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase__ = cur_pieces[1:] else: lowerCamelCase__ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_a ) else: new_pieces.append(_a ) return new_pieces def _UpperCamelCase ( self : Dict , a_ : int ): """simple docstring""" return self.sp_model.PieceToId(_a ) def _UpperCamelCase ( self : int , a_ : Tuple ): """simple docstring""" return self.sp_model.IdToPiece(_a ) def _UpperCamelCase ( self : Optional[int] , a_ : Tuple ): """simple docstring""" lowerCamelCase__ = """""".join(_a ).replace(_a , """ """ ).strip() return out_string def _UpperCamelCase ( self : Optional[Any] , a_ : Optional[int] , a_ : List[Any] = False , a_ : str = None , a_ : Optional[Any] = True , **a_ : Optional[int] , ): """simple docstring""" lowerCamelCase__ = kwargs.pop("""use_source_tokenizer""" , _a ) lowerCamelCase__ = self.convert_ids_to_tokens(_a , skip_special_tokens=_a ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCamelCase__ = [] lowerCamelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_a ) ) lowerCamelCase__ = [] sub_texts.append(_a ) else: current_sub_text.append(_a ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_a ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowerCamelCase__ = """""".join(_a ) lowerCamelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCamelCase__ = self.clean_up_tokenization(_a ) return clean_text else: return text def _UpperCamelCase ( self : Tuple , a_ : Dict , a_ : Tuple = None ): """simple docstring""" lowerCamelCase__ = [self.sep_token_id] lowerCamelCase__ = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _UpperCamelCase ( self : Union[str, Any] , a_ : Optional[int] , a_ : Optional[Any] = None , a_ : Any = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is not None: return ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1, 1] return ([0] * len(_a )) + [1, 1] def _UpperCamelCase ( self : str , a_ : str , a_ : Dict = None ): """simple docstring""" lowerCamelCase__ = [self.sep_token_id] lowerCamelCase__ = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _UpperCamelCase ( self : Union[str, Any] , a_ : str , a_ : Union[str, Any] = None ): """simple docstring""" if not os.path.isdir(_a ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase__ = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) 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: lowerCamelCase__ = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
165
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a :str = 16 a :Union[str, Any] = 32 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 16 ) -> Tuple: SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE__ : List[str] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : int = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : str = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Dict = 8 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None return tokenizer.pad( __lowerCAmelCase , padding="""longest""" , max_length=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : int = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders a :Dict = mocked_dataloaders # noqa: F811 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCAmelCase ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Optional[int] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__lowerCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config["""lr"""] SCREAMING_SNAKE_CASE__ : str = int(config["""num_epochs"""] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config["""seed"""] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config["""batch_size"""] ) SCREAMING_SNAKE_CASE__ : Any = evaluate.load("""glue""" , """mrpc""" ) set_seed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE__ : int = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = AdamW(params=model.parameters() , lr=__lowerCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Any = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCAmelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Now we train the model for epoch in range(__lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = output.loss accelerator.backward(__lowerCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , __lowerCAmelCase ) def _lowercase ( ) -> Any: SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCAmelCase , default=__lowerCAmelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__lowerCAmelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : int = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
680
0
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ = JukeboxTokenizer UpperCAmelCase__ = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def __lowercase( self ) -> Optional[Any]: import torch __UpperCamelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-1b-lyrics' ) __UpperCamelCase = tokenizer(**self.metas )["""input_ids"""] # fmt: off __UpperCamelCase = [ torch.tensor([[ 0, 0, 0, 7_169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1_069, 11]] ), torch.tensor([[0, 0, 0, 1_069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def __lowercase( self ) -> int: import torch __UpperCamelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-5b-lyrics' ) __UpperCamelCase = tokenizer(**self.metas )["""input_ids"""] # fmt: off __UpperCamelCase = [ torch.tensor([[ 0, 0, 0, 1_069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
383
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a :str = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a :str = [ "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 a :Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
680
0
from binascii import hexlify from hashlib import shaaaa from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 A = { # 1536-bit 5: { "prime": int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF', base=16, ), "generator": 2, }, # 2048-bit 14: { "prime": int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AACAA68FFFFFFFFFFFFFFFF', base=16, ), "generator": 2, }, # 3072-bit 15: { "prime": int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF', base=16, ), "generator": 2, }, # 4096-bit 16: { "prime": int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7' + '88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA' + '2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6' + '287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED' + '1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9' + '93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199' + 'FFFFFFFFFFFFFFFF', base=16, ), "generator": 2, }, # 6144-bit 17: { "prime": int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08' + '8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B' + '302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9' + 'A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6' + '49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8' + 'FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C' + '180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718' + '3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D' + '04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D' + 'B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226' + '1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC' + 'E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26' + '99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB' + '04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2' + '233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127' + 'D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492' + '36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406' + 'AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918' + 'DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151' + '2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03' + 'F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F' + 'BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA' + 'CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B' + 'B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632' + '387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E' + '6DCC4024FFFFFFFFFFFFFFFF', base=16, ), "generator": 2, }, # 8192-bit 18: { "prime": int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7' + '88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA' + '2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6' + '287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED' + '1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9' + '93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492' + '36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD' + 'F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831' + '179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B' + 'DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF' + '5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6' + 'D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3' + '23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA' + 'CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328' + '06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C' + 'DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE' + '12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4' + '38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300' + '741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568' + '3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9' + '22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B' + '4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A' + '062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36' + '4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1' + 'B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92' + '4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47' + '9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71' + '60C980DD98EDD3DFFFFFFFFFFFFFFFFF', base=16, ), "generator": 2, }, } class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self , __UpperCamelCase = 14 ): """simple docstring""" if group not in primes: raise ValueError('Unsupported Group' ) snake_case_ = primes[group]["""prime"""] snake_case_ = primes[group]["""generator"""] snake_case_ = int(hexlify(urandom(32 ) ) , base=16 ) def __lowerCAmelCase ( self ): """simple docstring""" return hex(self.__private_key )[2:] def __lowerCAmelCase ( self ): """simple docstring""" snake_case_ = pow(self.generator , self.__private_key , self.prime ) return hex(_a )[2:] def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" return ( 2 <= key <= self.prime - 2 and pow(_a , (self.prime - 1) // 2 , self.prime ) == 1 ) def __lowerCAmelCase ( self , __UpperCamelCase ): """simple docstring""" snake_case_ = int(_a , base=16 ) if not self.is_valid_public_key(_a ): raise ValueError('Invalid public key' ) snake_case_ = pow(_a , self.__private_key , self.prime ) return shaaaa(str(_a ).encode() ).hexdigest() @staticmethod def __lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return ( 2 <= remote_public_key_str <= prime - 2 and pow(_a , (prime - 1) // 2 , _a ) == 1 ) @staticmethod def __lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 14 ): """simple docstring""" snake_case_ = int(_a , base=16 ) snake_case_ = int(_a , base=16 ) snake_case_ = primes[group]["""prime"""] if not DiffieHellman.is_valid_public_key_static(_a , _a ): raise ValueError('Invalid public key' ) snake_case_ = pow(_a , _a , _a ) return shaaaa(str(_a ).encode() ).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()
187
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> int: assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
680
0
"""simple docstring""" import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class __A ( UpperCamelCase_ ): def lowerCamelCase__ ( self : Any ) -> List[str]: __magic_name__: List[str] = tempfile.mkdtemp() __magic_name__: List[Any] = 5 # Realm tok __magic_name__: List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """test""", """question""", """this""", """is""", """the""", """first""", """second""", """third""", """fourth""", """fifth""", """record""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __magic_name__: str = os.path.join(self.tmpdirname , """realm_tokenizer""" ) os.makedirs(_a , exist_ok=_a ) __magic_name__: List[Any] = os.path.join(_a , 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] ) ) __magic_name__: Optional[Any] = os.path.join(self.tmpdirname , """realm_block_records""" ) os.makedirs(_a , exist_ok=_a ) def lowerCamelCase__ ( self : List[Any] ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , """realm_tokenizer""" ) ) def lowerCamelCase__ ( self : int ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def lowerCamelCase__ ( self : Any ) -> Dict: __magic_name__: List[str] = RealmConfig(num_block_records=self.num_block_records ) return config def lowerCamelCase__ ( self : Any ) -> Any: __magic_name__: List[Any] = Dataset.from_dict( { """id""": ["""0""", """1"""], """question""": ["""foo""", """bar"""], """answers""": [["""Foo""", """Bar"""], ["""Bar"""]], } ) return dataset def lowerCamelCase__ ( self : List[Any] ) -> Dict: __magic_name__: List[str] = np.array( [ b"""This is the first record""", b"""This is the second record""", b"""This is the third record""", b"""This is the fourth record""", b"""This is the fifth record""", b"""This is a longer longer longer record""", ] , dtype=_a , ) return block_records def lowerCamelCase__ ( self : List[str] ) -> str: __magic_name__: int = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def lowerCamelCase__ ( self : Optional[int] ) -> str: __magic_name__: int = self.get_config() __magic_name__: Dict = self.get_dummy_retriever() __magic_name__: List[str] = retriever.tokenizer __magic_name__: Optional[int] = np.array([0, 3] , dtype="""long""" ) __magic_name__: Any = tokenizer(["""Test question"""] ).input_ids __magic_name__: Optional[Any] = tokenizer( ["""the fourth"""] , add_special_tokens=_a , return_token_type_ids=_a , return_attention_mask=_a , ).input_ids __magic_name__: Union[str, Any] = config.reader_seq_len __magic_name__: Union[str, Any] = retriever( _a , _a , answer_ids=_a , max_length=_a , return_tensors="""np""" ) self.assertEqual(len(_a ) , 2 ) self.assertEqual(len(_a ) , 2 ) self.assertEqual(len(_a ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 1_0) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 1_0) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 1_0) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 1_0) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ["""[CLS]""", """test""", """question""", """[SEP]""", """this""", """is""", """the""", """first""", """record""", """[SEP]"""] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ["""[CLS]""", """test""", """question""", """[SEP]""", """this""", """is""", """the""", """fourth""", """record""", """[SEP]"""] , ) def lowerCamelCase__ ( self : Dict ) -> List[str]: __magic_name__: Any = self.get_config() __magic_name__: Optional[Any] = self.get_dummy_retriever() __magic_name__: str = retriever.tokenizer __magic_name__: Tuple = np.array([0, 3, 5] , dtype="""long""" ) __magic_name__: List[str] = tokenizer(["""Test question"""] ).input_ids __magic_name__: Optional[Any] = tokenizer( ["""the fourth""", """longer longer"""] , add_special_tokens=_a , return_token_type_ids=_a , return_attention_mask=_a , ).input_ids __magic_name__: List[Any] = config.reader_seq_len __magic_name__: List[Any] = retriever( _a , _a , answer_ids=_a , max_length=_a , return_tensors="""np""" ) self.assertEqual([False, True, True] , _a ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , _a ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , _a ) def lowerCamelCase__ ( self : int ) -> Any: __magic_name__: str = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , """realm_block_records""" ) ) # Test local path __magic_name__: Union[str, Any] = retriever.from_pretrained(os.path.join(self.tmpdirname , """realm_block_records""" ) ) self.assertEqual(retriever.block_records[0] , b"""This is the first record""" ) # Test mocked remote path with patch("""transformers.models.realm.retrieval_realm.hf_hub_download""" ) as mock_hf_hub_download: __magic_name__: Optional[Any] = os.path.join( os.path.join(self.tmpdirname , """realm_block_records""" ) , _REALM_BLOCK_RECORDS_FILENAME ) __magic_name__: List[str] = RealmRetriever.from_pretrained("""google/realm-cc-news-pretrained-openqa""" ) self.assertEqual(retriever.block_records[0] , b"""This is the first record""" )
96
"""simple docstring""" from math import factorial def _lowercase ( __lowerCAmelCase = 100 ) -> int: return sum(int(__lowerCAmelCase ) for x in str(factorial(__lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
680
0
"""simple docstring""" from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } _SCREAMING_SNAKE_CASE = { "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } _SCREAMING_SNAKE_CASE = { "facebook/blenderbot_small-90M": 512, } class __magic_name__ ( UpperCamelCase_ ): _SCREAMING_SNAKE_CASE : Optional[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : List[str] = BlenderbotSmallTokenizer def __init__( self : Union[str, Any] , snake_case_ : str=None , snake_case_ : Tuple=None , snake_case_ : List[Any]="<|endoftext|>" , snake_case_ : Union[str, Any]="<|endoftext|>" , snake_case_ : List[Any]="<|endoftext|>" , snake_case_ : List[Any]=False , snake_case_ : Dict=True , **snake_case_ : Dict , ): super().__init__( ByteLevelBPETokenizer( vocab=_a , merges=_a , add_prefix_space=_a , trim_offsets=_a , ) , bos_token=_a , eos_token=_a , unk_token=_a , **_a , ) __snake_case = add_prefix_space def lowerCAmelCase ( self : str , snake_case_ : List[str] , snake_case_ : Dict=None ): __snake_case = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowerCAmelCase ( self : Optional[Any] , snake_case_ : Dict , snake_case_ : int = None ): __snake_case = [self.sep_token_id] __snake_case = [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]
163
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 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 (UpperCamelCase_): '''simple docstring''' def __init__( self , _a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = data def __iter__( self ) -> Tuple: """simple docstring""" for element in self.data: yield element def _lowercase ( __lowerCAmelCase=True ) -> str: SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]: if iterable: SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase ) return dl def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple: SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[str] = [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 _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( __lowerCAmelCase , 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( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( __lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _lowercase ( ) -> str: SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : int = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE__ : List[Any] = output.sum() loss.backward() batch_idxs.append(__lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]: with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowercase ( ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE__ : str = 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 _lowercase ( ) -> Tuple: SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings("""ignore""" ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 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 _lowercase ( ) -> List[str]: SCREAMING_SNAKE_CASE__ : str = create_accelerator() SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase ) create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase ) with warnings.catch_warnings(record=__lowerCAmelCase ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ): pass assert issubclass(w[-1].category , __lowerCAmelCase ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowercase ( ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 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""" ) SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : str = original_state if __name__ == "__main__": main()
680
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/config.json", # See all XGLM models at https://huggingface.co/models?filter=xglm } class __lowercase ( UpperCamelCase_ ): _a = """xglm""" _a = ["""past_key_values"""] _a = { """num_attention_heads""": """attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """num_layers""", } def __init__( self , UpperCamelCase=25_6008 , UpperCamelCase=2048 , UpperCamelCase=1024 , UpperCamelCase=4096 , UpperCamelCase=24 , UpperCamelCase=16 , UpperCamelCase="gelu" , UpperCamelCase=0.1 , UpperCamelCase=0.1 , UpperCamelCase=0.0 , UpperCamelCase=0.0 , UpperCamelCase=0.02 , UpperCamelCase=True , UpperCamelCase=True , UpperCamelCase=2 , UpperCamelCase=1 , UpperCamelCase=0 , UpperCamelCase=2 , **UpperCamelCase , ) -> str: __a = vocab_size __a = max_position_embeddings __a = d_model __a = ffn_dim __a = num_layers __a = attention_heads __a = activation_function __a = dropout __a = attention_dropout __a = activation_dropout __a = layerdrop __a = init_std __a = scale_embedding # scale factor will be sqrt(d_model) if True __a = use_cache super().__init__( pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , decoder_start_token_id=_a , **_a , )
539
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 200_0000 ) -> int: SCREAMING_SNAKE_CASE__ : int = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : str = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for i in range(__lowerCAmelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
680
0
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler lowerCamelCase : int =16 lowerCamelCase : List[str] =32 def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase = 16 , __lowerCAmelCase = "bert-base-cased" ) -> Tuple: UpperCamelCase__ : List[Any] = AutoTokenizer.from_pretrained(__lowerCAmelCase ) UpperCamelCase__ : Any = load_dataset("glue" , "mrpc" ) def tokenize_function(__lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase__ : Optional[int] = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase__ : Optional[int] = datasets.map( __lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["idx", "sentence1", "sentence2"] , load_from_cache_file=__lowerCAmelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase__ : Optional[Any] = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(__lowerCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__lowerCAmelCase , padding="max_length" , max_length=128 , return_tensors="pt" ) return tokenizer.pad(__lowerCAmelCase , padding="longest" , return_tensors="pt" ) # Instantiate dataloaders. UpperCamelCase__ : Union[str, Any] = DataLoader( tokenized_datasets["train"] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) UpperCamelCase__ : List[Any] = DataLoader( tokenized_datasets["validation"] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=__lowerCAmelCase ) return train_dataloader, eval_dataloader def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]: # Initialize accelerator UpperCamelCase__ : Optional[int] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase__ : Tuple = config["""lr"""] UpperCamelCase__ : str = int(config["num_epochs"] ) UpperCamelCase__ : Union[str, Any] = int(config["seed"] ) UpperCamelCase__ : Union[str, Any] = int(config["batch_size"] ) UpperCamelCase__ : str = args.model_name_or_path set_seed(__lowerCAmelCase ) UpperCamelCase__ : List[str] = get_dataloaders(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase__ : Dict = AutoModelForSequenceClassification.from_pretrained(__lowerCAmelCase , return_dict=__lowerCAmelCase ) # Instantiate optimizer UpperCamelCase__ : List[str] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase__ : Optional[int] = optimizer_cls(params=model.parameters() , lr=__lowerCAmelCase ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase__ : int = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCamelCase__ : Tuple = 1 UpperCamelCase__ : Dict = (len(__lowerCAmelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase__ : str = get_linear_schedule_with_warmup( optimizer=__lowerCAmelCase , num_warmup_steps=0 , num_training_steps=__lowerCAmelCase , ) else: UpperCamelCase__ : Tuple = DummyScheduler(__lowerCAmelCase , total_num_steps=__lowerCAmelCase , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase__ : str = accelerator.prepare( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # We need to keep track of how many total steps we have iterated over UpperCamelCase__ : Any = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase__ : Optional[Any] = 0 # Now we train the model UpperCamelCase__ : Optional[int] = evaluate.load("glue" , "mrpc" ) UpperCamelCase__ : Any = 0 UpperCamelCase__ : Optional[Any] = {} for epoch in range(__lowerCAmelCase , __lowerCAmelCase ): model.train() for step, batch in enumerate(__lowerCAmelCase ): UpperCamelCase__ : Dict = model(**__lowerCAmelCase ) UpperCamelCase__ : List[str] = outputs.loss UpperCamelCase__ : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(__lowerCAmelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() UpperCamelCase__ : Optional[int] = 0 for step, batch in enumerate(__lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase__ : Optional[Any] = model(**__lowerCAmelCase ) UpperCamelCase__ : Dict = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCamelCase__ : int = accelerator.gather( (predictions, batch["labels"]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__lowerCAmelCase ) - 1: UpperCamelCase__ : Tuple = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCamelCase__ : Tuple = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__lowerCAmelCase , references=__lowerCAmelCase , ) UpperCamelCase__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' , __lowerCAmelCase ) UpperCamelCase__ : Union[str, Any] = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: UpperCamelCase__ : Any = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , "all_results.json" ) , "w" ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: UpperCamelCase__ : List[str] = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage." ) parser.add_argument( "--model_name_or_path" , type=__lowerCAmelCase , default="bert-base-cased" , help="Path to pretrained model or model identifier from huggingface.co/models." , required=__lowerCAmelCase , ) parser.add_argument( "--output_dir" , type=__lowerCAmelCase , default="." , help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory." , ) parser.add_argument( "--performance_lower_bound" , type=__lowerCAmelCase , default=__lowerCAmelCase , help="Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value." , ) parser.add_argument( "--num_epochs" , type=__lowerCAmelCase , default=3 , help="Number of train epochs." , ) UpperCamelCase__ : List[Any] = parser.parse_args() UpperCamelCase__ : int = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": main()
228
"""simple docstring""" import numpy as np import qiskit def _lowercase ( __lowerCAmelCase = 8 , __lowerCAmelCase = None ) -> str: SCREAMING_SNAKE_CASE__ : List[Any] = np.random.default_rng(seed=__lowerCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE__ : List[str] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE__ : List[Any] = rng.integers(2 , size=__lowerCAmelCase ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE__ : Optional[Any] = rng.integers(2 , size=__lowerCAmelCase ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE__ : str = rng.integers(2 , size=__lowerCAmelCase ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE__ : Union[str, Any] = qiskit.QuantumCircuit(__lowerCAmelCase , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(__lowerCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__lowerCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(__lowerCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE__ : str = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE__ : Optional[int] = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1 , seed_simulator=__lowerCAmelCase ) # Returns the result of measurement. SCREAMING_SNAKE_CASE__ : int = job.result().get_counts(__lowerCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE__ : Optional[Any] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE__ : Optional[int] = gen_key[:key_len] if len(__lowerCAmelCase ) >= key_len else gen_key.ljust(__lowerCAmelCase , """0""" ) return key if __name__ == "__main__": print(f'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
680
0
import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class A( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[int] , A_ : Tuple , A_ : str=7 , A_ : Any=3 , A_ : Tuple=18 , A_ : List[str]=30 , A_ : Optional[Any]=400 , A_ : Tuple=True , A_ : int=None , A_ : Tuple=True , A_ : List[Any]=None , A_ : List[Any]=True , A_ : Dict=[0.5, 0.5, 0.5] , A_ : List[Any]=[0.5, 0.5, 0.5] , A_ : List[str]=False , ) -> List[Any]: """simple docstring""" lowerCamelCase_ = size if size is not None else {"""height""": 20, """width""": 20} lowerCamelCase_ = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} lowerCamelCase_ = parent lowerCamelCase_ = batch_size lowerCamelCase_ = num_channels lowerCamelCase_ = image_size lowerCamelCase_ = min_resolution lowerCamelCase_ = max_resolution lowerCamelCase_ = do_resize lowerCamelCase_ = size lowerCamelCase_ = do_center_crop lowerCamelCase_ = crop_size lowerCamelCase_ = do_normalize lowerCamelCase_ = image_mean lowerCamelCase_ = image_std lowerCamelCase_ = do_reduce_labels def a__ ( self : int ) -> Union[str, Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowerCamelCase_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) lowerCamelCase_ = Image.open(dataset[0]['file'] ) lowerCamelCase_ = Image.open(dataset[1]['file'] ) return image, map def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowerCamelCase_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) lowerCamelCase_ = Image.open(ds[0]['file'] ) lowerCamelCase_ = Image.open(ds[1]['file'] ) lowerCamelCase_ = Image.open(ds[2]['file'] ) lowerCamelCase_ = Image.open(ds[3]['file'] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class A( UpperCamelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = BeitImageProcessor if is_vision_available() else None def a__ ( self : str ) -> List[str]: """simple docstring""" lowerCamelCase_ = BeitImageProcessingTester(self ) @property def a__ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self : Tuple ) -> Optional[int]: """simple docstring""" lowerCamelCase_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'do_resize' ) ) self.assertTrue(hasattr(_a , 'size' ) ) self.assertTrue(hasattr(_a , 'do_center_crop' ) ) self.assertTrue(hasattr(_a , 'center_crop' ) ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'image_mean' ) ) self.assertTrue(hasattr(_a , 'image_std' ) ) def a__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 20, 'width': 20} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) self.assertEqual(image_processor.do_reduce_labels , _a ) lowerCamelCase_ = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_a ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) self.assertEqual(image_processor.do_reduce_labels , _a ) def a__ ( self : Dict ) -> Any: """simple docstring""" pass def a__ ( self : Union[str, Any] ) -> Any: """simple docstring""" lowerCamelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input lowerCamelCase_ = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched lowerCamelCase_ = image_processing(_a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def a__ ( self : Union[str, Any] ) -> Any: """simple docstring""" lowerCamelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) # Test not batched input lowerCamelCase_ = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched lowerCamelCase_ = image_processing(_a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def a__ ( self : str ) -> Tuple: """simple docstring""" lowerCamelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input lowerCamelCase_ = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched lowerCamelCase_ = image_processing(_a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def a__ ( self : str ) -> List[str]: """simple docstring""" lowerCamelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) lowerCamelCase_ = [] for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input lowerCamelCase_ = image_processing(image_inputs[0] , maps[0] , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test batched lowerCamelCase_ = image_processing(_a , _a , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test not batched input (PIL images) lowerCamelCase_ = prepare_semantic_single_inputs() lowerCamelCase_ = image_processing(_a , _a , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test batched input (PIL images) lowerCamelCase_ = prepare_semantic_batch_inputs() lowerCamelCase_ = image_processing(_a , _a , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 2, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) def a__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 lowerCamelCase_ = prepare_semantic_single_inputs() lowerCamelCase_ = image_processing(_a , _a , return_tensors='pt' ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 150 ) lowerCamelCase_ = True lowerCamelCase_ = image_processing(_a , _a , return_tensors='pt' ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 )
70
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = StableDiffusionInpaintPipeline _SCREAMING_SNAKE_CASE :Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS _SCREAMING_SNAKE_CASE :Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE :Optional[int] = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _SCREAMING_SNAKE_CASE :Dict = frozenset([]) def _a ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_a , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=_a ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : 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=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) SCREAMING_SNAKE_CASE__ : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Any = Image.fromarray(np.uinta(_a ) ).convert("""RGB""" ).resize((64, 64) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(_a ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(_a ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=_a ).manual_seed(_a ) SCREAMING_SNAKE_CASE__ : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInpaintPipeline(**_a ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) SCREAMING_SNAKE_CASE__ : int = self.get_dummy_inputs(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**_a ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _a ( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInpaintPipeline.from_pretrained(_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : int = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( _a , torch_dtype=torch.floataa , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _a ( self ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) SCREAMING_SNAKE_CASE__ : List[str] = """stabilityai/stable-diffusion-2-inpainting""" SCREAMING_SNAKE_CASE__ : Dict = PNDMScheduler.from_pretrained(_a , subfolder="""scheduler""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( _a , safety_checker=_a , scheduler=_a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Union[str, Any] = """Face of a yellow cat, high resolution, sitting on a park bench""" SCREAMING_SNAKE_CASE__ : Any = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe( prompt=_a , image=_a , mask_image=_a , generator=_a , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
680
0
"""simple docstring""" import numpy as np class a : def __init__( self ): UpperCAmelCase__ : int = (0, 0) UpperCAmelCase__ : Optional[Any] = None UpperCAmelCase__ : List[Any] = 0 UpperCAmelCase__ : List[Any] = 0 UpperCAmelCase__ : List[str] = 0 def __eq__( self , UpperCamelCase_ ): return self.position == cell.position def __snake_case ( self ): print(self.position ) class a : def __init__( self , UpperCamelCase_=(5, 5) ): UpperCAmelCase__ : List[Any] = np.zeros(_a ) UpperCAmelCase__ : Any = world_size[0] UpperCAmelCase__ : Tuple = world_size[1] def __snake_case ( self ): print(self.w ) def __snake_case ( self , UpperCamelCase_ ): UpperCAmelCase__ : Dict = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] UpperCAmelCase__ : List[str] = cell.position[0] UpperCAmelCase__ : Optional[int] = cell.position[1] UpperCAmelCase__ : str = [] for n in neughbour_cord: UpperCAmelCase__ : Tuple = current_x + n[0] UpperCAmelCase__ : List[str] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: UpperCAmelCase__ : Union[str, Any] = Cell() UpperCAmelCase__ : List[str] = (x, y) UpperCAmelCase__ : int = cell neighbours.append(_a ) return neighbours def lowerCamelCase ( _snake_case ,_snake_case ,_snake_case ): UpperCAmelCase__ : List[str] = [] UpperCAmelCase__ : Any = [] _open.append(__lowerCAmelCase ) while _open: UpperCAmelCase__ : Any = np.argmin([n.f for n in _open] ) UpperCAmelCase__ : List[Any] = _open[min_f] _closed.append(_open.pop(__lowerCAmelCase ) ) if current == goal: break for n in world.get_neigbours(__lowerCAmelCase ): for c in _closed: if c == n: continue UpperCAmelCase__ : List[Any] = current.g + 1 UpperCAmelCase__ : Optional[Any] = n.position UpperCAmelCase__ : Dict = goal.position UpperCAmelCase__ : str = (ya - ya) ** 2 + (xa - xa) ** 2 UpperCAmelCase__ : List[str] = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(__lowerCAmelCase ) UpperCAmelCase__ : str = [] while current.parent is not None: path.append(current.position ) UpperCAmelCase__ : Optional[int] = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": UpperCamelCase__ = Gridworld() # Start position and goal UpperCamelCase__ = Cell() UpperCamelCase__ = (0, 0) UpperCamelCase__ = Cell() UpperCamelCase__ = (4, 4) print(f'path from {start.position} to {goal.position}') UpperCamelCase__ = astar(world, start, goal) # Just for visual reasons. for i in s: UpperCamelCase__ = 1 print(world.w)
110
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a :str = logging.getLogger(__name__) def _lowercase ( ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser( description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).""" ) parser.add_argument("""--file_path""" , type=__lowerCAmelCase , default="""data/dump.txt""" , help="""The path to the data.""" ) parser.add_argument("""--tokenizer_type""" , type=__lowerCAmelCase , default="""bert""" , choices=["""bert""", """roberta""", """gpt2"""] ) parser.add_argument("""--tokenizer_name""" , type=__lowerCAmelCase , default="""bert-base-uncased""" , help="""The tokenizer to use.""" ) parser.add_argument("""--dump_file""" , type=__lowerCAmelCase , default="""data/dump""" , help="""The dump file prefix.""" ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() logger.info(F'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": SCREAMING_SNAKE_CASE__ : List[str] = BertTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""cls_token"""] # `[CLS]` SCREAMING_SNAKE_CASE__ : str = tokenizer.special_tokens_map["""sep_token"""] # `[SEP]` elif args.tokenizer_type == "roberta": SCREAMING_SNAKE_CASE__ : List[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""cls_token"""] # `<s>` SCREAMING_SNAKE_CASE__ : Dict = tokenizer.special_tokens_map["""sep_token"""] # `</s>` elif args.tokenizer_type == "gpt2": SCREAMING_SNAKE_CASE__ : List[Any] = GPTaTokenizer.from_pretrained(args.tokenizer_name ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.special_tokens_map["""bos_token"""] # `<|endoftext|>` SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.special_tokens_map["""eos_token"""] # `<|endoftext|>` logger.info(F'''Loading text from {args.file_path}''' ) with open(args.file_path , """r""" , encoding="""utf8""" ) as fp: SCREAMING_SNAKE_CASE__ : int = fp.readlines() logger.info("""Start encoding""" ) logger.info(F'''{len(__lowerCAmelCase )} examples to process.''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1_0000 SCREAMING_SNAKE_CASE__ : Dict = time.time() for text in data: SCREAMING_SNAKE_CASE__ : Dict = F'''{bos} {text.strip()} {sep}''' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase ) rslt.append(__lowerCAmelCase ) iter += 1 if iter % interval == 0: SCREAMING_SNAKE_CASE__ : str = time.time() logger.info(F'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) SCREAMING_SNAKE_CASE__ : Tuple = time.time() logger.info("""Finished binarization""" ) logger.info(F'''{len(__lowerCAmelCase )} examples processed.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''{args.dump_file}.{args.tokenizer_name}.pickle''' SCREAMING_SNAKE_CASE__ : Dict = tokenizer.vocab_size if vocab_size < (1 << 16): SCREAMING_SNAKE_CASE__ : Tuple = [np.uintaa(__lowerCAmelCase ) for d in rslt] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [np.intaa(__lowerCAmelCase ) for d in rslt] random.shuffle(rslt_ ) logger.info(F'''Dump to {dp_file}''' ) with open(__lowerCAmelCase , """wb""" ) as handle: pickle.dump(rslt_ , __lowerCAmelCase , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
680
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule lowerCAmelCase__ = {"tokenization_bertweet": ["BertweetTokenizer"]} if TYPE_CHECKING: from .tokenization_bertweet import BertweetTokenizer else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
645
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva a :List[Any] = "" a :Union[str, Any] = "" a :List[str] = "" a :str = 1 # (0 is vertical, 1 is horizontal) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) print("""Processing...""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = update_image_and_anno(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) for index, image in enumerate(__lowerCAmelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE__ : List[Any] = random_chars(32 ) SCREAMING_SNAKE_CASE__ : List[str] = paths[index].split(os.sep )[-1].rsplit(""".""" , 1 )[0] SCREAMING_SNAKE_CASE__ : List[str] = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(__lowerCAmelCase )} with {file_name}''' ) SCREAMING_SNAKE_CASE__ : int = [] for anno in new_annos[index]: SCREAMING_SNAKE_CASE__ : Tuple = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__lowerCAmelCase ) with open(F'''/{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> tuple[list, list]: SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: SCREAMING_SNAKE_CASE__ : Dict = in_file.readlines() SCREAMING_SNAKE_CASE__ : int = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) SCREAMING_SNAKE_CASE__ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE__ : Optional[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(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = 1 ) -> tuple[list, list, list]: SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] for idx in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : str = img_list[idx] path_list.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] = anno_list[idx] SCREAMING_SNAKE_CASE__ : Tuple = cva.imread(__lowerCAmelCase ) if flip_type == 1: SCREAMING_SNAKE_CASE__ : int = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: SCREAMING_SNAKE_CASE__ : Any = cva.flip(__lowerCAmelCase , __lowerCAmelCase ) for bbox in img_annos: SCREAMING_SNAKE_CASE__ : List[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__lowerCAmelCase ) new_imgs_list.append(__lowerCAmelCase ) return new_imgs_list, new_annos_lists, path_list def _lowercase ( __lowerCAmelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE__ : List[str] = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
680
0
import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor __snake_case :int =logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCamelCase_ ): def __init__( self : List[Any] , *__UpperCamelCase : Dict , **__UpperCamelCase : int ) -> None: warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' , _a , ) super().__init__(*_a , **_a )
106
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class __a (enum.Enum): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = 0 _SCREAMING_SNAKE_CASE :List[Any] = 1 _SCREAMING_SNAKE_CASE :Dict = 2 @add_end_docstrings(UpperCamelCase_) class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Any] = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """ def __init__( self , *_a , **_a ) -> Tuple: """simple docstring""" super().__init__(*_a , **_a ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. SCREAMING_SNAKE_CASE__ : Any = None if self.model.config.prefix is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. SCREAMING_SNAKE_CASE__ : Optional[Any] = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self._sanitize_parameters(prefix=_a , **self._forward_params ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._preprocess_params, **preprocess_params} SCREAMING_SNAKE_CASE__ : Optional[Any] = {**self._forward_params, **forward_params} def _a ( self , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , _a=None , **_a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = {} if prefix is not None: SCREAMING_SNAKE_CASE__ : Dict = prefix if prefix: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer( _a , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected''' """ [None, 'hole']""" ) SCREAMING_SNAKE_CASE__ : int = handle_long_generation preprocess_params.update(_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs SCREAMING_SNAKE_CASE__ : int = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : List[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) SCREAMING_SNAKE_CASE__ : Tuple = ReturnType.TENSORS if return_type is not None: SCREAMING_SNAKE_CASE__ : int = return_type if clean_up_tokenization_spaces is not None: SCREAMING_SNAKE_CASE__ : List[str] = clean_up_tokenization_spaces if stop_sequence is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.encode(_a , add_special_tokens=_a ) if len(_a ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) SCREAMING_SNAKE_CASE__ : List[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def _a ( self , *_a , **_a ) -> Any: """simple docstring""" if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*_a , **_a ) def __call__( self , _a , **_a ) -> Optional[int]: """simple docstring""" return super().__call__(_a , **_a ) def _a ( self , _a , _a="" , _a=None , **_a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( prefix + prompt_text , padding=_a , add_special_tokens=_a , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : Tuple = prompt_text if handle_long_generation == "hole": SCREAMING_SNAKE_CASE__ : List[Any] = inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_kwargs["""max_new_tokens"""] else: SCREAMING_SNAKE_CASE__ : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : str = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: SCREAMING_SNAKE_CASE__ : Optional[int] = inputs["""attention_mask"""][:, -keep_length:] return inputs def _a ( self , _a , **_a ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_inputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.get("""attention_mask""" , _a ) # Allow empty prompts if input_ids.shape[1] == 0: SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : List[str] = 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. SCREAMING_SNAKE_CASE__ : Optional[int] = generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: SCREAMING_SNAKE_CASE__ : List[str] = """max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: SCREAMING_SNAKE_CASE__ : int = generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length SCREAMING_SNAKE_CASE__ : Dict = """min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL SCREAMING_SNAKE_CASE__ : Tuple = self.model.generate(input_ids=_a , attention_mask=_a , **_a ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated_sequence.shape[0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : str = generated_sequence.reshape(_a , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(_a , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def _a ( self , _a , _a=ReturnType.FULL_TEXT , _a=True ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs["""generated_sequence"""][0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_outputs["""input_ids"""] SCREAMING_SNAKE_CASE__ : str = model_outputs["""prompt_text"""] SCREAMING_SNAKE_CASE__ : Any = generated_sequence.numpy().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: SCREAMING_SNAKE_CASE__ : Tuple = {"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.decode( _a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: SCREAMING_SNAKE_CASE__ : Dict = 0 else: SCREAMING_SNAKE_CASE__ : Optional[int] = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , ) ) if return_type == ReturnType.FULL_TEXT: SCREAMING_SNAKE_CASE__ : Tuple = prompt_text + text[prompt_length:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = text[prompt_length:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""generated_text""": all_text} records.append(_a ) return records
680
0
from math import sqrt def snake_case (UpperCamelCase : Any ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" lowerCamelCase__ = True # 0 and 1 are none primes. if number <= 1: lowerCamelCase__ = False for divisor in range(2 , int(round(sqrt(__lowerCAmelCase ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: lowerCamelCase__ = False break # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'status' must been from type bool" return status def snake_case (UpperCamelCase : List[Any] ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N lowerCamelCase__ = list(range(2 , n + 1 ) ) lowerCamelCase__ = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(__lowerCAmelCase ) ): for j in range(i + 1 , len(__lowerCAmelCase ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): lowerCamelCase__ = 0 # filters actual prime numbers. lowerCamelCase__ = [x for x in begin_list if x != 0] # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'ans' must been from type list" return ans def snake_case (UpperCamelCase : Union[str, Any] ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n > 2), "'N' must been an int and > 2" lowerCamelCase__ = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(__lowerCAmelCase ): ans.append(__lowerCAmelCase ) # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'ans' must been from type list" return ans def snake_case (UpperCamelCase : Optional[int] ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and number >= 0, "'number' must been an int and >= 0" lowerCamelCase__ = [] # this list will be returns of the function. # potential prime number factors. lowerCamelCase__ = 2 lowerCamelCase__ = number if number == 0 or number == 1: ans.append(__lowerCAmelCase ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(__lowerCAmelCase ): while quotient != 1: if is_prime(__lowerCAmelCase ) and (quotient % factor == 0): ans.append(__lowerCAmelCase ) quotient /= factor else: factor += 1 else: ans.append(__lowerCAmelCase ) # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'ans' must been from type list" return ans def snake_case (UpperCamelCase : Dict ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" lowerCamelCase__ = 0 # prime factorization of 'number' lowerCamelCase__ = prime_factorization(__lowerCAmelCase ) lowerCamelCase__ = max(__lowerCAmelCase ) # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'ans' must been from type int" return ans def snake_case (UpperCamelCase : List[Any] ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" lowerCamelCase__ = 0 # prime factorization of 'number' lowerCamelCase__ = prime_factorization(__lowerCAmelCase ) lowerCamelCase__ = min(__lowerCAmelCase ) # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'ans' must been from type int" return ans def snake_case (UpperCamelCase : List[Any] ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 == 0 , __lowerCAmelCase ), "compare bust been from type bool" return number % 2 == 0 def snake_case (UpperCamelCase : Tuple ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "'number' must been an int" assert isinstance(number % 2 != 0 , __lowerCAmelCase ), "compare bust been from type bool" return number % 2 != 0 def snake_case (UpperCamelCase : str ): '''simple docstring''' assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (number > 2) and is_even(__lowerCAmelCase ) ), "'number' must been an int, even and > 2" lowerCamelCase__ = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' lowerCamelCase__ = get_prime_numbers(__lowerCAmelCase ) lowerCamelCase__ = len(__lowerCAmelCase ) # run variable for while-loops. lowerCamelCase__ = 0 lowerCamelCase__ = None # exit variable. for break up the loops lowerCamelCase__ = True while i < len_pn and loop: lowerCamelCase__ = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: lowerCamelCase__ = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (len(__lowerCAmelCase ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def snake_case (UpperCamelCase : str , UpperCamelCase : str ): '''simple docstring''' assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." lowerCamelCase__ = 0 while numbera != 0: lowerCamelCase__ = numbera % numbera lowerCamelCase__ = numbera lowerCamelCase__ = rest # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def snake_case (UpperCamelCase : int , UpperCamelCase : List[Any] ): '''simple docstring''' assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." lowerCamelCase__ = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' lowerCamelCase__ = prime_factorization(__lowerCAmelCase ) lowerCamelCase__ = prime_factorization(__lowerCAmelCase ) elif numbera == 1 or numbera == 1: lowerCamelCase__ = [] lowerCamelCase__ = [] lowerCamelCase__ = max(__lowerCAmelCase , __lowerCAmelCase ) lowerCamelCase__ = 0 lowerCamelCase__ = 0 lowerCamelCase__ = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: lowerCamelCase__ = prime_fac_a.count(__lowerCAmelCase ) lowerCamelCase__ = prime_fac_a.count(__lowerCAmelCase ) for _ in range(max(__lowerCAmelCase , __lowerCAmelCase ) ): ans *= n else: lowerCamelCase__ = prime_fac_a.count(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ): ans *= n done.append(__lowerCAmelCase ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: lowerCamelCase__ = prime_fac_a.count(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ): ans *= n done.append(__lowerCAmelCase ) # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def snake_case (UpperCamelCase : List[Any] ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n >= 0), "'number' must been a positive int" lowerCamelCase__ = 0 lowerCamelCase__ = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(__lowerCAmelCase ): ans += 1 # precondition assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and is_prime( __lowerCAmelCase ), "'ans' must been a prime number and from type int" return ans def snake_case (UpperCamelCase : Tuple , UpperCamelCase : int ): '''simple docstring''' assert ( is_prime(__lowerCAmelCase ) and is_prime(__lowerCAmelCase ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" lowerCamelCase__ = p_number_a + 1 # jump to the next number lowerCamelCase__ = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(__lowerCAmelCase ): number += 1 while number < p_number_a: ans.append(__lowerCAmelCase ) number += 1 # fetch the next prime number. while not is_prime(__lowerCAmelCase ): number += 1 # precondition assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ans[0] != p_number_a and ans[len(__lowerCAmelCase ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def snake_case (UpperCamelCase : List[Any] ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n >= 1), "'n' must been int and >= 1" lowerCamelCase__ = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(__lowerCAmelCase ) # precondition assert ans[0] == 1 and ans[len(__lowerCAmelCase ) - 1] == n, "Error in function getDivisiors(...)" return ans def snake_case (UpperCamelCase : Optional[int] ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( number > 1 ), "'number' must been an int and >= 1" lowerCamelCase__ = get_divisors(__lowerCAmelCase ) # precondition assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (divisors[0] == 1) and (divisors[len(__lowerCAmelCase ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def snake_case (UpperCamelCase : Dict , UpperCamelCase : Any ): '''simple docstring''' assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. lowerCamelCase__ = gcd(abs(__lowerCAmelCase ) , abs(__lowerCAmelCase ) ) # precondition assert ( isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def snake_case (UpperCamelCase : Dict ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n >= 0), "'n' must been a int and >= 0" lowerCamelCase__ = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def snake_case (UpperCamelCase : List[Any] ): '''simple docstring''' assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and (n >= 0), "'n' must been an int and >= 0" lowerCamelCase__ = 0 lowerCamelCase__ = 1 lowerCamelCase__ = 1 # this will be return for _ in range(n - 1 ): lowerCamelCase__ = ans ans += fiba lowerCamelCase__ = tmp return ans
165
"""simple docstring""" from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> list[float]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = coefficient_matrix.shape SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE__ : Tuple = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if colsa != 1: SCREAMING_SNAKE_CASE__ : str = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(__lowerCAmelCase ) if rowsa != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Coefficient and constant matrices dimensions must be nxn and nx1 but """ F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(__lowerCAmelCase ) if len(__lowerCAmelCase ) != rowsa: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( """Number of initial values must be equal to number of rows in coefficient """ F'''matrix but received {len(__lowerCAmelCase )} and {rowsa}''' ) raise ValueError(__lowerCAmelCase ) if iterations <= 0: raise ValueError("""Iterations must be at least 1""" ) SCREAMING_SNAKE_CASE__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = table.shape strictly_diagonally_dominant(__lowerCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : Any = [] for row in range(__lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : List[str] = 0 for col in range(__lowerCAmelCase ): if col == row: SCREAMING_SNAKE_CASE__ : int = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE__ : Any = (temp + val) / denom new_val.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = new_val return [float(__lowerCAmelCase ) for i in new_val] def _lowercase ( __lowerCAmelCase ) -> bool: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = table.shape SCREAMING_SNAKE_CASE__ : str = True for i in range(0 , __lowerCAmelCase ): SCREAMING_SNAKE_CASE__ : str = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("""Coefficient matrix is not strictly diagonally dominant""" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
680
0
from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def _a ( __lowercase , __lowercase ) -> List[str]: """simple docstring""" __UpperCamelCase = k_size // 2 __UpperCamelCase = mgrid[0 - center : k_size - center, 0 - center : k_size - center] __UpperCamelCase = 1 / (2 * pi * sigma) * exp(-(square(__lowerCAmelCase ) + square(__lowerCAmelCase )) / (2 * square(__lowerCAmelCase )) ) return g def _a ( __lowercase , __lowercase , __lowercase ) -> str: """simple docstring""" __UpperCamelCase = image.shape[0], image.shape[1] # dst image height and width __UpperCamelCase = height - k_size + 1 __UpperCamelCase = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows __UpperCamelCase = zeros((dst_height * dst_width, k_size * k_size) ) __UpperCamelCase = 0 for i, j in product(range(__lowerCAmelCase ) , range(__lowerCAmelCase ) ): __UpperCamelCase = ravel(image[i : i + k_size, j : j + k_size] ) __UpperCamelCase = window row += 1 # turn the kernel into shape(k*k, 1) __UpperCamelCase = gen_gaussian_kernel(__lowerCAmelCase , __lowerCAmelCase ) __UpperCamelCase = ravel(__lowerCAmelCase ) # reshape and get the dst image __UpperCamelCase = dot(__lowerCAmelCase , __lowerCAmelCase ).reshape(__lowerCAmelCase , __lowerCAmelCase ).astype(__lowerCAmelCase ) return dst if __name__ == "__main__": # read original image _snake_case = imread(r'../image_data/lena.jpg') # turn image in gray scale value _snake_case = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size _snake_case = gaussian_filter(gray, 3, sigma=1) _snake_case = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow('gaussian filter with 3x3 mask', gaussianaxa) imshow('gaussian filter with 5x5 mask', gaussianaxa) waitKey()
383
"""simple docstring""" import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Optional[Union[str, Path]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :bool = True _SCREAMING_SNAKE_CASE :Optional[int] = None _SCREAMING_SNAKE_CASE :int = 1 _SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = None _SCREAMING_SNAKE_CASE :bool = False _SCREAMING_SNAKE_CASE :Optional[Dict] = None _SCREAMING_SNAKE_CASE :Optional[str] = None def _a ( self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(_a ) for k, v in self.__dict__.items()} )
680
0
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig A = logging.get_logger(__name__) A = "T5Config" def a(lowercase__ , lowercase__ , lowercase__ ): '''simple docstring''' snake_case_ = jnp.zeros_like(__lowerCAmelCase ) snake_case_ = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) snake_case_ = shifted_input_ids.at[:, 0].set(__lowerCAmelCase ) snake_case_ = jnp.where(shifted_input_ids == -100 , __lowerCAmelCase , __lowerCAmelCase ) return shifted_input_ids class SCREAMING_SNAKE_CASE ( UpperCamelCase_ ): """simple docstring""" __A = """mt5""" __A = MTaConfig class SCREAMING_SNAKE_CASE ( UpperCamelCase_ ): """simple docstring""" __A = """mt5""" __A = MTaConfig class SCREAMING_SNAKE_CASE ( UpperCamelCase_ ): """simple docstring""" __A = """mt5""" __A = MTaConfig
187
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a :Optional[Any] = "<<<<<<< This should probably be modified because it mentions: " a :Tuple = "=======\n>>>>>>>\n" a :str = [ "TextEncoderConfig", "ByteTextEncoder", "SubwordTextEncoder", "encoder_config", "maybe_build_from_corpus", "manual_dir", ] a :Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (r"tfds\.core", r"datasets"), (r"tf\.io\.gfile\.GFile", r"open"), (r"tf\.([\w\d]+)", r"datasets.Value('\1')"), (r"tfds\.features\.Text\(\)", r"datasets.Value('string')"), (r"tfds\.features\.Text\(", r"datasets.Value('string'),"), (r"features\s*=\s*tfds.features.FeaturesDict\(", r"features=datasets.Features("), (r"tfds\.features\.FeaturesDict\(", r"dict("), (r"The TensorFlow Datasets Authors", r"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"), (r"tfds\.", r"datasets."), (r"dl_manager\.manual_dir", r"self.config.data_dir"), (r"self\.builder_config", r"self.config"), ] def _lowercase ( __lowerCAmelCase ) -> int: return ConvertCommand(args.tfds_path , args.datasets_directory ) class __a (UpperCamelCase_): '''simple docstring''' @staticmethod def _a ( _a ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.add_parser( """convert""" , help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" , ) train_parser.add_argument( """--tfds_path""" , type=_a , required=_a , help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" , ) train_parser.add_argument( """--datasets_directory""" , type=_a , required=_a , help="""Path to the HuggingFace Datasets folder.""" ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , *_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = get_logger("""datasets-cli/converting""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tfds_path SCREAMING_SNAKE_CASE__ : List[Any] = datasets_directory def _a ( self ) -> List[str]: """simple docstring""" if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Tuple = os.path.dirname(self._tfds_path ) else: raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" ) SCREAMING_SNAKE_CASE__ : Dict = os.path.abspath(self._datasets_directory ) self._logger.info(f'''Converting datasets from {abs_tfds_path} to {abs_datasets_path}''' ) SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : List[Any] = {} if os.path.isdir(self._tfds_path ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.listdir(_a ) else: SCREAMING_SNAKE_CASE__ : List[Any] = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f'''Looking at file {f_name}''' ) SCREAMING_SNAKE_CASE__ : int = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Dict = os.path.join(_a , _a ) if not os.path.isfile(_a ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("""Skipping file""" ) continue with open(_a , encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[str] = f.readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Dict = [] for line in lines: SCREAMING_SNAKE_CASE__ : List[str] = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: SCREAMING_SNAKE_CASE__ : List[Any] = """import datasets\n""" elif "import tensorflow" in out_line: # order is important here SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" continue elif "from absl import logging" in out_line: SCREAMING_SNAKE_CASE__ : Any = """from datasets import logging\n""" elif "getLogger" in out_line: SCREAMING_SNAKE_CASE__ : Optional[int] = out_line.replace("""getLogger""" , """get_logger""" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Tuple = list(filter(lambda _a : e in out_line , _a ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(_a ) + """\n""" ) out_lines.append(_a ) out_lines.append(_a ) continue else: for pattern, replacement in TO_CONVERT: SCREAMING_SNAKE_CASE__ : int = re.sub(_a , _a , _a ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: SCREAMING_SNAKE_CASE__ : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" , _a ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) ) SCREAMING_SNAKE_CASE__ : Dict = """from . import """ + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f'''Error converting {out_line.strip()}''' ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: SCREAMING_SNAKE_CASE__ : Union[str, Any] = True out_lines.append(_a ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = f_name.replace(""".py""" , """""" ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(_a , _a ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(_a , _a ) os.makedirs(_a , exist_ok=_a ) self._logger.info(f'''Adding directory {output_dir}''' ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(_a ) if needs_manual_update: with_manual_update.append(_a ) with open(_a , """w""" , encoding="""utf-8""" ) as f: f.writelines(_a ) self._logger.info(f'''Converted in {output_file}''' ) for utils_file in utils_files: try: SCREAMING_SNAKE_CASE__ : str = os.path.basename(_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = imports_to_builder_map[f_name.replace(""".py""" , """""" )] self._logger.info(f'''Moving {dest_folder} to {utils_file}''' ) shutil.copy(_a , _a ) except KeyError: self._logger.error(f'''Cannot find destination folder for {utils_file}. Please copy manually.''' ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f'''You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.''' )
680
0
"""simple docstring""" import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = { "kakaobrain/align-base": "https://huggingface.co/kakaobrain/align-base/resolve/main/config.json", } class __A ( UpperCamelCase_ ): UpperCAmelCase__ = """align_text_model""" def __init__( self : Optional[int] , __snake_case : List[str]=3_0_5_2_2 , __snake_case : Optional[Any]=7_6_8 , __snake_case : Dict=1_2 , __snake_case : List[Any]=1_2 , __snake_case : Optional[Any]=3_0_7_2 , __snake_case : Optional[int]="gelu" , __snake_case : List[Any]=0.1 , __snake_case : List[str]=0.1 , __snake_case : Any=5_1_2 , __snake_case : Any=2 , __snake_case : Tuple=0.02 , __snake_case : Optional[int]=1E-12 , __snake_case : str=0 , __snake_case : Any="absolute" , __snake_case : Dict=True , **__snake_case : Union[str, Any] , ) -> Any: super().__init__(**_a ) __magic_name__: List[Any] = vocab_size __magic_name__: Any = hidden_size __magic_name__: Tuple = num_hidden_layers __magic_name__: Optional[int] = num_attention_heads __magic_name__: Union[str, Any] = hidden_act __magic_name__: int = intermediate_size __magic_name__: Optional[Any] = hidden_dropout_prob __magic_name__: Union[str, Any] = attention_probs_dropout_prob __magic_name__: Optional[Any] = max_position_embeddings __magic_name__: Dict = type_vocab_size __magic_name__: Tuple = initializer_range __magic_name__: Optional[int] = layer_norm_eps __magic_name__: Any = position_embedding_type __magic_name__: Optional[int] = use_cache __magic_name__: Dict = pad_token_id @classmethod def lowerCamelCase__ ( cls : Optional[Any] , __snake_case : Union[str, Any] , **__snake_case : Tuple ) -> "PretrainedConfig": cls._set_token_in_kwargs(_a ) __magic_name__: Any = cls.get_config_dict(_a , **_a ) # get the text config dict if we are loading from AlignConfig if config_dict.get("""model_type""" ) == "align": __magic_name__: Optional[int] = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(_a , **_a ) class __A ( UpperCamelCase_ ): UpperCAmelCase__ = """align_vision_model""" def __init__( self : Any , __snake_case : List[Any] = 3 , __snake_case : List[Any] = 6_0_0 , __snake_case : Union[str, Any] = 2.0 , __snake_case : List[str] = 3.1 , __snake_case : Optional[Any] = 8 , __snake_case : Tuple = [3, 3, 5, 3, 5, 5, 3] , __snake_case : int = [3_2, 1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2] , __snake_case : Tuple = [1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2, 3_2_0] , __snake_case : Optional[Any] = [] , __snake_case : Optional[Any] = [1, 2, 2, 2, 1, 2, 1] , __snake_case : str = [1, 2, 2, 3, 3, 4, 1] , __snake_case : List[str] = [1, 6, 6, 6, 6, 6, 6] , __snake_case : Optional[int] = 0.25 , __snake_case : Dict = "swish" , __snake_case : Optional[Any] = 2_5_6_0 , __snake_case : Optional[int] = "mean" , __snake_case : List[Any] = 0.02 , __snake_case : Union[str, Any] = 0.001 , __snake_case : int = 0.99 , __snake_case : Optional[int] = 0.2 , **__snake_case : Tuple , ) -> Tuple: super().__init__(**_a ) __magic_name__: Optional[int] = num_channels __magic_name__: int = image_size __magic_name__: Dict = width_coefficient __magic_name__: Dict = depth_coefficient __magic_name__: Union[str, Any] = depth_divisor __magic_name__: Union[str, Any] = kernel_sizes __magic_name__: Dict = in_channels __magic_name__: int = out_channels __magic_name__: Dict = depthwise_padding __magic_name__: str = strides __magic_name__: Any = num_block_repeats __magic_name__: Dict = expand_ratios __magic_name__: int = squeeze_expansion_ratio __magic_name__: Dict = hidden_act __magic_name__: Optional[int] = hidden_dim __magic_name__: int = pooling_type __magic_name__: Union[str, Any] = initializer_range __magic_name__: Dict = batch_norm_eps __magic_name__: Any = batch_norm_momentum __magic_name__: List[Any] = drop_connect_rate __magic_name__: int = sum(_a ) * 4 @classmethod def lowerCamelCase__ ( cls : Any , __snake_case : Optional[Any] , **__snake_case : str ) -> "PretrainedConfig": cls._set_token_in_kwargs(_a ) __magic_name__: int = cls.get_config_dict(_a , **_a ) # get the vision config dict if we are loading from AlignConfig if config_dict.get("""model_type""" ) == "align": __magic_name__: Dict = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(_a , **_a ) class __A ( UpperCamelCase_ ): UpperCAmelCase__ = """align""" UpperCAmelCase__ = True def __init__( self : Union[str, Any] , __snake_case : str=None , __snake_case : Tuple=None , __snake_case : Any=6_4_0 , __snake_case : Union[str, Any]=1.0 , __snake_case : List[Any]=0.02 , **__snake_case : Union[str, Any] , ) -> Tuple: super().__init__(**_a ) if text_config is None: __magic_name__: List[Any] = {} logger.info("""text_config is None. Initializing the AlignTextConfig with default values.""" ) if vision_config is None: __magic_name__: Optional[Any] = {} logger.info("""vision_config is None. Initializing the AlignVisionConfig with default values.""" ) __magic_name__: Dict = AlignTextConfig(**_a ) __magic_name__: Dict = AlignVisionConfig(**_a ) __magic_name__: List[str] = projection_dim __magic_name__: List[str] = temperature_init_value __magic_name__: Dict = initializer_range @classmethod def lowerCamelCase__ ( cls : Tuple , __snake_case : Tuple , __snake_case : int , **__snake_case : str ) -> str: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_a ) def lowerCamelCase__ ( self : List[Any] ) -> Union[str, Any]: __magic_name__: Tuple = copy.deepcopy(self.__dict__ ) __magic_name__: Union[str, Any] = self.text_config.to_dict() __magic_name__: Any = self.vision_config.to_dict() __magic_name__: Dict = self.__class__.model_type return output
96
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance a :str = 637_8137.0 a :Optional[Any] = 635_6752.31_4245 a :List[Any] = 6_378_137 def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float: SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2 SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2) SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
680
0