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
"""simple docstring""" import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHECKING: from ... import PreTrainedTokenizerBase, TensorType UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): __UpperCAmelCase = '''vision-encoder-decoder''' __UpperCAmelCase = True def __init__( self , **SCREAMING_SNAKE_CASE) -> Optional[Any]: super().__init__(**SCREAMING_SNAKE_CASE) if "encoder" not in kwargs or "decoder" not in kwargs: raise ValueError( F'A configuraton of type {self.model_type} cannot be instantiated because ' F'not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}') _lowerCamelCase : int = kwargs.pop("""encoder""") _lowerCamelCase : List[Any] = encoder_config.pop("""model_type""") _lowerCamelCase : Tuple = kwargs.pop("""decoder""") _lowerCamelCase : Tuple = decoder_config.pop("""model_type""") _lowerCamelCase : int = AutoConfig.for_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = AutoConfig.for_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = True @classmethod def UpperCamelCase_ ( cls , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> PretrainedConfig: logger.info("""Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""") _lowerCamelCase : List[Any] = True _lowerCamelCase : Tuple = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[Any] = copy.deepcopy(self.__dict__) _lowerCamelCase : Any = self.encoder.to_dict() _lowerCamelCase : Optional[int] = self.decoder.to_dict() _lowerCamelCase : List[Any] = self.__class__.model_type return output class lowercase__ ( A_ ): __UpperCAmelCase = version.parse('''1.11''' ) @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ]) @property def UpperCamelCase_ ( self) -> float: return 1e-4 @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: return OrderedDict({"""last_hidden_state""": {0: """batch""", 1: """encoder_sequence"""}}) class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: _lowerCamelCase : Dict = OrderedDict() _lowerCamelCase : Dict = {0: """batch""", 1: """past_decoder_sequence + sequence"""} _lowerCamelCase : Union[str, Any] = {0: """batch""", 1: """past_decoder_sequence + sequence"""} _lowerCamelCase : Optional[Any] = {0: """batch""", 1: """encoder_sequence"""} return common_inputs def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = -1 , SCREAMING_SNAKE_CASE = -1 , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: import torch _lowerCamelCase : Optional[Any] = OrderedDict() _lowerCamelCase : List[Any] = super().generate_dummy_inputs( SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE , seq_length=SCREAMING_SNAKE_CASE , is_pair=SCREAMING_SNAKE_CASE , framework=SCREAMING_SNAKE_CASE) _lowerCamelCase , _lowerCamelCase : List[Any] = dummy_input["""input_ids"""].shape _lowerCamelCase : List[str] = (batch, encoder_sequence, self._config.encoder_hidden_size) _lowerCamelCase : List[str] = dummy_input.pop("""input_ids""") _lowerCamelCase : Tuple = dummy_input.pop("""attention_mask""") _lowerCamelCase : Dict = torch.zeros(SCREAMING_SNAKE_CASE) return common_inputs class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> None: pass def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> OnnxConfig: return VisionEncoderDecoderEncoderOnnxConfig(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = "default") -> OnnxConfig: _lowerCamelCase : List[Any] = encoder_config.hidden_size return VisionEncoderDecoderDecoderOnnxConfig(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)
88
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionSAGPipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: torch.manual_seed(0) _lowerCamelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0) _lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : List[Any] = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> List[Any]: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""") _lowerCamelCase : Union[str, Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = """.""" _lowerCamelCase : int = torch.manual_seed(0) _lowerCamelCase : Tuple = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Dict = output.images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Optional[Any] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Dict = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = """.""" _lowerCamelCase : List[str] = torch.manual_seed(0) _lowerCamelCase : int = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Any = output.images _lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Optional[Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """.""" _lowerCamelCase : Union[str, Any] = torch.manual_seed(0) _lowerCamelCase : Optional[int] = sag_pipe( [prompt] , width=768 , height=512 , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) _lowerCamelCase : Union[str, Any] = output.images assert image.shape == (1, 512, 768, 3)
88
1
"""simple docstring""" import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class lowercase__ ( A_ ): __UpperCAmelCase = (DDPMScheduler,) def UpperCamelCase_ ( self , **SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : Optional[int] = { """num_train_timesteps""": 1000, """beta_start""": 0.00_01, """beta_end""": 0.02, """beta_schedule""": """linear""", """variance_type""": """fixed_small""", """clip_sample""": True, } config.update(**SCREAMING_SNAKE_CASE) return config def UpperCamelCase_ ( self) -> Optional[int]: for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[int]: for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2]): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE , beta_end=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[Any]: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> str: for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE , prediction_type=SCREAMING_SNAKE_CASE , sample_max_value=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Tuple: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: for t in [0, 500, 999]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Union[str, Any] = self.scheduler_classes[0] _lowerCamelCase : Dict = self.get_scheduler_config() _lowerCamelCase : Union[str, Any] = scheduler_class(**SCREAMING_SNAKE_CASE) assert torch.sum(torch.abs(scheduler._get_variance(0) - 0.0)) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487) - 0.0_09_79)) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999) - 0.02)) < 1e-5 def UpperCamelCase_ ( self) -> str: _lowerCamelCase : List[Any] = self.scheduler_classes[0] _lowerCamelCase : List[Any] = self.get_scheduler_config() _lowerCamelCase : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = len(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = self.dummy_model() _lowerCamelCase : List[Any] = self.dummy_sample_deter _lowerCamelCase : int = torch.manual_seed(0) for t in reversed(range(SCREAMING_SNAKE_CASE)): # 1. predict noise residual _lowerCamelCase : Tuple = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # 2. predict previous mean of sample x_t-1 _lowerCamelCase : Tuple = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance _lowerCamelCase : Any = pred_prev_sample _lowerCamelCase : Dict = torch.sum(torch.abs(SCREAMING_SNAKE_CASE)) _lowerCamelCase : Dict = torch.mean(torch.abs(SCREAMING_SNAKE_CASE)) assert abs(result_sum.item() - 2_58.96_06) < 1e-2 assert abs(result_mean.item() - 0.33_72) < 1e-3 def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : Optional[Any] = self.scheduler_classes[0] _lowerCamelCase : Dict = self.get_scheduler_config(prediction_type="""v_prediction""") _lowerCamelCase : Tuple = scheduler_class(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = len(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = self.dummy_model() _lowerCamelCase : Tuple = self.dummy_sample_deter _lowerCamelCase : List[Any] = torch.manual_seed(0) for t in reversed(range(SCREAMING_SNAKE_CASE)): # 1. predict noise residual _lowerCamelCase : Tuple = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # 2. predict previous mean of sample x_t-1 _lowerCamelCase : Union[str, Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance _lowerCamelCase : Optional[Any] = pred_prev_sample _lowerCamelCase : Union[str, Any] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE)) _lowerCamelCase : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE)) assert abs(result_sum.item() - 2_02.02_96) < 1e-2 assert abs(result_mean.item() - 0.26_31) < 1e-3 def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Any = self.scheduler_classes[0] _lowerCamelCase : Union[str, Any] = self.get_scheduler_config() _lowerCamelCase : Union[str, Any] = scheduler_class(**SCREAMING_SNAKE_CASE) _lowerCamelCase : int = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = scheduler.timesteps for i, timestep in enumerate(SCREAMING_SNAKE_CASE): if i == len(SCREAMING_SNAKE_CASE) - 1: _lowerCamelCase : Dict = -1 else: _lowerCamelCase : int = timesteps[i + 1] _lowerCamelCase : Union[str, Any] = scheduler.previous_timestep(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = prev_t.item() self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : Dict = self.scheduler_classes[0] _lowerCamelCase : List[str] = self.get_scheduler_config() _lowerCamelCase : Any = scheduler_class(**SCREAMING_SNAKE_CASE) _lowerCamelCase : int = [100, 87, 50, 51, 0] with self.assertRaises(SCREAMING_SNAKE_CASE , msg="""`custom_timesteps` must be in descending order."""): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> str: _lowerCamelCase : str = self.scheduler_classes[0] _lowerCamelCase : Dict = self.get_scheduler_config() _lowerCamelCase : Any = scheduler_class(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = [100, 87, 50, 1, 0] _lowerCamelCase : List[str] = len(SCREAMING_SNAKE_CASE) with self.assertRaises(SCREAMING_SNAKE_CASE , msg="""Can only pass one of `num_inference_steps` or `custom_timesteps`."""): scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE , timesteps=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = self.scheduler_classes[0] _lowerCamelCase : Optional[Any] = self.get_scheduler_config() _lowerCamelCase : Dict = scheduler_class(**SCREAMING_SNAKE_CASE) _lowerCamelCase : int = [scheduler.config.num_train_timesteps] with self.assertRaises( SCREAMING_SNAKE_CASE , msg="""`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}""" , ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE)
88
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=64 , ) -> Optional[int]: _lowerCamelCase : List[str] = parent _lowerCamelCase : List[Any] = batch_size _lowerCamelCase : Tuple = is_training _lowerCamelCase : Tuple = use_auxiliary_loss _lowerCamelCase : Any = num_queries _lowerCamelCase : List[str] = num_channels _lowerCamelCase : List[str] = min_size _lowerCamelCase : Tuple = max_size _lowerCamelCase : str = num_labels _lowerCamelCase : Any = hidden_dim _lowerCamelCase : Dict = hidden_dim def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) > 0.5 ).float() _lowerCamelCase : Dict = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE) > 0.5).long() _lowerCamelCase : Optional[int] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCamelCase_ ( self) -> str: _lowerCamelCase : List[str] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _lowerCamelCase : Any = self.num_queries _lowerCamelCase : int = self.num_labels _lowerCamelCase : int = [1, 1, 1, 1] _lowerCamelCase : Any = self.num_channels _lowerCamelCase : Optional[Any] = 64 _lowerCamelCase : str = 128 _lowerCamelCase : Optional[Any] = self.hidden_dim _lowerCamelCase : Any = self.hidden_dim _lowerCamelCase : List[Any] = self.hidden_dim return config def UpperCamelCase_ ( self) -> Any: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = self.prepare_config_and_inputs() _lowerCamelCase : str = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : str = output.encoder_hidden_states _lowerCamelCase : int = output.pixel_decoder_hidden_states _lowerCamelCase : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , config.decoder_layers) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False) -> List[str]: with torch.no_grad(): _lowerCamelCase : Optional[int] = MaskaFormerModel(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[int] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = model(SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(output.encoder_last_hidden_state is not None) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : str = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(result.encoder_last_hidden_state is not None) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1)) with torch.no_grad(): _lowerCamelCase : List[Any] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model( pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape , torch.Size([1])) @require_torch class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = MaskaFormerModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> int: _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""") def UpperCamelCase_ ( self) -> Optional[int]: pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""") def UpperCamelCase_ ( self) -> Tuple: pass @unittest.skip(reason="""Mask2Former is not a generative model""") def UpperCamelCase_ ( self) -> List[Any]: pass @unittest.skip(reason="""Mask2Former does not use token embeddings""") def UpperCamelCase_ ( self) -> Any: pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""") def UpperCamelCase_ ( self) -> Dict: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""") def UpperCamelCase_ ( self) -> Optional[int]: pass def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : str = [*signature.parameters.keys()] _lowerCamelCase : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> Optional[int]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _lowerCamelCase : Optional[int] = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Dict = (self.model_tester.min_size,) * 2 _lowerCamelCase : str = { """pixel_values""": torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE), """mask_labels""": torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE), """class_labels""": torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE).long(), } _lowerCamelCase : List[str] = self.model_tester.get_config() _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE , output_attentions=SCREAMING_SNAKE_CASE) self.assertTrue(outputs.attentions is not None) def UpperCamelCase_ ( self) -> Optional[Any]: if not self.model_tester.is_training: return _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE).loss loss.backward() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : int = True _lowerCamelCase : Optional[Any] = True _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _lowerCamelCase : int = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _lowerCamelCase : str = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _lowerCamelCase : Optional[int] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(pixel_decoder_hidden_states.grad) self.assertIsNotNone(transformer_decoder_hidden_states.grad) self.assertIsNotNone(attentions.grad) UpperCAmelCase = 1e-4 def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def UpperCamelCase_ ( self) -> Union[str, Any]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Tuple = MaskaFormerModel.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : List[str] = prepare_img() _lowerCamelCase : Union[str, Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Any = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Dict = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : Optional[Any] = self.default_image_processor _lowerCamelCase : Any = prepare_img() _lowerCamelCase : Dict = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : List[str] = model(**SCREAMING_SNAKE_CASE) # masks_queries_logits _lowerCamelCase : str = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)) _lowerCamelCase : Any = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] _lowerCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) # class_queries_logits _lowerCamelCase : List[str] = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1)) _lowerCamelCase : Optional[Any] = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ]).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : Tuple = image_processor( [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors="""pt""" , ) _lowerCamelCase : Optional[Any] = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""mask_labels"""]] _lowerCamelCase : Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""class_labels"""]] with torch.no_grad(): _lowerCamelCase : Any = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None)
88
1
"""simple docstring""" import math def _snake_case ( __snake_case : int ): """simple docstring""" _lowerCamelCase : Optional[Any] = 0 _lowerCamelCase : int = 0 while num > 0: _lowerCamelCase : Any = num % 8 _lowerCamelCase : int = octal + (remainder * math.floor(math.pow(10 , __snake_case ) )) counter += 1 _lowerCamelCase : str = math.floor(num / 8 ) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return F'0o{int(__snake_case )}' def _snake_case ( ): """simple docstring""" print("""\n2 in octal is:""" ) print(decimal_to_octal(2 ) ) # = 2 print("""\n8 in octal is:""" ) print(decimal_to_octal(8 ) ) # = 10 print("""\n65 in octal is:""" ) print(decimal_to_octal(65 ) ) # = 101 print("""\n216 in octal is:""" ) print(decimal_to_octal(216 ) ) # = 330 print("""\n512 in octal is:""" ) print(decimal_to_octal(512 ) ) # = 1000 print("""\n""" ) if __name__ == "__main__": main()
88
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) UpperCAmelCase = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) UpperCAmelCase = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) UpperCAmelCase = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModel) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
88
1
"""simple docstring""" import math def _snake_case ( __snake_case : float , __snake_case : float ): """simple docstring""" if ( not isinstance(__snake_case , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("""power_factor must be a valid float value between -1 and 1.""" ) return apparent_power * power_factor def _snake_case ( __snake_case : float , __snake_case : float ): """simple docstring""" if ( not isinstance(__snake_case , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("""power_factor must be a valid float value between -1 and 1.""" ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
88
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
88
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase = { """configuration_bloom""": ["""BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BloomConfig""", """BloomOnnxConfig"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""BloomTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ """BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST""", """BloomForCausalLM""", """BloomModel""", """BloomPreTrainedModel""", """BloomForSequenceClassification""", """BloomForTokenClassification""", """BloomForQuestionAnswering""", ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
"""simple docstring""" def _snake_case ( __snake_case : list[list[int]] , __snake_case : int , __snake_case : int , __snake_case : list[int] ): """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def _snake_case ( __snake_case : list[list[int]] , __snake_case : list[int] , __snake_case : int ): """simple docstring""" if curr_ind == len(__snake_case ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(__snake_case ) ): if valid_connection(__snake_case , __snake_case , __snake_case , __snake_case ): # Insert current vertex into path as next transition _lowerCamelCase : List[str] = next_ver # Validate created path if util_hamilton_cycle(__snake_case , __snake_case , curr_ind + 1 ): return True # Backtrack _lowerCamelCase : Tuple = -1 return False def _snake_case ( __snake_case : list[list[int]] , __snake_case : int = 0 ): """simple docstring""" _lowerCamelCase : Any = [-1] * (len(__snake_case ) + 1) # initialize start and end of path with starting index _lowerCamelCase : Optional[int] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__snake_case , __snake_case , 1 ) else []
88
1
"""simple docstring""" from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , ) -> Dict: _lowerCamelCase : Union[str, Any] = parent _lowerCamelCase : str = 13 _lowerCamelCase : Union[str, Any] = 7 _lowerCamelCase : Optional[int] = 30 _lowerCamelCase : Optional[int] = self.seq_length + self.mem_len _lowerCamelCase : Dict = 15 _lowerCamelCase : int = True _lowerCamelCase : Union[str, Any] = True _lowerCamelCase : List[Any] = 99 _lowerCamelCase : Tuple = [10, 50, 80] _lowerCamelCase : Tuple = 32 _lowerCamelCase : int = 32 _lowerCamelCase : Optional[Any] = 4 _lowerCamelCase : Optional[Any] = 8 _lowerCamelCase : List[Any] = 128 _lowerCamelCase : Dict = 2 _lowerCamelCase : str = 2 _lowerCamelCase : Any = None _lowerCamelCase : Union[str, Any] = 1 _lowerCamelCase : int = 0 _lowerCamelCase : Tuple = 3 _lowerCamelCase : str = self.vocab_size - 1 _lowerCamelCase : str = 0.01 def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _lowerCamelCase : Dict = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _lowerCamelCase : Optional[Any] = TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def UpperCamelCase_ ( self) -> int: random.seed(self.seed) tf.random.set_seed(self.seed) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Any: _lowerCamelCase : str = TFTransfoXLModel(SCREAMING_SNAKE_CASE) _lowerCamelCase , _lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE).to_tuple() _lowerCamelCase : int = {"""input_ids""": input_ids_a, """mems""": mems_a} _lowerCamelCase , _lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Tuple: _lowerCamelCase : str = TFTransfoXLLMHeadModel(SCREAMING_SNAKE_CASE) _lowerCamelCase , _lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE).to_tuple() _lowerCamelCase : Tuple = {"""input_ids""": input_ids_a, """labels""": lm_labels} _lowerCamelCase , _lowerCamelCase : Tuple = model(SCREAMING_SNAKE_CASE).to_tuple() _lowerCamelCase , _lowerCamelCase : int = model([input_ids_a, mems_a]).to_tuple() _lowerCamelCase : Optional[Any] = {"""input_ids""": input_ids_a, """mems""": mems_a, """labels""": lm_labels} _lowerCamelCase , _lowerCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Tuple = TFTransfoXLForSequenceClassification(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = model(SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : str = self.prepare_config_and_inputs() ((_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase)) : int = config_and_inputs _lowerCamelCase : Optional[Any] = {"""input_ids""": input_ids_a} return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) __UpperCAmelCase = () if is_tf_available() else () __UpperCAmelCase = ( { '''feature-extraction''': TFTransfoXLModel, '''text-classification''': TFTransfoXLForSequenceClassification, '''text-generation''': TFTransfoXLLMHeadModel, '''zero-shot''': TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[Any]: if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : List[str] = TFTransfoXLModelTester(self) _lowerCamelCase : Any = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , d_embed=37) def UpperCamelCase_ ( self) -> Any: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> Optional[Any]: self.model_tester.set_seed() _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: self.model_tester.set_seed() _lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> str: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() _lowerCamelCase : Any = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer) if model_class in list_other_models_with_output_ebd: _lowerCamelCase : Union[str, Any] = model.get_output_embeddings() assert isinstance(SCREAMING_SNAKE_CASE , tf.keras.layers.Layer) _lowerCamelCase : Tuple = model.get_bias() assert name is None else: _lowerCamelCase : Dict = model.get_output_embeddings() assert x is None _lowerCamelCase : List[str] = model.get_bias() assert name is None def UpperCamelCase_ ( self) -> Dict: # TODO JP: Make TransfoXL XLA compliant pass @slow def UpperCamelCase_ ( self) -> int: for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Any = TFTransfoXLModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""This model doesn't play well with fit() due to not returning a single loss.""") def UpperCamelCase_ ( self) -> Any: pass @require_tf class lowercase__ ( unittest.TestCase ): @unittest.skip("""Skip test until #12651 is resolved.""") @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[int] = TFTransfoXLLMHeadModel.from_pretrained("""transfo-xl-wt103""") # fmt: off _lowerCamelCase : int = tf.convert_to_tensor([[33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0]] , dtype=tf.intaa) # noqa: E231 # fmt: on # 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> # fmt: off _lowerCamelCase : List[str] = [33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0,33,1,1857,2,1,1009,4,1109,1_1739,4762,358,5,25,245,28,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of 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. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> _lowerCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE , max_length=200 , do_sample=SCREAMING_SNAKE_CASE) self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE)
88
"""simple docstring""" import mpmath # for roots of unity import numpy as np class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None) -> Tuple: # Input as list _lowerCamelCase : Any = list(poly_a or [0])[:] _lowerCamelCase : Optional[Any] = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _lowerCamelCase : int = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() _lowerCamelCase : Union[str, Any] = len(self.polyB) # Add 0 to make lengths equal a power of 2 _lowerCamelCase : List[Any] = int( 2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1))) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform _lowerCamelCase : Optional[Any] = complex(mpmath.root(x=1 , n=self.c_max_length , k=1)) # The product _lowerCamelCase : int = self.__multiply() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Dict = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE) <= 1: return dft[0] # _lowerCamelCase : str = self.c_max_length // 2 while next_ncol > 0: _lowerCamelCase : Dict = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : Tuple = self.root**next_ncol # First half of next step _lowerCamelCase : int = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step _lowerCamelCase : Optional[int] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update _lowerCamelCase : Union[str, Any] = new_dft _lowerCamelCase : List[str] = next_ncol // 2 return dft[0] def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[Any] = self.__dft("""A""") _lowerCamelCase : List[str] = self.__dft("""B""") _lowerCamelCase : List[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT _lowerCamelCase : List[str] = 2 while next_ncol <= self.c_max_length: _lowerCamelCase : Any = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : List[Any] = self.root ** (next_ncol // 2) _lowerCamelCase : str = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root)) current_root *= root # Update _lowerCamelCase : Any = new_inverse_c next_ncol *= 2 # Unpack _lowerCamelCase : Optional[Any] = [round(x[0].real , 8) + round(x[0].imag , 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self) -> Any: _lowerCamelCase : Dict = """A = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A])) _lowerCamelCase : List[Any] = """B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B])) _lowerCamelCase : int = """A*B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.product)) return F'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" def _snake_case ( __snake_case : int = 1000000 ): """simple docstring""" _lowerCamelCase : str = set(range(3 , __snake_case , 2 ) ) primes.add(2 ) for p in range(3 , __snake_case , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , __snake_case , __snake_case ) ) ) _lowerCamelCase : List[Any] = [float(__snake_case ) for n in range(limit + 1 )] for p in primes: for n in range(__snake_case , limit + 1 , __snake_case ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(f'''{solution() = }''')
88
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase = { """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""VisionEncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""TFVisionEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""FlaxVisionEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase = { """configuration_chinese_clip""": [ """CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ChineseCLIPConfig""", """ChineseCLIPOnnxConfig""", """ChineseCLIPTextConfig""", """ChineseCLIPVisionConfig""", ], """processing_chinese_clip""": ["""ChineseCLIPProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""ChineseCLIPFeatureExtractor"""] UpperCAmelCase = ["""ChineseCLIPImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ """CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """ChineseCLIPModel""", """ChineseCLIPPreTrainedModel""", """ChineseCLIPTextModel""", """ChineseCLIPVisionModel""", ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def _snake_case ( __snake_case : List[str] ): """simple docstring""" for param in module.parameters(): _lowerCamelCase : Optional[Any] = False def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _lowerCamelCase : Any = """mps""" if device == "mps": print( """WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch""" """ errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues""" """ with generations.""" ) return device def _snake_case ( __snake_case : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = plt.imshow(__snake_case ) fig.axes.get_xaxis().set_visible(__snake_case ) fig.axes.get_yaxis().set_visible(__snake_case ) plt.show() def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = datetime.now() _lowerCamelCase : Optional[Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
88
1
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class lowercase__ ( A_ ,unittest.TestCase ): __UpperCAmelCase = XLNetTokenizer __UpperCAmelCase = XLNetTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = True def UpperCamelCase_ ( self) -> str: super().setUp() # We have a SentencePiece fixture for testing _lowerCamelCase : str = XLNetTokenizer(SCREAMING_SNAKE_CASE , keep_accents=SCREAMING_SNAKE_CASE) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname) def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : int = """<s>""" _lowerCamelCase : Union[str, Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE) , SCREAMING_SNAKE_CASE) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE) , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : List[Any] = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , """<unk>""") self.assertEqual(vocab_keys[1] , """<s>""") self.assertEqual(vocab_keys[-1] , """<eod>""") self.assertEqual(len(SCREAMING_SNAKE_CASE) , 1006) def UpperCamelCase_ ( self) -> int: self.assertEqual(self.get_tokenizer().vocab_size , 1000) def UpperCamelCase_ ( self) -> str: _lowerCamelCase : int = XLNetTokenizer(SCREAMING_SNAKE_CASE , keep_accents=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = tokenizer.tokenize("""This is a test""") self.assertListEqual(SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""]) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE) , [285, 46, 10, 170, 382]) _lowerCamelCase : Union[str, Any] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""") self.assertListEqual( SCREAMING_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""", """é""", """.""", ] , ) _lowerCamelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4]) _lowerCamelCase : int = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE) self.assertListEqual( SCREAMING_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>""", """.""", ] , ) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : List[Any] = XLNetTokenizer(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""") self.assertListEqual( SCREAMING_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""", """se""", """.""", ] , ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""") , ["""▁he""", """ll""", """o"""]) def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Dict = XLNetTokenizer(SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = tokenizer.tokenize("""I was born in 92000, and this is falsé.""") self.assertListEqual( SCREAMING_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""", """se""", """.""", ] , ) @slow def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : Dict = XLNetTokenizer.from_pretrained("""xlnet-base-cased""") _lowerCamelCase : str = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def UpperCamelCase_ ( self) -> List[str]: # fmt: off _lowerCamelCase : Dict = {"""input_ids""": [[17, 2_1442, 270, 17, 10, 1_4645, 318, 34, 17, 4546, 3145, 787, 13, 7752, 2_2018, 23, 21, 17, 4546, 3145, 787, 13, 3352, 1_4431, 13, 5500, 11, 1176, 580, 13, 1_6819, 4797, 23, 17, 10, 1_7135, 658, 19, 457, 7932, 13, 184, 19, 3154, 1_7135, 6468, 19, 1404, 1_2269, 19, 4229, 5356, 1_6264, 46, 19, 17, 2_0545, 1_0395, 9, 9, 9, 11, 28, 6421, 9531, 2_0729, 17, 10, 353, 1_7022, 11, 21, 6421, 9531, 1_6949, 17, 10, 1_1509, 753, 11, 33, 95, 2421, 7385, 956, 1_4431, 2626, 25, 842, 7385, 4836, 21, 1429, 2272, 9855, 3120, 161, 2_4738, 19, 1_3203, 658, 218, 787, 21, 430, 1_8482, 847, 2637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 2_2178, 27, 1064, 22, 956, 13, 1_1101, 1429, 5854, 2_4313, 1_8953, 40, 422, 2_4366, 68, 1758, 37, 1_0483, 1_4257, 31, 207, 263, 21, 203, 3773, 25, 71, 9735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2049, 3442, 17, 1_3894, 3380, 23, 95, 18, 1_7634, 2288, 9, 4, 3]], """token_type_ids""": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE , model_name="""xlnet-base-cased""" , revision="""c841166438c31ec7ca9a106dee7bb312b73ae511""" , )
88
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCAmelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""") @dataclass class lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_mae""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. _lowerCamelCase : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = split["""test"""] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _lowerCamelCase : str = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = ViTMAEConfig() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) # adapt config config.update( { """mask_ratio""": model_args.mask_ratio, """norm_pix_loss""": model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """facebook/data2vec-text-base""": """https://huggingface.co/data2vec/resolve/main/config.json""", } class lowercase__ ( A_ ): __UpperCAmelCase = '''data2vec-text''' def __init__( self , SCREAMING_SNAKE_CASE=3_0522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE , ) -> Tuple: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = vocab_size _lowerCamelCase : int = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : List[str] = num_attention_heads _lowerCamelCase : Union[str, Any] = hidden_act _lowerCamelCase : Optional[Any] = intermediate_size _lowerCamelCase : Dict = hidden_dropout_prob _lowerCamelCase : List[Any] = attention_probs_dropout_prob _lowerCamelCase : str = max_position_embeddings _lowerCamelCase : Tuple = type_vocab_size _lowerCamelCase : str = initializer_range _lowerCamelCase : Any = layer_norm_eps _lowerCamelCase : List[str] = position_embedding_type _lowerCamelCase : Optional[Any] = use_cache _lowerCamelCase : int = classifier_dropout class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : Any = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Tuple = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
"""simple docstring""" import numpy as np def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return vector * sigmoid(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" import numpy as np import datasets UpperCAmelCase = """ Compute the Mahalanobis Distance Mahalonobis distance is the distance between a point and a distribution. And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance. It was introduced by Prof. P. C. Mahalanobis in 1936 and has been used in various statistical applications ever since [source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/] """ UpperCAmelCase = """\ @article{de2000mahalanobis, title={The mahalanobis distance}, author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L}, journal={Chemometrics and intelligent laboratory systems}, volume={50}, number={1}, pages={1--18}, year={2000}, publisher={Elsevier} } """ UpperCAmelCase = """ Args: X: List of datapoints to be compared with the `reference_distribution`. reference_distribution: List of datapoints from the reference distribution we want to compare to. Returns: mahalanobis: The Mahalonobis distance for each datapoint in `X`. Examples: >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\") >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]]) >>> print(results) {'mahalanobis': array([0.5])} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """X""": datasets.Sequence(datasets.Value("""float""" , id="""sequence""") , id="""X"""), }) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: # convert to numpy arrays _lowerCamelCase : Optional[Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = np.array(SCREAMING_SNAKE_CASE) # Assert that arrays are 2D if len(X.shape) != 2: raise ValueError("""Expected `X` to be a 2D vector""") if len(reference_distribution.shape) != 2: raise ValueError("""Expected `reference_distribution` to be a 2D vector""") if reference_distribution.shape[0] < 2: raise ValueError( """Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension""") # Get mahalanobis distance for each prediction _lowerCamelCase : Tuple = X - np.mean(SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = np.cov(reference_distribution.T) try: _lowerCamelCase : Optional[Any] = np.linalg.inv(SCREAMING_SNAKE_CASE) except np.linalg.LinAlgError: _lowerCamelCase : Any = np.linalg.pinv(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = np.dot(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : int = np.dot(SCREAMING_SNAKE_CASE , X_minus_mu.T).diagonal() return {"mahalanobis": mahal_dist}
88
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = HfArgumentParser(__snake_case ) _lowerCamelCase : int = parser.parse_args_into_dataclasses()[0] _lowerCamelCase : Dict = TensorFlowBenchmark(args=__snake_case ) try: _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: _lowerCamelCase : Union[str, Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" _lowerCamelCase : List[str] = """ """.join(str(__snake_case ).split(""" """ )[:-1] ) _lowerCamelCase : Dict = """""" _lowerCamelCase : List[Any] = eval(str(__snake_case ).split(""" """ )[-1] ) _lowerCamelCase : Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _lowerCamelCase : Tuple = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
88
1
"""simple docstring""" import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class lowercase__ ( A_ ): __UpperCAmelCase = ['''image_processor''', '''tokenizer'''] __UpperCAmelCase = '''BlipImageProcessor''' __UpperCAmelCase = '''AutoTokenizer''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Union[str, Any]: super().__init__(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # add QFormer tokenizer _lowerCamelCase : Dict = qformer_tokenizer def __call__( self , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 0 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> BatchFeature: if images is None and text is None: raise ValueError("""You have to specify at least images or text.""") _lowerCamelCase : Tuple = BatchFeature() if text is not None: _lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , stride=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , return_overflowing_tokens=SCREAMING_SNAKE_CASE , return_special_tokens_mask=SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , return_token_type_ids=SCREAMING_SNAKE_CASE , return_length=SCREAMING_SNAKE_CASE , verbose=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) encoding.update(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = self.qformer_tokenizer( text=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , stride=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , return_overflowing_tokens=SCREAMING_SNAKE_CASE , return_special_tokens_mask=SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , return_token_type_ids=SCREAMING_SNAKE_CASE , return_length=SCREAMING_SNAKE_CASE , verbose=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) _lowerCamelCase : str = qformer_text_encoding.pop("""input_ids""") _lowerCamelCase : str = qformer_text_encoding.pop("""attention_mask""") if images is not None: _lowerCamelCase : Tuple = self.image_processor(SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE) encoding.update(SCREAMING_SNAKE_CASE) return encoding def UpperCamelCase_ ( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> Optional[int]: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> List[str]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : List[Any] = self.tokenizer.model_input_names _lowerCamelCase : List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> str: if os.path.isfile(SCREAMING_SNAKE_CASE): raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file') os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = os.path.join(SCREAMING_SNAKE_CASE , """qformer_tokenizer""") self.qformer_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE) return super().save_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) @classmethod def UpperCamelCase_ ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : Optional[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , subfolder="""qformer_tokenizer""") _lowerCamelCase : Optional[Any] = cls._get_arguments_from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) args.append(SCREAMING_SNAKE_CASE) return cls(*SCREAMING_SNAKE_CASE)
88
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""", """kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""", """kssteven/ibert-roberta-large-mnli""": ( """https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''ibert''' def __init__( self , SCREAMING_SNAKE_CASE=3_0522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="none" , **SCREAMING_SNAKE_CASE , ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Dict = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Dict = type_vocab_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : Any = quant_mode _lowerCamelCase : List[str] = force_dequant class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
1
"""simple docstring""" from __future__ import annotations class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE = 0) -> Optional[int]: _lowerCamelCase : Dict = key def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> list[str]: assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) and isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(SCREAMING_SNAKE_CASE) ^ key) for ch in content] def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> list[str]: assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) and isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(SCREAMING_SNAKE_CASE) ^ key) for ch in content] def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 0) -> str: assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) and isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : str = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned _lowerCamelCase : Optional[Any] = """""" for ch in content: ans += chr(ord(SCREAMING_SNAKE_CASE) ^ key) return ans def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 0) -> str: assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) and isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned _lowerCamelCase : Optional[Any] = """""" for ch in content: ans += chr(ord(SCREAMING_SNAKE_CASE) ^ key) return ans def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 0) -> bool: assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) and isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) try: with open(SCREAMING_SNAKE_CASE) as fin, open("""encrypt.out""" , """w+""") as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)) except OSError: return False return True def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> bool: assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) and isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) try: with open(SCREAMING_SNAKE_CASE) as fin, open("""decrypt.out""" , """w+""") as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
88
"""simple docstring""" from __future__ import annotations import queue class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : int = data _lowerCamelCase : List[str] = None _lowerCamelCase : Any = None def _snake_case ( ): """simple docstring""" print("""\n********Press N to stop entering at any point of time********\n""" ) _lowerCamelCase : Optional[int] = input("""Enter the value of the root node: """ ).strip().lower() _lowerCamelCase : queue.Queue = queue.Queue() _lowerCamelCase : Optional[int] = TreeNode(int(__snake_case ) ) q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Tuple = q.get() _lowerCamelCase : Any = F'Enter the left node of {node_found.data}: ' _lowerCamelCase : Union[str, Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : Dict = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[str] = left_node q.put(__snake_case ) _lowerCamelCase : Optional[int] = F'Enter the right node of {node_found.data}: ' _lowerCamelCase : Optional[Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : List[Any] = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[Any] = right_node q.put(__snake_case ) raise def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Any = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Optional[Any] = [] while not q.empty(): _lowerCamelCase : Dict = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__snake_case ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : Optional[int] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__snake_case ) _lowerCamelCase : Tuple = n.left # end of while means current node doesn't have left child _lowerCamelCase : Optional[Any] = stack.pop() # start to traverse its right child _lowerCamelCase : Dict = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : int = node while n or stack: while n: stack.append(__snake_case ) _lowerCamelCase : Any = n.left _lowerCamelCase : Optional[Any] = stack.pop() print(n.data , end=""",""" ) _lowerCamelCase : List[Any] = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase , _lowerCamelCase : Union[str, Any] = [], [] _lowerCamelCase : Optional[Any] = node stacka.append(__snake_case ) while stacka: # to find the reversed order of post order, store it in stack2 _lowerCamelCase : Union[str, Any] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__snake_case ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def _snake_case ( __snake_case : str = "" , __snake_case : Any=50 , __snake_case : List[str]="*" ): """simple docstring""" if not s: return "\n" + width * char _lowerCamelCase , _lowerCamelCase : Optional[int] = divmod(width - len(__snake_case ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
88
1
"""simple docstring""" from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class lowercase__ ( A_ ): __UpperCAmelCase = CustomTokenizer pass
88
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowercase__ : __UpperCAmelCase = XGLMConfig __UpperCAmelCase = {} __UpperCAmelCase = '''gelu''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=14 , SCREAMING_SNAKE_CASE=7 , 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=0.02 , ) -> List[str]: _lowerCamelCase : Optional[int] = parent _lowerCamelCase : int = batch_size _lowerCamelCase : str = seq_length _lowerCamelCase : Any = is_training _lowerCamelCase : int = use_input_mask _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : str = vocab_size _lowerCamelCase : List[str] = d_model _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : int = ffn_dim _lowerCamelCase : str = activation_function _lowerCamelCase : Optional[int] = activation_dropout _lowerCamelCase : Tuple = attention_dropout _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Dict = initializer_range _lowerCamelCase : Optional[Any] = None _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[Any] = 2 _lowerCamelCase : str = 1 def UpperCamelCase_ ( self) -> int: return XGLMConfig.from_pretrained("""facebook/xglm-564M""") def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) , clip_value_min=0 , clip_value_max=3) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Tuple = self.get_config() _lowerCamelCase : Optional[int] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2) return ( config, input_ids, input_mask, head_mask, ) def UpperCamelCase_ ( self) -> Optional[int]: return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : str = config_and_inputs _lowerCamelCase : Optional[Any] = { """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () __UpperCAmelCase = (TFXGLMForCausalLM,) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Optional[Any] = TFXGLMModelTester(self) _lowerCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , n_embd=37) def UpperCamelCase_ ( self) -> Dict: self.config_tester.run_common_tests() @slow def UpperCamelCase_ ( self) -> List[Any]: for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""") def UpperCamelCase_ ( self) -> List[Any]: super().test_resize_token_embeddings() @require_tf class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=True) -> List[Any]: _lowerCamelCase : List[str] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Union[str, Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCamelCase : Dict = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on _lowerCamelCase : str = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: _lowerCamelCase : int = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") tf.random.set_seed(0) _lowerCamelCase : Union[str, Any] = tokenizer("""Today is a nice day and""" , return_tensors="""tf""") _lowerCamelCase : Any = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(""":/CPU:0"""): _lowerCamelCase : Any = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , seed=[7, 0]) _lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = ( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Any = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : List[Any] = """left""" # use different length sentences to test batching _lowerCamelCase : List[Any] = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""tf""" , padding=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = inputs["""input_ids"""] _lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , attention_mask=inputs["""attention_mask"""] , max_new_tokens=12) _lowerCamelCase : List[str] = tokenizer(sentences[0] , return_tensors="""tf""").input_ids _lowerCamelCase : Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Tuple = tokenizer(sentences[1] , return_tensors="""tf""").input_ids _lowerCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , [non_padded_sentence, padded_sentence])
88
1
"""simple docstring""" import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class lowercase__ ( A_ ): __UpperCAmelCase = (CMStochasticIterativeScheduler,) __UpperCAmelCase = 10 def UpperCamelCase_ ( self , **SCREAMING_SNAKE_CASE) -> Dict: _lowerCamelCase : Tuple = { """num_train_timesteps""": 201, """sigma_min""": 0.0_02, """sigma_max""": 80.0, } config.update(**SCREAMING_SNAKE_CASE) return config def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : List[str] = 10 _lowerCamelCase : Tuple = self.get_scheduler_config() _lowerCamelCase : int = self.scheduler_classes[0](**SCREAMING_SNAKE_CASE) scheduler.set_timesteps(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = scheduler.timesteps[0] _lowerCamelCase : Union[str, Any] = scheduler.timesteps[1] _lowerCamelCase : int = self.dummy_sample _lowerCamelCase : Optional[Any] = 0.1 * sample _lowerCamelCase : str = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).prev_sample _lowerCamelCase : List[str] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) def UpperCamelCase_ ( self) -> Union[str, Any]: for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[int] = self.scheduler_classes[0] _lowerCamelCase : Dict = self.get_scheduler_config() _lowerCamelCase : Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = 1 scheduler.set_timesteps(SCREAMING_SNAKE_CASE) _lowerCamelCase : int = scheduler.timesteps _lowerCamelCase : Optional[int] = torch.manual_seed(0) _lowerCamelCase : Optional[Any] = self.dummy_model() _lowerCamelCase : int = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(SCREAMING_SNAKE_CASE): # 1. scale model input _lowerCamelCase : Tuple = scheduler.scale_model_input(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # 2. predict noise residual _lowerCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # 3. predict previous sample x_t-1 _lowerCamelCase : Optional[Any] = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE).prev_sample _lowerCamelCase : List[Any] = pred_prev_sample _lowerCamelCase : List[str] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE)) _lowerCamelCase : Optional[int] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE)) assert abs(result_sum.item() - 1_92.76_14) < 1e-2 assert abs(result_mean.item() - 0.25_10) < 1e-3 def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : Any = self.scheduler_classes[0] _lowerCamelCase : Optional[Any] = self.get_scheduler_config() _lowerCamelCase : str = scheduler_class(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = [106, 0] scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = scheduler.timesteps _lowerCamelCase : List[str] = torch.manual_seed(0) _lowerCamelCase : List[Any] = self.dummy_model() _lowerCamelCase : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input _lowerCamelCase : Optional[Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # 2. predict noise residual _lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # 3. predict previous sample x_t-1 _lowerCamelCase : Dict = scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE).prev_sample _lowerCamelCase : Union[str, Any] = pred_prev_sample _lowerCamelCase : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE)) _lowerCamelCase : Optional[int] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE)) assert abs(result_sum.item() - 3_47.63_57) < 1e-2 assert abs(result_mean.item() - 0.45_27) < 1e-3 def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : List[str] = self.scheduler_classes[0] _lowerCamelCase : List[str] = self.get_scheduler_config() _lowerCamelCase : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE) _lowerCamelCase : int = [39, 30, 12, 15, 0] with self.assertRaises(SCREAMING_SNAKE_CASE , msg="""`timesteps` must be in descending order."""): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : Any = self.scheduler_classes[0] _lowerCamelCase : Optional[int] = self.get_scheduler_config() _lowerCamelCase : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = [39, 30, 12, 1, 0] _lowerCamelCase : Any = len(SCREAMING_SNAKE_CASE) with self.assertRaises(SCREAMING_SNAKE_CASE , msg="""Can only pass one of `num_inference_steps` or `timesteps`."""): scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE , timesteps=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : Union[str, Any] = self.scheduler_classes[0] _lowerCamelCase : Optional[int] = self.get_scheduler_config() _lowerCamelCase : Tuple = scheduler_class(**SCREAMING_SNAKE_CASE) _lowerCamelCase : int = [scheduler.config.num_train_timesteps] with self.assertRaises( SCREAMING_SNAKE_CASE , msg="""`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}""" , ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE)
88
"""simple docstring""" from collections import defaultdict def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : Tuple = first_str.lower().strip() _lowerCamelCase : int = second_str.lower().strip() # Remove whitespace _lowerCamelCase : Any = first_str.replace(""" """ , """""" ) _lowerCamelCase : List[str] = second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(__snake_case ) != len(__snake_case ): return False # Default values for count should be 0 _lowerCamelCase : defaultdict[str, int] = defaultdict(__snake_case ) # For each character in input strings, # increment count in the corresponding for i in range(len(__snake_case ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase = input("""Enter the first string """).strip() UpperCAmelCase = input("""Enter the second string """).strip() UpperCAmelCase = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
88
1
"""simple docstring""" import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def _snake_case ( __snake_case : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = os.path.join(args.tf_model_dir , """parameters.json""" ) _lowerCamelCase : Tuple = json.loads(open(__snake_case ).read() ) if not params: raise ValueError( F'It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.' ) if not args.output.endswith(""".pt""" ): _lowerCamelCase : str = args.output + """.pt""" _lowerCamelCase : int = OrderedDict() with tf.device("""/CPU:0""" ): _lowerCamelCase : str = tf.train.load_checkpoint(args.tf_model_dir ) _lowerCamelCase : List[str] = reader.get_variable_to_shape_map() for key_name in shapes.keys(): _lowerCamelCase : Union[str, Any] = reader.get_tensor(__snake_case ).astype(np.floataa ) if key_name.endswith("""/adam_m""" ) or key_name.endswith("""/adam_v""" ): continue if key_name.startswith("""pasts/""" ): if key_name.startswith("""pasts/mlp""" ): _lowerCamelCase : Tuple = int(key_name[9] ) elif key_name.startswith("""pasts/out""" ): _lowerCamelCase : List[str] = 8 _lowerCamelCase : str = """model.sqout.%d.weight""" % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time _lowerCamelCase : int = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _lowerCamelCase : List[Any] = torch.tensor(__snake_case ) elif key_name.startswith("""model/moe""" ): _lowerCamelCase : Tuple = int(key_name[9:].split("""/""" )[0] ) if key_name.endswith("""/switch_gating/kernel""" ): _lowerCamelCase : Optional[Any] = """model.blocks.%d.feed_forward.mlp.router.classifier.weight""" % player _lowerCamelCase : Optional[int] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _lowerCamelCase : List[str] = torch.tensor(__snake_case ) elif key_name.endswith("""/softmlp/kernel""" ): _lowerCamelCase : Optional[Any] = """model.blocks.%d.feed_forward.soft_bypass_mlp.weight""" % player _lowerCamelCase : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _lowerCamelCase : str = torch.tensor(__snake_case ) elif key_name.endswith("""/wo/kernel""" ) or key_name.endswith("""/wi/kernel""" ): _lowerCamelCase : List[str] = key_name[-9:-7] for i in range(16 ): _lowerCamelCase : Any = """model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight""" % (player, i, nlayer) _lowerCamelCase : Optional[int] = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided _lowerCamelCase : List[str] = torch.tensor(__snake_case ) elif key_name.startswith("""model/mlp""" ): _lowerCamelCase : int = int(key_name[9:].split("""/""" )[0] ) if key_name.endswith("""/p1/kernel""" ): _lowerCamelCase : Dict = """model.blocks.%d.feed_forward.mlp.wi.weight""" % player _lowerCamelCase : Optional[int] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _lowerCamelCase : Dict = torch.tensor(__snake_case ) elif key_name.endswith("""/p1/bias""" ): _lowerCamelCase : Tuple = """model.blocks.%d.feed_forward.mlp.wi.bias""" % player _lowerCamelCase : Tuple = vnp.copy() # same because it is one dimensional _lowerCamelCase : List[Any] = torch.tensor(__snake_case ) elif key_name.endswith("""/p2/kernel""" ): _lowerCamelCase : List[str] = """model.blocks.%d.feed_forward.mlp.wo.weight""" % player _lowerCamelCase : Tuple = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _lowerCamelCase : List[Any] = torch.tensor(__snake_case ) elif key_name.endswith("""/p2/bias""" ): _lowerCamelCase : str = """model.blocks.%d.feed_forward.mlp.wo.bias""" % player _lowerCamelCase : Dict = vnp.copy() # same because it is one dimensional _lowerCamelCase : List[str] = torch.tensor(__snake_case ) elif key_name.startswith("""model/ln""" ): _lowerCamelCase : List[Any] = int(key_name[8:].split("""/""" )[0] ) if key_name.endswith("""/b""" ): _lowerCamelCase : Any = """model.blocks.%d.feed_forward.norm.bias""" % player _lowerCamelCase : Optional[Any] = vnp.copy() # same because it is one dimensional _lowerCamelCase : Optional[Any] = torch.tensor(__snake_case ) elif key_name.endswith("""/g""" ): _lowerCamelCase : List[str] = """model.blocks.%d.feed_forward.norm.weight""" % player _lowerCamelCase : int = vnp.copy() # same because it is one dimensional _lowerCamelCase : int = torch.tensor(__snake_case ) elif key_name.startswith("""model/att""" ): _lowerCamelCase : List[Any] = int(key_name[9:].split("""/""" )[0] ) if key_name.endswith("""/qkv/kernel""" ): _lowerCamelCase : Tuple = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum _lowerCamelCase : List[Any] = state[:, 0, :, :] _lowerCamelCase : Tuple = state[:, 1, :, :] _lowerCamelCase : List[Any] = state[:, 2, :, :] _lowerCamelCase : int = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix _lowerCamelCase : Any = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix _lowerCamelCase : Union[str, Any] = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix _lowerCamelCase : Any = """model.blocks.%d.self_attn.self_attn.q_proj.weight""" % player _lowerCamelCase : Dict = torch.tensor(__snake_case ) _lowerCamelCase : List[str] = """model.blocks.%d.self_attn.self_attn.k_proj.weight""" % player _lowerCamelCase : Any = torch.tensor(__snake_case ) _lowerCamelCase : str = """model.blocks.%d.self_attn.self_attn.v_proj.weight""" % player _lowerCamelCase : Union[str, Any] = torch.tensor(__snake_case ) elif key_name.endswith("""/o/kernel""" ): _lowerCamelCase : Union[str, Any] = """model.blocks.%d.self_attn.self_attn.out_proj.weight""" % player _lowerCamelCase : Any = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix _lowerCamelCase : Optional[int] = torch.tensor(__snake_case ) elif key_name.startswith("""model/an""" ): _lowerCamelCase : Optional[int] = int(key_name[8:].split("""/""" )[0] ) if key_name.endswith("""/b""" ): _lowerCamelCase : Union[str, Any] = """model.blocks.%d.self_attn.norm.bias""" % player _lowerCamelCase : Dict = vnp.copy() # same because it is one dimensional _lowerCamelCase : Tuple = torch.tensor(__snake_case ) elif key_name.endswith("""/g""" ): _lowerCamelCase : str = """model.blocks.%d.self_attn.norm.weight""" % player _lowerCamelCase : Optional[int] = vnp.copy() # same because it is one dimensional _lowerCamelCase : Optional[int] = torch.tensor(__snake_case ) elif ( key_name.startswith("""model/wte""" ) or key_name.startswith("""model/wpe""" ) or key_name.startswith("""model/ete""" ) ): _lowerCamelCase : Optional[int] = {"""wte""": """embed_tokens""", """wpe""": """position_embeddings""", """ete""": """extra_position_embeddings"""}[ key_name[-3:] ] _lowerCamelCase : int = """model.%s.weight""" % nlayer _lowerCamelCase : Dict = vnp.copy() # same in embedded _lowerCamelCase : List[Any] = torch.tensor(__snake_case ) if key_name.startswith("""model/wte""" ): _lowerCamelCase : List[Any] = """lm_head.weight""" _lowerCamelCase : str = vnp.copy() # same in embedded _lowerCamelCase : List[Any] = torch.tensor(__snake_case ) elif key_name.startswith("""model/wob""" ): _lowerCamelCase : Tuple = """final_logits_bias""" _lowerCamelCase : List[str] = vnp.copy() # same in embedded _lowerCamelCase : Optional[int] = state.reshape((1, -1) ) _lowerCamelCase : str = torch.tensor(__snake_case ) elif key_name == "model/dense/kernel": _lowerCamelCase : List[str] = """model.last_project.weight""" _lowerCamelCase : Tuple = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix _lowerCamelCase : Dict = torch.tensor(__snake_case ) elif key_name == "model/dense_1/bias": _lowerCamelCase : str = """model.last_project.bias""" _lowerCamelCase : Optional[int] = vnp.copy() # same because it is one dimensional _lowerCamelCase : Optional[Any] = torch.tensor(__snake_case ) torch.save(__snake_case , args.output ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser( description="""model converter.""", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("""--tf_model_dir""", metavar="""PATH""", type=str, required=True, help="""import model""") parser.add_argument("""--output""", metavar="""PATH""", type=str, required=True, help="""output model""") UpperCAmelCase = parser.parse_args() convert_tf_gptsan_to_pt(args)
88
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _snake_case ( __snake_case : float , __snake_case : float , __snake_case : bool = False ): """simple docstring""" if radian_mode: return [magnitude * cos(__snake_case ), magnitude * sin(__snake_case )] return [magnitude * cos(radians(__snake_case ) ), magnitude * sin(radians(__snake_case ) )] def _snake_case ( __snake_case : NDArray[floataa] , __snake_case : NDArray[floataa] , __snake_case : float = 10**-1 ): """simple docstring""" _lowerCamelCase : NDArray[floataa] = cross(__snake_case , __snake_case ) _lowerCamelCase : float = sum(__snake_case ) return abs(__snake_case ) < eps if __name__ == "__main__": # Test to check if it works UpperCAmelCase = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg UpperCAmelCase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg UpperCAmelCase = array([[0, -2000], [0, -1200], [0, 1_5600], [0, -1_2400]]) UpperCAmelCase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
88
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> None: warnings.warn( """The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ImageGPTImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE)
88
"""simple docstring""" import random def _snake_case ( __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = a[left_index] _lowerCamelCase : Dict = left_index + 1 for j in range(left_index + 1 , __snake_case ): if a[j] < pivot: _lowerCamelCase , _lowerCamelCase : List[str] = a[i], a[j] i += 1 _lowerCamelCase , _lowerCamelCase : Optional[int] = a[i - 1], a[left_index] return i - 1 def _snake_case ( __snake_case : Tuple , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" if left < right: _lowerCamelCase : Any = random.randint(__snake_case , right - 1 ) _lowerCamelCase , _lowerCamelCase : Optional[Any] = ( a[left], a[pivot], ) # switches the pivot with the left most bound _lowerCamelCase : List[str] = partition(__snake_case , __snake_case , __snake_case ) quick_sort_random( __snake_case , __snake_case , __snake_case ) # recursive quicksort to the left of the pivot point quick_sort_random( __snake_case , pivot_index + 1 , __snake_case ) # recursive quicksort to the right of the pivot point def _snake_case ( ): """simple docstring""" _lowerCamelCase : Union[str, Any] = input("""Enter numbers separated by a comma:\n""" ).strip() _lowerCamelCase : int = [int(__snake_case ) for item in user_input.split(""",""" )] quick_sort_random(__snake_case , 0 , len(__snake_case ) ) print(__snake_case ) if __name__ == "__main__": main()
88
1
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _snake_case ( __snake_case : float , __snake_case : float , __snake_case : bool = False ): """simple docstring""" if radian_mode: return [magnitude * cos(__snake_case ), magnitude * sin(__snake_case )] return [magnitude * cos(radians(__snake_case ) ), magnitude * sin(radians(__snake_case ) )] def _snake_case ( __snake_case : NDArray[floataa] , __snake_case : NDArray[floataa] , __snake_case : float = 10**-1 ): """simple docstring""" _lowerCamelCase : NDArray[floataa] = cross(__snake_case , __snake_case ) _lowerCamelCase : float = sum(__snake_case ) return abs(__snake_case ) < eps if __name__ == "__main__": # Test to check if it works UpperCAmelCase = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg UpperCAmelCase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg UpperCAmelCase = array([[0, -2000], [0, -1200], [0, 1_5600], [0, -1_2400]]) UpperCAmelCase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
88
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase = """\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } """ UpperCAmelCase = """\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). """ UpperCAmelCase = """ Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric(\"code_eval\") >>> test_cases = [\"assert add(2,3)==5\"] >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {'pass@1': 0.5, 'pass@2': 1.0} """ UpperCAmelCase = """ ################################################################################ !!!WARNING!!! ################################################################################ The \"code_eval\" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this with: >>> import os >>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\" ################################################################################\ """ UpperCAmelCase = """The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> str: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""")), """references""": datasets.Value("""string"""), }) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=[1, 10, 100] , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=3.0) -> Union[str, Any]: if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0) != "1": raise ValueError(_WARNING) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""") with ThreadPoolExecutor(max_workers=SCREAMING_SNAKE_CASE) as executor: _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Optional[int] = Counter() _lowerCamelCase : Any = 0 _lowerCamelCase : List[Any] = defaultdict(SCREAMING_SNAKE_CASE) for task_id, (candidates, test_case) in enumerate(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)): for candidate in candidates: _lowerCamelCase : Any = candidate + """\n""" + test_case _lowerCamelCase : Union[str, Any] = (test_program, timeout, task_id, completion_id[task_id]) _lowerCamelCase : List[str] = executor.submit(SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE) futures.append(SCREAMING_SNAKE_CASE) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(SCREAMING_SNAKE_CASE): _lowerCamelCase : int = future.result() results[result["task_id"]].append((result["""completion_id"""], result)) _lowerCamelCase , _lowerCamelCase : List[Any] = [], [] for result in results.values(): result.sort() _lowerCamelCase : List[str] = [r[1]["""passed"""] for r in result] total.append(len(SCREAMING_SNAKE_CASE)) correct.append(sum(SCREAMING_SNAKE_CASE)) _lowerCamelCase : List[Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = k _lowerCamelCase : Optional[Any] = {F'pass@{k}': estimate_pass_at_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).mean() for k in ks if (total >= k).all()} return pass_at_k, results def _snake_case ( __snake_case : List[str] , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" def estimator(__snake_case : int , __snake_case : int , __snake_case : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(__snake_case , __snake_case ): _lowerCamelCase : Optional[int] = itertools.repeat(__snake_case , len(__snake_case ) ) else: assert len(__snake_case ) == len(__snake_case ) _lowerCamelCase : List[str] = iter(__snake_case ) return np.array([estimator(int(__snake_case ) , int(__snake_case ) , __snake_case ) for n, c in zip(__snake_case , __snake_case )] )
88
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin UpperCAmelCase = False @skip_mps class lowercase__ ( A_ ,A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionAttendAndExcitePipeline __UpperCAmelCase = False __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''} ) __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def UpperCamelCase_ ( cls) -> List[Any]: super().setUpClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE) @classmethod def UpperCamelCase_ ( cls) -> Optional[Any]: super().tearDownClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Dict: torch.manual_seed(0) _lowerCamelCase : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=SCREAMING_SNAKE_CASE , ) _lowerCamelCase : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : str = 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) _lowerCamelCase : Dict = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=512 , ) _lowerCamelCase : Dict = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : Dict = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> Any: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : Tuple = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = { """prompt""": """a cat and a frog""", """token_indices""": [2, 5], """generator""": generator, """num_inference_steps""": 1, """guidance_scale""": 6.0, """output_type""": """numpy""", """max_iter_to_alter""": 2, """thresholds""": {0: 0.7}, } return inputs def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Dict = """cpu""" _lowerCamelCase : Tuple = self.get_dummy_components() _lowerCamelCase : Tuple = self.pipeline_class(**SCREAMING_SNAKE_CASE) pipe.to(SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = pipe(**SCREAMING_SNAKE_CASE).images _lowerCamelCase : List[str] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 64, 64, 3)) _lowerCamelCase : int = np.array( [0.63_90_53_64, 0.62_89_73_07, 0.48_59_90_17, 0.5_13_36_24, 0.5_55_00_48, 0.45_76_95_16, 0.50_32_69_73, 0.5_02_31_39, 0.45_38_44_96]) _lowerCamelCase : Any = np.abs(image_slice.flatten() - expected_slice).max() self.assertLessEqual(SCREAMING_SNAKE_CASE , 1e-3) def UpperCamelCase_ ( self) -> List[str]: super().test_cpu_offload_forward_pass(expected_max_diff=5e-4) def UpperCamelCase_ ( self) -> Optional[Any]: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2]) def UpperCamelCase_ ( self) -> Optional[Any]: self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7e-4) def UpperCamelCase_ ( self) -> Tuple: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3) def UpperCamelCase_ ( self) -> str: super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4) def UpperCamelCase_ ( self) -> str: super().test_save_load_local(expected_max_difference=5e-4) def UpperCamelCase_ ( self) -> int: super().test_save_load_optional_components(expected_max_difference=4e-4) @require_torch_gpu @slow class lowercase__ ( unittest.TestCase ): @classmethod def UpperCamelCase_ ( cls) -> Any: super().setUpClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE) @classmethod def UpperCamelCase_ ( cls) -> str: super().tearDownClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Dict = torch.manual_seed(51) _lowerCamelCase : str = StableDiffusionAttendAndExcitePipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , safety_checker=SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa) pipe.to("""cuda""") _lowerCamelCase : List[str] = """a painting of an elephant with glasses""" _lowerCamelCase : Optional[Any] = [5, 7] _lowerCamelCase : List[Any] = pipe( prompt=SCREAMING_SNAKE_CASE , token_indices=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , generator=SCREAMING_SNAKE_CASE , num_inference_steps=5 , max_iter_to_alter=5 , output_type="""numpy""" , ).images[0] _lowerCamelCase : Tuple = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy""") assert np.abs((expected_image - image).max()) < 5e-1
88
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo UpperCAmelCase = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ UpperCAmelCase = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ UpperCAmelCase = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence"""), """references""": datasets.Sequence( datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence""") , id="""references"""), }) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 4 , ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=SCREAMING_SNAKE_CASE , hypotheses=SCREAMING_SNAKE_CASE , min_len=SCREAMING_SNAKE_CASE , max_len=SCREAMING_SNAKE_CASE) }
88
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionPanoramaPipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS def UpperCamelCase_ ( self) -> str: torch.manual_seed(0) _lowerCamelCase : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : Optional[Any] = DDIMScheduler() torch.manual_seed(0) _lowerCamelCase : 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 , ) torch.manual_seed(0) _lowerCamelCase : Dict = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : Any = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[str] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> Tuple: _lowerCamelCase : Optional[int] = torch.manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = { """prompt""": """a photo of the dolomites""", """generator""": generator, # Setting height and width to None to prevent OOMs on CPU. """height""": None, """width""": None, """num_inference_steps""": 1, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : Optional[int] = self.get_dummy_components() _lowerCamelCase : Dict = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = sd_pipe.to(SCREAMING_SNAKE_CASE) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = sd_pipe(**SCREAMING_SNAKE_CASE).images _lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCamelCase : Any = np.array([0.61_86, 0.53_74, 0.49_15, 0.41_35, 0.41_14, 0.45_63, 0.51_28, 0.49_77, 0.47_57]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def UpperCamelCase_ ( self) -> Tuple: super().test_inference_batch_consistent(batch_sizes=[1, 2]) def UpperCamelCase_ ( self) -> int: super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.2_5e-3) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : List[Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : int = self.get_dummy_components() _lowerCamelCase : Union[str, Any] = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = sd_pipe.to(SCREAMING_SNAKE_CASE) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.get_dummy_inputs(SCREAMING_SNAKE_CASE) _lowerCamelCase : int = """french fries""" _lowerCamelCase : List[str] = sd_pipe(**SCREAMING_SNAKE_CASE , negative_prompt=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = output.images _lowerCamelCase : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCamelCase : Optional[int] = np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : int = """cpu""" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : Any = self.get_dummy_components() _lowerCamelCase : Tuple = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = sd_pipe.to(SCREAMING_SNAKE_CASE) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.get_dummy_inputs(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = sd_pipe(**SCREAMING_SNAKE_CASE , view_batch_size=2) _lowerCamelCase : List[Any] = output.images _lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCamelCase : List[str] = np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def UpperCamelCase_ ( self) -> int: _lowerCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : str = self.get_dummy_components() _lowerCamelCase : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""") _lowerCamelCase : str = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = sd_pipe.to(SCREAMING_SNAKE_CASE) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE) _lowerCamelCase : int = sd_pipe(**SCREAMING_SNAKE_CASE).images _lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCamelCase : Dict = np.array([0.40_24, 0.65_10, 0.49_01, 0.53_78, 0.58_13, 0.56_22, 0.47_95, 0.44_67, 0.49_52]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def UpperCamelCase_ ( self) -> int: _lowerCamelCase : int = """cpu""" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : Tuple = self.get_dummy_components() _lowerCamelCase : Any = PNDMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , skip_prk_steps=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = sd_pipe.to(SCREAMING_SNAKE_CASE) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = sd_pipe(**SCREAMING_SNAKE_CASE).images _lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _lowerCamelCase : Union[str, Any] = np.array([0.63_91, 0.62_91, 0.48_61, 0.51_34, 0.55_52, 0.45_78, 0.50_32, 0.50_23, 0.45_39]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Dict: super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=0) -> str: _lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = { """prompt""": """a photo of the dolomites""", """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Tuple = """stabilityai/stable-diffusion-2-base""" _lowerCamelCase : Optional[Any] = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE , subfolder="""scheduler""") _lowerCamelCase : Union[str, Any] = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , safety_checker=SCREAMING_SNAKE_CASE) pipe.to(SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) pipe.enable_attention_slicing() _lowerCamelCase : int = self.get_inputs() _lowerCamelCase : Dict = pipe(**SCREAMING_SNAKE_CASE).images _lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) _lowerCamelCase : Union[str, Any] = np.array( [ 0.36_96_83_92, 0.27_02_53_72, 0.32_44_67_66, 0.28_37_93_87, 0.36_36_32_74, 0.30_73_33_47, 0.27_10_00_27, 0.27_05_41_25, 0.25_53_60_96, ]) assert np.abs(expected_slice - image_slice).max() < 1e-2 def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : int = StableDiffusionPanoramaPipeline.from_pretrained( """stabilityai/stable-diffusion-2-base""" , safety_checker=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = LMSDiscreteScheduler.from_config(pipe.scheduler.config) pipe.to(SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) pipe.enable_attention_slicing() _lowerCamelCase : Optional[int] = self.get_inputs() _lowerCamelCase : str = pipe(**SCREAMING_SNAKE_CASE).images _lowerCamelCase : int = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) _lowerCamelCase : int = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ]) assert np.abs(expected_slice - image_slice).max() < 1e-3 def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : List[str] = 0 def callback_fn(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> None: _lowerCamelCase : str = True nonlocal number_of_steps number_of_steps += 1 if step == 1: _lowerCamelCase : int = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) _lowerCamelCase : Dict = latents[0, -3:, -3:, -1] _lowerCamelCase : Tuple = np.array( [ 0.18_68_18_69, 0.33_90_78_16, 0.5_36_12_76, 0.14_43_28_65, -0.02_85_66_11, -0.73_94_11_23, 0.23_39_79_87, 0.47_32_26_82, -0.37_82_31_64, ]) assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2 elif step == 2: _lowerCamelCase : int = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) _lowerCamelCase : int = latents[0, -3:, -3:, -1] _lowerCamelCase : Tuple = np.array( [ 0.18_53_96_45, 0.33_98_72_48, 0.5_37_85_59, 0.14_43_71_42, -0.02_45_52_61, -0.7_33_83_17, 0.23_99_07_55, 0.47_35_62_72, -0.3_78_65_05, ]) assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2 _lowerCamelCase : Any = False _lowerCamelCase : Optional[Any] = """stabilityai/stable-diffusion-2-base""" _lowerCamelCase : Optional[Any] = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE , subfolder="""scheduler""") _lowerCamelCase : int = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , safety_checker=SCREAMING_SNAKE_CASE) _lowerCamelCase : str = pipe.to(SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) pipe.enable_attention_slicing() _lowerCamelCase : Dict = self.get_inputs() pipe(**SCREAMING_SNAKE_CASE , callback=SCREAMING_SNAKE_CASE , callback_steps=1) assert callback_fn.has_been_called assert number_of_steps == 3 def UpperCamelCase_ ( self) -> Tuple: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _lowerCamelCase : Tuple = """stabilityai/stable-diffusion-2-base""" _lowerCamelCase : List[str] = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE , subfolder="""scheduler""") _lowerCamelCase : Any = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , safety_checker=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = pipe.to(SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) pipe.enable_attention_slicing(1) pipe.enable_sequential_cpu_offload() _lowerCamelCase : int = self.get_inputs() _lowerCamelCase : int = pipe(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
88
"""simple docstring""" def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : str = len(__snake_case ) _lowerCamelCase : Union[str, Any] = len(__snake_case ) _lowerCamelCase : int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] _lowerCamelCase : Union[str, Any] = True for i in range(__snake_case ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: _lowerCamelCase : Tuple = True if a[i].islower(): _lowerCamelCase : Tuple = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase = { """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""MvpTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""MvpTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ """MVP_PRETRAINED_MODEL_ARCHIVE_LIST""", """MvpForCausalLM""", """MvpForConditionalGeneration""", """MvpForQuestionAnswering""", """MvpForSequenceClassification""", """MvpModel""", """MvpPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
"""simple docstring""" import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> None: warnings.warn( """The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ImageGPTImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE)
88
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """facebook/s2t-wav2vec2-large-en-de""": ( """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json""" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class lowercase__ ( A_ ): __UpperCAmelCase = '''speech_to_text_2''' __UpperCAmelCase = ['''past_key_values'''] __UpperCAmelCase = {'''num_attention_heads''': '''decoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self , SCREAMING_SNAKE_CASE=1_0000 , SCREAMING_SNAKE_CASE=6 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE="relu" , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=1024 , **SCREAMING_SNAKE_CASE , ) -> Dict: _lowerCamelCase : Dict = vocab_size _lowerCamelCase : str = d_model _lowerCamelCase : List[str] = decoder_ffn_dim _lowerCamelCase : Tuple = decoder_layers _lowerCamelCase : str = decoder_attention_heads _lowerCamelCase : Dict = dropout _lowerCamelCase : Union[str, Any] = attention_dropout _lowerCamelCase : int = activation_dropout _lowerCamelCase : str = activation_function _lowerCamelCase : Dict = init_std _lowerCamelCase : Optional[Any] = decoder_layerdrop _lowerCamelCase : Dict = use_cache _lowerCamelCase : str = decoder_layers _lowerCamelCase : str = scale_embedding # scale factor will be sqrt(d_model) if True _lowerCamelCase : Optional[Any] = max_target_positions super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , decoder_start_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , )
88
"""simple docstring""" from math import isqrt, loga def _snake_case ( __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __snake_case , __snake_case ): _lowerCamelCase : Optional[int] = False return [i for i in range(2 , __snake_case ) if is_prime[i]] def _snake_case ( __snake_case : int = 800800 , __snake_case : int = 800800 ): """simple docstring""" _lowerCamelCase : Union[str, Any] = degree * loga(__snake_case ) _lowerCamelCase : Union[str, Any] = int(__snake_case ) _lowerCamelCase : Dict = calculate_prime_numbers(__snake_case ) _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : Any = 0 _lowerCamelCase : Any = len(__snake_case ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f'''{solution() = }''')
88
1
"""simple docstring""" import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig UpperCAmelCase = logging.get_logger(__name__) class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : Any = question_encoder _lowerCamelCase : Optional[int] = generator _lowerCamelCase : Tuple = self.question_encoder def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> Union[str, Any]: if os.path.isfile(SCREAMING_SNAKE_CASE): raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file') os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = os.path.join(SCREAMING_SNAKE_CASE , """question_encoder_tokenizer""") _lowerCamelCase : Any = os.path.join(SCREAMING_SNAKE_CASE , """generator_tokenizer""") self.question_encoder.save_pretrained(SCREAMING_SNAKE_CASE) self.generator.save_pretrained(SCREAMING_SNAKE_CASE) @classmethod def UpperCamelCase_ ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> Optional[int]: # dynamically import AutoTokenizer from ..auto.tokenization_auto import AutoTokenizer _lowerCamelCase : Optional[int] = kwargs.pop("""config""" , SCREAMING_SNAKE_CASE) if config is None: _lowerCamelCase : Dict = RagConfig.from_pretrained(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE , config=config.question_encoder , subfolder="""question_encoder_tokenizer""") _lowerCamelCase : Tuple = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE , config=config.generator , subfolder="""generator_tokenizer""") return cls(question_encoder=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE) def __call__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> str: return self.current_tokenizer(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> List[str]: return self.generator.batch_decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> List[Any]: return self.generator.decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : List[str] = self.question_encoder def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : List[str] = self.generator def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "longest" , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = True , **SCREAMING_SNAKE_CASE , ) -> BatchEncoding: warnings.warn( """`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the """ """regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` """ """context manager to prepare your targets. See the documentation of your specific tokenizer for more """ """details""" , SCREAMING_SNAKE_CASE , ) if max_length is None: _lowerCamelCase : Union[str, Any] = self.current_tokenizer.model_max_length _lowerCamelCase : Dict = self( SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: _lowerCamelCase : List[Any] = self.current_tokenizer.model_max_length _lowerCamelCase : int = self( text_target=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) _lowerCamelCase : Dict = labels["""input_ids"""] return model_inputs
88
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionSAGPipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: torch.manual_seed(0) _lowerCamelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0) _lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : List[Any] = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> List[Any]: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""") _lowerCamelCase : Union[str, Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = """.""" _lowerCamelCase : int = torch.manual_seed(0) _lowerCamelCase : Tuple = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Dict = output.images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Optional[Any] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Dict = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = """.""" _lowerCamelCase : List[str] = torch.manual_seed(0) _lowerCamelCase : int = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Any = output.images _lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Optional[Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """.""" _lowerCamelCase : Union[str, Any] = torch.manual_seed(0) _lowerCamelCase : Optional[int] = sag_pipe( [prompt] , width=768 , height=512 , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) _lowerCamelCase : Union[str, Any] = output.images assert image.shape == (1, 512, 768, 3)
88
1
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCAmelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""") @dataclass class lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_mae""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. _lowerCamelCase : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = split["""test"""] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _lowerCamelCase : str = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = ViTMAEConfig() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) # adapt config config.update( { """mask_ratio""": model_args.mask_ratio, """norm_pix_loss""": model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=64 , ) -> Optional[int]: _lowerCamelCase : List[str] = parent _lowerCamelCase : List[Any] = batch_size _lowerCamelCase : Tuple = is_training _lowerCamelCase : Tuple = use_auxiliary_loss _lowerCamelCase : Any = num_queries _lowerCamelCase : List[str] = num_channels _lowerCamelCase : List[str] = min_size _lowerCamelCase : Tuple = max_size _lowerCamelCase : str = num_labels _lowerCamelCase : Any = hidden_dim _lowerCamelCase : Dict = hidden_dim def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) > 0.5 ).float() _lowerCamelCase : Dict = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE) > 0.5).long() _lowerCamelCase : Optional[int] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCamelCase_ ( self) -> str: _lowerCamelCase : List[str] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _lowerCamelCase : Any = self.num_queries _lowerCamelCase : int = self.num_labels _lowerCamelCase : int = [1, 1, 1, 1] _lowerCamelCase : Any = self.num_channels _lowerCamelCase : Optional[Any] = 64 _lowerCamelCase : str = 128 _lowerCamelCase : Optional[Any] = self.hidden_dim _lowerCamelCase : Any = self.hidden_dim _lowerCamelCase : List[Any] = self.hidden_dim return config def UpperCamelCase_ ( self) -> Any: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = self.prepare_config_and_inputs() _lowerCamelCase : str = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : str = output.encoder_hidden_states _lowerCamelCase : int = output.pixel_decoder_hidden_states _lowerCamelCase : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , config.decoder_layers) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False) -> List[str]: with torch.no_grad(): _lowerCamelCase : Optional[int] = MaskaFormerModel(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[int] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = model(SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(output.encoder_last_hidden_state is not None) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : str = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(result.encoder_last_hidden_state is not None) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1)) with torch.no_grad(): _lowerCamelCase : List[Any] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model( pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape , torch.Size([1])) @require_torch class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = MaskaFormerModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> int: _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""") def UpperCamelCase_ ( self) -> Optional[int]: pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""") def UpperCamelCase_ ( self) -> Tuple: pass @unittest.skip(reason="""Mask2Former is not a generative model""") def UpperCamelCase_ ( self) -> List[Any]: pass @unittest.skip(reason="""Mask2Former does not use token embeddings""") def UpperCamelCase_ ( self) -> Any: pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""") def UpperCamelCase_ ( self) -> Dict: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""") def UpperCamelCase_ ( self) -> Optional[int]: pass def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : str = [*signature.parameters.keys()] _lowerCamelCase : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> Optional[int]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _lowerCamelCase : Optional[int] = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Dict = (self.model_tester.min_size,) * 2 _lowerCamelCase : str = { """pixel_values""": torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE), """mask_labels""": torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE), """class_labels""": torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE).long(), } _lowerCamelCase : List[str] = self.model_tester.get_config() _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE , output_attentions=SCREAMING_SNAKE_CASE) self.assertTrue(outputs.attentions is not None) def UpperCamelCase_ ( self) -> Optional[Any]: if not self.model_tester.is_training: return _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE).loss loss.backward() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : int = True _lowerCamelCase : Optional[Any] = True _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _lowerCamelCase : int = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _lowerCamelCase : str = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _lowerCamelCase : Optional[int] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(pixel_decoder_hidden_states.grad) self.assertIsNotNone(transformer_decoder_hidden_states.grad) self.assertIsNotNone(attentions.grad) UpperCAmelCase = 1e-4 def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def UpperCamelCase_ ( self) -> Union[str, Any]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Tuple = MaskaFormerModel.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : List[str] = prepare_img() _lowerCamelCase : Union[str, Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Any = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Dict = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : Optional[Any] = self.default_image_processor _lowerCamelCase : Any = prepare_img() _lowerCamelCase : Dict = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : List[str] = model(**SCREAMING_SNAKE_CASE) # masks_queries_logits _lowerCamelCase : str = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)) _lowerCamelCase : Any = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] _lowerCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) # class_queries_logits _lowerCamelCase : List[str] = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1)) _lowerCamelCase : Optional[Any] = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ]).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : Tuple = image_processor( [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors="""pt""" , ) _lowerCamelCase : Optional[Any] = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""mask_labels"""]] _lowerCamelCase : Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""class_labels"""]] with torch.no_grad(): _lowerCamelCase : Any = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None)
88
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class lowercase__ : __UpperCAmelCase = BlenderbotSmallConfig __UpperCAmelCase = {} __UpperCAmelCase = '''gelu''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=20 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , ) -> Union[str, Any]: _lowerCamelCase : List[Any] = parent _lowerCamelCase : Dict = batch_size _lowerCamelCase : List[str] = seq_length _lowerCamelCase : Union[str, Any] = is_training _lowerCamelCase : Optional[int] = use_labels _lowerCamelCase : List[str] = vocab_size _lowerCamelCase : int = hidden_size _lowerCamelCase : Optional[int] = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : Tuple = intermediate_size _lowerCamelCase : Tuple = hidden_dropout_prob _lowerCamelCase : List[str] = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Optional[int] = eos_token_id _lowerCamelCase : List[str] = pad_token_id _lowerCamelCase : Dict = bos_token_id def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size) _lowerCamelCase : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) , 1) _lowerCamelCase : str = tf.concat([input_ids, eos_tensor] , axis=1) _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _lowerCamelCase : Optional[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _lowerCamelCase : Tuple = prepare_blenderbot_small_inputs_dict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) return config, inputs_dict def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Union[str, Any]: _lowerCamelCase : List[str] = TFBlenderbotSmallModel(config=SCREAMING_SNAKE_CASE).get_decoder() _lowerCamelCase : int = inputs_dict["""input_ids"""] _lowerCamelCase : List[str] = input_ids[:1, :] _lowerCamelCase : Any = inputs_dict["""attention_mask"""][:1, :] _lowerCamelCase : Any = inputs_dict["""head_mask"""] _lowerCamelCase : Union[str, Any] = 1 # first forward pass _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , head_mask=SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE) _lowerCamelCase , _lowerCamelCase : int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _lowerCamelCase : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size) _lowerCamelCase : List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2) , tf.inta) # append to next input_ids and _lowerCamelCase : List[str] = tf.concat([input_ids, next_tokens] , axis=-1) _lowerCamelCase : Optional[Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1) _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE)[0] _lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , past_key_values=SCREAMING_SNAKE_CASE)[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1]) # select random slice _lowerCamelCase : Union[str, Any] = int(ids_tensor((1,) , output_from_past.shape[-1])) _lowerCamelCase : Tuple = output_from_no_past[:, -3:, random_slice_idx] _lowerCamelCase : Optional[int] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , rtol=1e-3) def _snake_case ( __snake_case : str , __snake_case : Tuple , __snake_case : Optional[Any] , __snake_case : Optional[int]=None , __snake_case : Any=None , __snake_case : Optional[int]=None , __snake_case : str=None , __snake_case : str=None , ): """simple docstring""" if attention_mask is None: _lowerCamelCase : Any = tf.cast(tf.math.not_equal(__snake_case , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: _lowerCamelCase : Any = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: _lowerCamelCase : str = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _lowerCamelCase : Union[str, Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _lowerCamelCase : int = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __UpperCAmelCase = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __UpperCAmelCase = ( { '''conversational''': TFBlenderbotSmallForConditionalGeneration, '''feature-extraction''': TFBlenderbotSmallModel, '''summarization''': TFBlenderbotSmallForConditionalGeneration, '''text2text-generation''': TFBlenderbotSmallForConditionalGeneration, '''translation''': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __UpperCAmelCase = True __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = TFBlenderbotSmallModelTester(self) _lowerCamelCase : Tuple = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[Any]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE) @require_tokenizers @require_tf class lowercase__ ( unittest.TestCase ): __UpperCAmelCase = [ '''Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ''' ''' i\'m going to throw up.\nand why is that?''' ] __UpperCAmelCase = '''facebook/blenderbot_small-90M''' @cached_property def UpperCamelCase_ ( self) -> Dict: # use "old" tokenizer here because of bug when downloading new tokenizer return BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""") @cached_property def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : int = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name) return model @slow def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : int = self.tokenizer(self.src_text , return_tensors="""tf""") _lowerCamelCase : List[Any] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=SCREAMING_SNAKE_CASE , ) _lowerCamelCase : Dict = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=SCREAMING_SNAKE_CASE)[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
88
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) UpperCAmelCase = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) UpperCAmelCase = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) UpperCAmelCase = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModel) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
88
1
"""simple docstring""" from math import sqrt def _snake_case ( __snake_case : int ): """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(__snake_case ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _snake_case ( __snake_case : int = 10001 ): """simple docstring""" _lowerCamelCase : str = 0 _lowerCamelCase : Any = 1 while count != nth and number < 3: number += 1 if is_prime(__snake_case ): count += 1 while count != nth: number += 2 if is_prime(__snake_case ): count += 1 return number if __name__ == "__main__": print(f'''{solution() = }''')
88
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
88
1
"""simple docstring""" from __future__ import annotations from math import pi, sqrt def _snake_case ( __snake_case : float , __snake_case : float ): """simple docstring""" if inductance <= 0: raise ValueError("""Inductance cannot be 0 or negative""" ) elif capacitance <= 0: raise ValueError("""Capacitance cannot be 0 or negative""" ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
88
"""simple docstring""" def _snake_case ( __snake_case : list[list[int]] , __snake_case : int , __snake_case : int , __snake_case : list[int] ): """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def _snake_case ( __snake_case : list[list[int]] , __snake_case : list[int] , __snake_case : int ): """simple docstring""" if curr_ind == len(__snake_case ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(__snake_case ) ): if valid_connection(__snake_case , __snake_case , __snake_case , __snake_case ): # Insert current vertex into path as next transition _lowerCamelCase : List[str] = next_ver # Validate created path if util_hamilton_cycle(__snake_case , __snake_case , curr_ind + 1 ): return True # Backtrack _lowerCamelCase : Tuple = -1 return False def _snake_case ( __snake_case : list[list[int]] , __snake_case : int = 0 ): """simple docstring""" _lowerCamelCase : Any = [-1] * (len(__snake_case ) + 1) # initialize start and end of path with starting index _lowerCamelCase : Optional[int] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__snake_case , __snake_case , 1 ) else []
88
1
"""simple docstring""" import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class lowercase__ ( A_ ,unittest.TestCase ): __UpperCAmelCase = TransfoXLTokenizer __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> List[Any]: super().setUp() _lowerCamelCase : List[Any] = [ """<unk>""", """[CLS]""", """[SEP]""", """want""", """unwanted""", """wa""", """un""", """running""", """,""", """low""", """l""", ] _lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""]) with open(self.vocab_file , """w""" , encoding="""utf-8""") as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens])) def UpperCamelCase_ ( self , **SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : Union[str, Any] = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : Optional[int] = """<unk> UNwanted , running""" _lowerCamelCase : int = """<unk> unwanted, running""" return input_text, output_text def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Optional[Any] = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = tokenizer.tokenize("""<unk> UNwanted , running""") self.assertListEqual(SCREAMING_SNAKE_CASE , ["""<unk>""", """unwanted""", """,""", """running"""]) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE) , [0, 4, 8, 7]) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Tuple = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """) , ["""hello""", """!""", """how""", """are""", """you""", """?"""]) def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : Optional[Any] = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""]) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : int = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?""" _lowerCamelCase : str = [ """Hello""", """(""", """bracket""", """)""", """and""", """side""", """@-@""", """scrolled""", """[""", """and""", """]""", """Henry""", """'s""", """$""", """5""", """@,@""", """000""", """with""", """3""", """@.@""", """34""", """m""", """.""", """What""", """'s""", """up""", """!""", """?""", ] self.assertListEqual(tokenizer.tokenize(SCREAMING_SNAKE_CASE) , SCREAMING_SNAKE_CASE) self.assertEqual(tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE) , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Optional[int] = self.get_tokenizer() _lowerCamelCase : Any = len(SCREAMING_SNAKE_CASE) tokenizer.add_tokens(["""new1""", """new2"""]) tokenizer.move_added_token("""new1""" , 1) # Check that moved token is not copied (duplicate) self.assertEqual(len(SCREAMING_SNAKE_CASE) , original_len + 2) # Check that token is moved to specified id self.assertEqual(tokenizer.encode("""new1""") , [1]) self.assertEqual(tokenizer.decode([1]) , """new1""")
88
"""simple docstring""" import mpmath # for roots of unity import numpy as np class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None) -> Tuple: # Input as list _lowerCamelCase : Any = list(poly_a or [0])[:] _lowerCamelCase : Optional[Any] = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _lowerCamelCase : int = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() _lowerCamelCase : Union[str, Any] = len(self.polyB) # Add 0 to make lengths equal a power of 2 _lowerCamelCase : List[Any] = int( 2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1))) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform _lowerCamelCase : Optional[Any] = complex(mpmath.root(x=1 , n=self.c_max_length , k=1)) # The product _lowerCamelCase : int = self.__multiply() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Dict = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE) <= 1: return dft[0] # _lowerCamelCase : str = self.c_max_length // 2 while next_ncol > 0: _lowerCamelCase : Dict = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : Tuple = self.root**next_ncol # First half of next step _lowerCamelCase : int = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step _lowerCamelCase : Optional[int] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update _lowerCamelCase : Union[str, Any] = new_dft _lowerCamelCase : List[str] = next_ncol // 2 return dft[0] def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[Any] = self.__dft("""A""") _lowerCamelCase : List[str] = self.__dft("""B""") _lowerCamelCase : List[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT _lowerCamelCase : List[str] = 2 while next_ncol <= self.c_max_length: _lowerCamelCase : Any = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : List[Any] = self.root ** (next_ncol // 2) _lowerCamelCase : str = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root)) current_root *= root # Update _lowerCamelCase : Any = new_inverse_c next_ncol *= 2 # Unpack _lowerCamelCase : Optional[Any] = [round(x[0].real , 8) + round(x[0].imag , 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self) -> Any: _lowerCamelCase : Dict = """A = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A])) _lowerCamelCase : List[Any] = """B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B])) _lowerCamelCase : int = """A*B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.product)) return F'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase = logging.get_logger(__name__) def _snake_case ( __snake_case : str ): """simple docstring""" _lowerCamelCase : int = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: _lowerCamelCase : Union[str, Any] = 192 _lowerCamelCase : int = 768 _lowerCamelCase : Optional[Any] = 12 _lowerCamelCase : Optional[int] = 3 _lowerCamelCase : str = [800, 1333] _lowerCamelCase : Dict = False elif yolos_name == "yolos_s_dWr": _lowerCamelCase : List[str] = 330 _lowerCamelCase : Tuple = 14 _lowerCamelCase : List[Any] = 6 _lowerCamelCase : Optional[int] = 1320 elif "yolos_s" in yolos_name: _lowerCamelCase : int = 384 _lowerCamelCase : Optional[Any] = 1536 _lowerCamelCase : Union[str, Any] = 12 _lowerCamelCase : Any = 6 elif "yolos_b" in yolos_name: _lowerCamelCase : List[Any] = [800, 1344] _lowerCamelCase : Dict = 91 _lowerCamelCase : int = """huggingface/label-files""" _lowerCamelCase : List[Any] = """coco-detection-id2label.json""" _lowerCamelCase : Optional[Any] = json.load(open(hf_hub_download(__snake_case , __snake_case , repo_type="""dataset""" ) , """r""" ) ) _lowerCamelCase : Optional[Any] = {int(__snake_case ): v for k, v in idalabel.items()} _lowerCamelCase : int = idalabel _lowerCamelCase : Optional[Any] = {v: k for k, v in idalabel.items()} return config def _snake_case ( __snake_case : dict , __snake_case : YolosConfig , __snake_case : bool = False ): """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _lowerCamelCase : int = state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) _lowerCamelCase : Any = state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict _lowerCamelCase : Tuple = in_proj_weight[: config.hidden_size, :] _lowerCamelCase : Optional[int] = in_proj_bias[: config.hidden_size] _lowerCamelCase : List[str] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _lowerCamelCase : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _lowerCamelCase : int = in_proj_weight[-config.hidden_size :, :] _lowerCamelCase : Dict = in_proj_bias[-config.hidden_size :] def _snake_case ( __snake_case : str ): """simple docstring""" if "backbone" in name: _lowerCamelCase : Optional[Any] = name.replace("""backbone""" , """vit""" ) if "cls_token" in name: _lowerCamelCase : str = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "det_token" in name: _lowerCamelCase : str = name.replace("""det_token""" , """embeddings.detection_tokens""" ) if "mid_pos_embed" in name: _lowerCamelCase : Any = name.replace("""mid_pos_embed""" , """encoder.mid_position_embeddings""" ) if "pos_embed" in name: _lowerCamelCase : Dict = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: _lowerCamelCase : Union[str, Any] = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "blocks" in name: _lowerCamelCase : int = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: _lowerCamelCase : Any = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: _lowerCamelCase : Any = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: _lowerCamelCase : str = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: _lowerCamelCase : List[str] = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: _lowerCamelCase : List[Any] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: _lowerCamelCase : Optional[Any] = name.replace("""mlp.fc2""" , """output.dense""" ) if "class_embed" in name: _lowerCamelCase : Any = name.replace("""class_embed""" , """class_labels_classifier""" ) if "bbox_embed" in name: _lowerCamelCase : Optional[int] = name.replace("""bbox_embed""" , """bbox_predictor""" ) if "vit.norm" in name: _lowerCamelCase : str = name.replace("""vit.norm""" , """vit.layernorm""" ) return name def _snake_case ( __snake_case : dict , __snake_case : YolosForObjectDetection ): """simple docstring""" for key in orig_state_dict.copy().keys(): _lowerCamelCase : List[str] = orig_state_dict.pop(__snake_case ) if "qkv" in key: _lowerCamelCase : Any = key.split(""".""" ) _lowerCamelCase : Dict = int(key_split[2] ) _lowerCamelCase : Optional[int] = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: _lowerCamelCase : Dict = val[:dim, :] _lowerCamelCase : str = val[ dim : dim * 2, : ] _lowerCamelCase : Union[str, Any] = val[-dim:, :] else: _lowerCamelCase : Optional[Any] = val[:dim] _lowerCamelCase : Optional[Any] = val[dim : dim * 2] _lowerCamelCase : List[str] = val[-dim:] else: _lowerCamelCase : int = val return orig_state_dict def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" _lowerCamelCase : Any = Image.open(requests.get(__snake_case , stream=__snake_case ).raw ) return im @torch.no_grad() def _snake_case ( __snake_case : str , __snake_case : str , __snake_case : str , __snake_case : bool = False ): """simple docstring""" _lowerCamelCase : str = get_yolos_config(__snake_case ) # load original state_dict _lowerCamelCase : Any = torch.load(__snake_case , map_location="""cpu""" )["""model"""] # load 🤗 model _lowerCamelCase : Dict = YolosForObjectDetection(__snake_case ) model.eval() _lowerCamelCase : Optional[Any] = convert_state_dict(__snake_case , __snake_case ) model.load_state_dict(__snake_case ) # Check outputs on an image, prepared by YolosImageProcessor _lowerCamelCase : List[Any] = 800 if yolos_name != """yolos_ti""" else 512 _lowerCamelCase : str = YolosImageProcessor(format="""coco_detection""" , size=__snake_case ) _lowerCamelCase : List[str] = image_processor(images=prepare_img() , return_tensors="""pt""" ) _lowerCamelCase : Optional[Any] = model(**__snake_case ) _lowerCamelCase , _lowerCamelCase : List[Any] = outputs.logits, outputs.pred_boxes _lowerCamelCase , _lowerCamelCase : Tuple = None, None if yolos_name == "yolos_ti": _lowerCamelCase : Union[str, Any] = torch.tensor( [[-39.5022, -11.9820, -17.6888], [-29.9574, -9.9769, -17.7691], [-42.3281, -20.7200, -30.6294]] ) _lowerCamelCase : Any = torch.tensor( [[0.4021, 0.0836, 0.7979], [0.0184, 0.2609, 0.0364], [0.1781, 0.2004, 0.2095]] ) elif yolos_name == "yolos_s_200_pre": _lowerCamelCase : List[str] = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] ) _lowerCamelCase : int = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] ) elif yolos_name == "yolos_s_300_pre": _lowerCamelCase : Any = torch.tensor( [[-36.2220, -14.4385, -23.5457], [-35.6970, -14.7583, -21.3935], [-31.5939, -13.6042, -16.8049]] ) _lowerCamelCase : List[str] = torch.tensor( [[0.7614, 0.2316, 0.4728], [0.7168, 0.4495, 0.3855], [0.4996, 0.1466, 0.9996]] ) elif yolos_name == "yolos_s_dWr": _lowerCamelCase : Optional[int] = torch.tensor( [[-42.8668, -24.1049, -41.1690], [-34.7456, -14.1274, -24.9194], [-33.7898, -12.1946, -25.6495]] ) _lowerCamelCase : Optional[int] = torch.tensor( [[0.5587, 0.2773, 0.0605], [0.5004, 0.3014, 0.9994], [0.4999, 0.1548, 0.9994]] ) elif yolos_name == "yolos_base": _lowerCamelCase : Union[str, Any] = torch.tensor( [[-40.6064, -24.3084, -32.6447], [-55.1990, -30.7719, -35.5877], [-51.4311, -33.3507, -35.6462]] ) _lowerCamelCase : List[Any] = torch.tensor( [[0.5555, 0.2794, 0.0655], [0.9049, 0.2664, 0.1894], [0.9183, 0.1984, 0.1635]] ) else: raise ValueError(F'Unknown yolos_name: {yolos_name}' ) assert torch.allclose(logits[0, :3, :3] , __snake_case , atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , __snake_case , atol=1E-4 ) Path(__snake_case ).mkdir(exist_ok=__snake_case ) print(F'Saving model {yolos_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__snake_case ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(__snake_case ) if push_to_hub: _lowerCamelCase : Any = { """yolos_ti""": """yolos-tiny""", """yolos_s_200_pre""": """yolos-small""", """yolos_s_300_pre""": """yolos-small-300""", """yolos_s_dWr""": """yolos-small-dwr""", """yolos_base""": """yolos-base""", } print("""Pushing to the hub...""" ) _lowerCamelCase : List[str] = model_mapping[yolos_name] image_processor.push_to_hub(__snake_case , organization="""hustvl""" ) model.push_to_hub(__snake_case , organization="""hustvl""" ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--yolos_name""", default="""yolos_s_200_pre""", type=str, help=( """Name of the YOLOS model you'd like to convert. Should be one of 'yolos_ti', 'yolos_s_200_pre',""" """ 'yolos_s_300_pre', 'yolos_s_dWr', 'yolos_base'.""" ), ) parser.add_argument( """--checkpoint_path""", default=None, type=str, help="""Path to the original state dict (.pth file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) UpperCAmelCase = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
88
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase = { """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""VisionEncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""TFVisionEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""FlaxVisionEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel from diffusers.utils.testing_utils import ( enable_full_determinism, load_numpy, nightly, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowercase__ ( A_ ,unittest.TestCase ): __UpperCAmelCase = LDMTextToImagePipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS - { '''negative_prompt''', '''negative_prompt_embeds''', '''cross_attention_kwargs''', '''prompt_embeds''', } __UpperCAmelCase = PipelineTesterMixin.required_optional_params - { '''num_images_per_prompt''', '''callback''', '''callback_steps''', } __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = False def UpperCamelCase_ ( self) -> List[str]: torch.manual_seed(0) _lowerCamelCase : Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : List[Any] = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : 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 , ) torch.manual_seed(0) _lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : str = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[str] = { """unet""": unet, """scheduler""": scheduler, """vqvae""": vae, """bert""": text_encoder, """tokenizer""": tokenizer, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> str: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : Dict = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : Optional[int] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = { """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 UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator _lowerCamelCase : List[Any] = self.get_dummy_components() _lowerCamelCase : int = LDMTextToImagePipeline(**SCREAMING_SNAKE_CASE) pipe.to(SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = self.get_dummy_inputs(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = pipe(**SCREAMING_SNAKE_CASE).images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 16, 16, 3) _lowerCamelCase : Optional[Any] = np.array([0.61_01, 0.61_56, 0.56_22, 0.48_95, 0.66_61, 0.38_04, 0.57_48, 0.61_36, 0.50_14]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> str: super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=torch.floataa , SCREAMING_SNAKE_CASE=0) -> List[Any]: _lowerCamelCase : Optional[int] = torch.manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = np.random.RandomState(SCREAMING_SNAKE_CASE).standard_normal((1, 4, 32, 32)) _lowerCamelCase : List[Any] = torch.from_numpy(SCREAMING_SNAKE_CASE).to(device=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : Any = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""").to(SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = self.get_inputs(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = pipe(**SCREAMING_SNAKE_CASE).images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 256, 256, 3) _lowerCamelCase : str = np.array([0.5_18_25, 0.5_28_50, 0.5_25_43, 0.5_42_58, 0.5_23_04, 0.5_25_69, 0.5_43_63, 0.5_52_76, 0.5_68_78]) _lowerCamelCase : Optional[int] = np.abs(expected_slice - image_slice).max() assert max_diff < 1e-3 @nightly @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Optional[int]: super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=torch.floataa , SCREAMING_SNAKE_CASE=0) -> int: _lowerCamelCase : Union[str, Any] = torch.manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = np.random.RandomState(SCREAMING_SNAKE_CASE).standard_normal((1, 4, 32, 32)) _lowerCamelCase : str = torch.from_numpy(SCREAMING_SNAKE_CASE).to(device=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = { """prompt""": """A painting of a squirrel eating a burger""", """latents""": latents, """generator""": generator, """num_inference_steps""": 50, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Union[str, Any] = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""").to(SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.get_inputs(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = pipe(**SCREAMING_SNAKE_CASE).images[0] _lowerCamelCase : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy""") _lowerCamelCase : str = np.abs(expected_image - image).max() assert max_diff < 1e-3
88
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def _snake_case ( __snake_case : List[str] ): """simple docstring""" for param in module.parameters(): _lowerCamelCase : Optional[Any] = False def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _lowerCamelCase : Any = """mps""" if device == "mps": print( """WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch""" """ errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues""" """ with generations.""" ) return device def _snake_case ( __snake_case : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = plt.imshow(__snake_case ) fig.axes.get_xaxis().set_visible(__snake_case ) fig.axes.get_yaxis().set_visible(__snake_case ) plt.show() def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = datetime.now() _lowerCamelCase : Optional[Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
88
1
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name class lowercase__ ( A_ ): def __init__( 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 , ) -> Union[str, Any]: super().__init__() if safety_checker is None: logger.warning( F'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered""" """ results in services or applications open to the public. Both the diffusers team and Hugging Face""" """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling""" """ it only for use-cases that involve analyzing network behavior or auditing its results. For more""" """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 .""") self.register_modules( speech_model=SCREAMING_SNAKE_CASE , speech_processor=SCREAMING_SNAKE_CASE , vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE = "auto") -> Dict: if slice_size == "auto": _lowerCamelCase : int = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Any: self.enable_attention_slicing(SCREAMING_SNAKE_CASE) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=1_6000 , SCREAMING_SNAKE_CASE = 512 , SCREAMING_SNAKE_CASE = 512 , SCREAMING_SNAKE_CASE = 50 , SCREAMING_SNAKE_CASE = 7.5 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 0.0 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "pil" , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 1 , **SCREAMING_SNAKE_CASE , ) -> Dict: _lowerCamelCase : Dict = self.speech_processor.feature_extractor( SCREAMING_SNAKE_CASE , return_tensors="""pt""" , sampling_rate=SCREAMING_SNAKE_CASE).input_features.to(self.device) _lowerCamelCase : Union[str, Any] = self.speech_model.generate(SCREAMING_SNAKE_CASE , max_length=48_0000) _lowerCamelCase : Optional[int] = self.speech_processor.tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE , normalize=SCREAMING_SNAKE_CASE)[ 0 ] if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : Tuple = 1 elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : Union[str, Any] = len(SCREAMING_SNAKE_CASE) else: raise ValueError(F'`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE)}') if height % 8 != 0 or width % 8 != 0: raise ValueError(F'`height` and `width` have to be divisible by 8 but are {height} and {width}.') if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) or callback_steps <= 0) ): raise ValueError( F'`callback_steps` has to be a positive integer but is {callback_steps} of type' F' {type(SCREAMING_SNAKE_CASE)}.') # get prompt text embeddings _lowerCamelCase : Tuple = self.tokenizer( SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) _lowerCamelCase : Any = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: _lowerCamelCase : Union[str, Any] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F' {self.tokenizer.model_max_length} tokens: {removed_text}') _lowerCamelCase : int = text_input_ids[:, : self.tokenizer.model_max_length] _lowerCamelCase : Union[str, Any] = self.text_encoder(text_input_ids.to(self.device))[0] # duplicate text embeddings for each generation per prompt, using mps friendly method _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = text_embeddings.shape _lowerCamelCase : Optional[int] = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE , 1) _lowerCamelCase : Optional[int] = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE , -1) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. _lowerCamelCase : Optional[int] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: _lowerCamelCase : List[str] if negative_prompt is None: _lowerCamelCase : List[Any] = [""""""] * batch_size elif type(SCREAMING_SNAKE_CASE) is not type(SCREAMING_SNAKE_CASE): raise TypeError( F'`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE)} !=' F' {type(SCREAMING_SNAKE_CASE)}.') elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : Optional[Any] = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE): raise ValueError( F'`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE)}, but `prompt`:' F' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches' """ the batch size of `prompt`.""") else: _lowerCamelCase : Any = negative_prompt _lowerCamelCase : int = text_input_ids.shape[-1] _lowerCamelCase : str = self.tokenizer( SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , return_tensors="""pt""" , ) _lowerCamelCase : List[Any] = self.text_encoder(uncond_input.input_ids.to(self.device))[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method _lowerCamelCase : List[Any] = uncond_embeddings.shape[1] _lowerCamelCase : Optional[int] = uncond_embeddings.repeat(1 , SCREAMING_SNAKE_CASE , 1) _lowerCamelCase : List[Any] = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE , -1) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _lowerCamelCase : Optional[Any] = torch.cat([uncond_embeddings, text_embeddings]) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. _lowerCamelCase : Optional[int] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) _lowerCamelCase : Any = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps _lowerCamelCase : str = torch.randn(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE).to( self.device) else: _lowerCamelCase : List[str] = torch.randn(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device=self.device , dtype=SCREAMING_SNAKE_CASE) else: if latents.shape != latents_shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}') _lowerCamelCase : str = latents.to(self.device) # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand _lowerCamelCase : Union[str, Any] = self.scheduler.timesteps.to(self.device) # scale the initial noise by the standard deviation required by the scheduler _lowerCamelCase : Any = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] _lowerCamelCase : str = """eta""" in set(inspect.signature(self.scheduler.step).parameters.keys()) _lowerCamelCase : Dict = {} if accepts_eta: _lowerCamelCase : Any = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE)): # expand the latents if we are doing classifier free guidance _lowerCamelCase : Optional[int] = torch.cat([latents] * 2) if do_classifier_free_guidance else latents _lowerCamelCase : str = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # predict the noise residual _lowerCamelCase : str = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE).sample # perform guidance if do_classifier_free_guidance: _lowerCamelCase , _lowerCamelCase : Dict = noise_pred.chunk(2) _lowerCamelCase : int = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 _lowerCamelCase : Tuple = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = 1 / 0.1_82_15 * latents _lowerCamelCase : Tuple = self.vae.decode(SCREAMING_SNAKE_CASE).sample _lowerCamelCase : int = (image / 2 + 0.5).clamp(0 , 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 _lowerCamelCase : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": _lowerCamelCase : Optional[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE) if not return_dict: return image return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE , nsfw_content_detected=SCREAMING_SNAKE_CASE)
88
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCAmelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""") @dataclass class lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_mae""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. _lowerCamelCase : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = split["""test"""] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _lowerCamelCase : str = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = ViTMAEConfig() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) # adapt config config.update( { """mask_ratio""": model_args.mask_ratio, """norm_pix_loss""": model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
1
"""simple docstring""" import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class lowercase__ ( unittest.TestCase ): __UpperCAmelCase = inspect.getfile(accelerate.test_utils ) __UpperCAmelCase = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) __UpperCAmelCase = ['''accelerate''', '''launch'''] __UpperCAmelCase = Path.home() / '''.cache/huggingface/accelerate''' __UpperCAmelCase = '''default_config.yaml''' __UpperCAmelCase = config_folder / config_file __UpperCAmelCase = config_folder / '''_default_config.yaml''' __UpperCAmelCase = Path('''tests/test_configs''' ) @classmethod def UpperCamelCase_ ( cls) -> List[str]: if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path) @classmethod def UpperCamelCase_ ( cls) -> Tuple: if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy()) def UpperCamelCase_ ( self) -> int: for config in sorted(self.test_config_path.glob("""**/*.yaml""")): with self.subTest(config_file=SCREAMING_SNAKE_CASE): execute_subprocess_async( self.base_cmd + ["""--config_file""", str(SCREAMING_SNAKE_CASE), self.test_file_path] , env=os.environ.copy()) def UpperCamelCase_ ( self) -> Any: execute_subprocess_async(["""accelerate""", """test"""] , env=os.environ.copy()) class lowercase__ ( unittest.TestCase ): __UpperCAmelCase = '''test-tpu''' __UpperCAmelCase = '''us-central1-a''' __UpperCAmelCase = '''ls''' __UpperCAmelCase = ['''accelerate''', '''tpu-config'''] __UpperCAmelCase = '''cd /usr/share''' __UpperCAmelCase = '''tests/test_samples/test_command_file.sh''' __UpperCAmelCase = '''Running gcloud compute tpus tpu-vm ssh''' def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Union[str, Any] = run_command( self.cmd + ["""--command""", self.command, """--tpu_zone""", self.tpu_zone, """--tpu_name""", self.tpu_name, """--debug"""] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( F'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all' , SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> str: _lowerCamelCase : int = run_command( self.cmd + [ """--config_file""", """tests/test_configs/0_12_0.yaml""", """--command""", self.command, """--tpu_zone""", self.tpu_zone, """--tpu_name""", self.tpu_name, """--debug""", ] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( F'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all' , SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--debug"""] , return_stdout=SCREAMING_SNAKE_CASE) self.assertIn( F'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' , SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[int] = run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--command""", self.command, """--debug"""] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( F'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all' , SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = run_command( self.cmd + [ """--config_file""", """tests/test_configs/latest.yaml""", """--command""", self.command, """--command""", """echo \"Hello World\"""", """--debug""", ] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( F'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all' , SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : Union[str, Any] = run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--command_file""", self.command_file, """--debug"""] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( F'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' , SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = run_command( self.cmd + [ """--config_file""", """tests/test_configs/0_12_0.yaml""", """--command_file""", self.command_file, """--tpu_zone""", self.tpu_zone, """--tpu_name""", self.tpu_name, """--debug""", ] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( F'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' , SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : List[str] = run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--install_accelerate""", """--debug"""] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( F'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all' , SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = run_command( self.cmd + [ """--config_file""", """tests/test_configs/latest.yaml""", """--install_accelerate""", """--accelerate_version""", """12.0.0""", """--debug""", ] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( F'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all' , SCREAMING_SNAKE_CASE , )
88
"""simple docstring""" import numpy as np def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return vector * sigmoid(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """tanreinama/GPTSAN-2.8B-spout_is_uniform""": ( """https://huggingface.co/tanreinama/GPTSAN-2.8B-spout_is_uniform/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''gptsan-japanese''' __UpperCAmelCase = [ '''past_key_values''', ] __UpperCAmelCase = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , SCREAMING_SNAKE_CASE=3_6000 , SCREAMING_SNAKE_CASE=1280 , SCREAMING_SNAKE_CASE=1024 , SCREAMING_SNAKE_CASE=8192 , SCREAMING_SNAKE_CASE=4096 , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE="float32" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=0.0_02 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=3_5998 , SCREAMING_SNAKE_CASE=3_5995 , SCREAMING_SNAKE_CASE=3_5999 , **SCREAMING_SNAKE_CASE , ) -> Dict: _lowerCamelCase : List[Any] = vocab_size _lowerCamelCase : Dict = max_position_embeddings _lowerCamelCase : Tuple = d_model _lowerCamelCase : List[str] = d_ff _lowerCamelCase : Optional[int] = d_ext _lowerCamelCase : List[str] = d_spout _lowerCamelCase : Union[str, Any] = num_switch_layers _lowerCamelCase : Dict = num_ext_layers _lowerCamelCase : int = num_switch_layers + num_ext_layers _lowerCamelCase : Optional[Any] = num_heads _lowerCamelCase : List[str] = num_experts _lowerCamelCase : Any = expert_capacity _lowerCamelCase : List[str] = dropout_rate _lowerCamelCase : Optional[int] = layer_norm_epsilon _lowerCamelCase : Any = router_bias _lowerCamelCase : List[str] = router_jitter_noise _lowerCamelCase : int = router_dtype _lowerCamelCase : Tuple = router_ignore_padding_tokens _lowerCamelCase : Optional[int] = output_hidden_states _lowerCamelCase : Tuple = output_attentions _lowerCamelCase : List[Any] = initializer_factor _lowerCamelCase : str = output_router_logits _lowerCamelCase : Tuple = use_cache super().__init__( separator_token_id=SCREAMING_SNAKE_CASE , pad_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , )
88
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = HfArgumentParser(__snake_case ) _lowerCamelCase : int = parser.parse_args_into_dataclasses()[0] _lowerCamelCase : Dict = TensorFlowBenchmark(args=__snake_case ) try: _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: _lowerCamelCase : Union[str, Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" _lowerCamelCase : List[str] = """ """.join(str(__snake_case ).split(""" """ )[:-1] ) _lowerCamelCase : Dict = """""" _lowerCamelCase : List[Any] = eval(str(__snake_case ).split(""" """ )[-1] ) _lowerCamelCase : Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _lowerCamelCase : Tuple = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
88
1
"""simple docstring""" from math import factorial class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : List[Any] = real if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : Tuple = [1] * rank else: _lowerCamelCase : Any = rank def __repr__( self) -> Optional[Any]: return ( F'{self.real}+' F'{"+".join(str(SCREAMING_SNAKE_CASE)+"E"+str(n+1)for n,dual in enumerate(self.duals))}' ) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[int] = self.duals.copy() while cur[-1] == 0: cur.pop(-1) return Dual(self.real , SCREAMING_SNAKE_CASE) def __add__( self , SCREAMING_SNAKE_CASE) -> List[str]: if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): return Dual(self.real + other , self.duals) _lowerCamelCase : Optional[int] = self.duals.copy() _lowerCamelCase : List[Any] = other.duals.copy() if len(SCREAMING_SNAKE_CASE) > len(SCREAMING_SNAKE_CASE): o_dual.extend([1] * (len(SCREAMING_SNAKE_CASE) - len(SCREAMING_SNAKE_CASE))) elif len(SCREAMING_SNAKE_CASE) < len(SCREAMING_SNAKE_CASE): s_dual.extend([1] * (len(SCREAMING_SNAKE_CASE) - len(SCREAMING_SNAKE_CASE))) _lowerCamelCase : Any = [] for i in range(len(SCREAMING_SNAKE_CASE)): new_duals.append(s_dual[i] + o_dual[i]) return Dual(self.real + other.real , SCREAMING_SNAKE_CASE) __UpperCAmelCase = __add__ def __sub__( self , SCREAMING_SNAKE_CASE) -> Optional[int]: return self + other * -1 def __mul__( self , SCREAMING_SNAKE_CASE) -> Optional[Any]: if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : Union[str, Any] = [] for i in self.duals: new_duals.append(i * other) return Dual(self.real * other , SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = [0] * (len(self.duals) + len(other.duals) + 1) for i, item in enumerate(self.duals): for j, jtem in enumerate(other.duals): new_duals[i + j + 1] += item * jtem for k in range(len(self.duals)): new_duals[k] += self.duals[k] * other.real for index in range(len(other.duals)): new_duals[index] += other.duals[index] * self.real return Dual(self.real * other.real , SCREAMING_SNAKE_CASE) __UpperCAmelCase = __mul__ def __truediv__( self , SCREAMING_SNAKE_CASE) -> Optional[int]: if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : Union[str, Any] = [] for i in self.duals: new_duals.append(i / other) return Dual(self.real / other , SCREAMING_SNAKE_CASE) raise ValueError def __floordiv__( self , SCREAMING_SNAKE_CASE) -> int: if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : List[Any] = [] for i in self.duals: new_duals.append(i // other) return Dual(self.real // other , SCREAMING_SNAKE_CASE) raise ValueError def __pow__( self , SCREAMING_SNAKE_CASE) -> Optional[Any]: if n < 0 or isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): raise ValueError("""power must be a positive integer""") if n == 0: return 1 if n == 1: return self _lowerCamelCase : int = self for _ in range(n - 1): x *= self return x def _snake_case ( __snake_case : List[Any] , __snake_case : Dict , __snake_case : Dict ): """simple docstring""" if not callable(__snake_case ): raise ValueError("""differentiate() requires a function as input for func""" ) if not isinstance(__snake_case , (float, int) ): raise ValueError("""differentiate() requires a float as input for position""" ) if not isinstance(__snake_case , __snake_case ): raise ValueError("""differentiate() requires an int as input for order""" ) _lowerCamelCase : Any = Dual(__snake_case , 1 ) _lowerCamelCase : Tuple = func(__snake_case ) if order == 0: return result.real return result.duals[order - 1] * factorial(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod() def _snake_case ( __snake_case : Tuple ): """simple docstring""" return y**2 * y**4 print(differentiate(f, 9, 2))
88
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""", """kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""", """kssteven/ibert-roberta-large-mnli""": ( """https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''ibert''' def __init__( self , SCREAMING_SNAKE_CASE=3_0522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="none" , **SCREAMING_SNAKE_CASE , ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Dict = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Dict = type_vocab_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : Any = quant_mode _lowerCamelCase : List[str] = force_dequant class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
1
"""simple docstring""" from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase__ ( A_ ): __UpperCAmelCase = ['''image_processor''', '''tokenizer'''] __UpperCAmelCase = '''BlipImageProcessor''' __UpperCAmelCase = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Dict = False super().__init__(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = self.image_processor def __call__( self , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 0 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> BatchEncoding: if images is None and text is None: raise ValueError("""You have to specify either images or text.""") # Get only text if images is None: _lowerCamelCase : Any = self.tokenizer _lowerCamelCase : str = self.tokenizer( text=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , stride=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , return_overflowing_tokens=SCREAMING_SNAKE_CASE , return_special_tokens_mask=SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , return_token_type_ids=SCREAMING_SNAKE_CASE , return_length=SCREAMING_SNAKE_CASE , verbose=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) return text_encoding # add pixel_values _lowerCamelCase : Dict = self.image_processor(SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE) if text is not None: _lowerCamelCase : Optional[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , stride=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , return_overflowing_tokens=SCREAMING_SNAKE_CASE , return_special_tokens_mask=SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , return_token_type_ids=SCREAMING_SNAKE_CASE , return_length=SCREAMING_SNAKE_CASE , verbose=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) else: _lowerCamelCase : List[Any] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE) return encoding_image_processor def UpperCamelCase_ ( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> Optional[int]: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> Optional[int]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) @property def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = self.tokenizer.model_input_names _lowerCamelCase : Optional[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
88
"""simple docstring""" from __future__ import annotations import queue class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : int = data _lowerCamelCase : List[str] = None _lowerCamelCase : Any = None def _snake_case ( ): """simple docstring""" print("""\n********Press N to stop entering at any point of time********\n""" ) _lowerCamelCase : Optional[int] = input("""Enter the value of the root node: """ ).strip().lower() _lowerCamelCase : queue.Queue = queue.Queue() _lowerCamelCase : Optional[int] = TreeNode(int(__snake_case ) ) q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Tuple = q.get() _lowerCamelCase : Any = F'Enter the left node of {node_found.data}: ' _lowerCamelCase : Union[str, Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : Dict = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[str] = left_node q.put(__snake_case ) _lowerCamelCase : Optional[int] = F'Enter the right node of {node_found.data}: ' _lowerCamelCase : Optional[Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : List[Any] = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[Any] = right_node q.put(__snake_case ) raise def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Any = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Optional[Any] = [] while not q.empty(): _lowerCamelCase : Dict = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__snake_case ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : Optional[int] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__snake_case ) _lowerCamelCase : Tuple = n.left # end of while means current node doesn't have left child _lowerCamelCase : Optional[Any] = stack.pop() # start to traverse its right child _lowerCamelCase : Dict = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : int = node while n or stack: while n: stack.append(__snake_case ) _lowerCamelCase : Any = n.left _lowerCamelCase : Optional[Any] = stack.pop() print(n.data , end=""",""" ) _lowerCamelCase : List[Any] = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase , _lowerCamelCase : Union[str, Any] = [], [] _lowerCamelCase : Optional[Any] = node stacka.append(__snake_case ) while stacka: # to find the reversed order of post order, store it in stack2 _lowerCamelCase : Union[str, Any] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__snake_case ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def _snake_case ( __snake_case : str = "" , __snake_case : Any=50 , __snake_case : List[str]="*" ): """simple docstring""" if not s: return "\n" + width * char _lowerCamelCase , _lowerCamelCase : Optional[int] = divmod(width - len(__snake_case ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
88
1
"""simple docstring""" # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import platform import sys UpperCAmelCase = """3""" print("""Python version:""", sys.version) print("""OS platform:""", platform.platform()) print("""OS architecture:""", platform.machine()) try: import torch print("""Torch version:""", torch.__version__) print("""Cuda available:""", torch.cuda.is_available()) print("""Cuda version:""", torch.version.cuda) print("""CuDNN version:""", torch.backends.cudnn.version()) print("""Number of GPUs available:""", torch.cuda.device_count()) except ImportError: print("""Torch version:""", None) try: import transformers print("""transformers version:""", transformers.__version__) except ImportError: print("""transformers version:""", None)
88
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowercase__ : __UpperCAmelCase = XGLMConfig __UpperCAmelCase = {} __UpperCAmelCase = '''gelu''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=14 , SCREAMING_SNAKE_CASE=7 , 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=0.02 , ) -> List[str]: _lowerCamelCase : Optional[int] = parent _lowerCamelCase : int = batch_size _lowerCamelCase : str = seq_length _lowerCamelCase : Any = is_training _lowerCamelCase : int = use_input_mask _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : str = vocab_size _lowerCamelCase : List[str] = d_model _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : int = ffn_dim _lowerCamelCase : str = activation_function _lowerCamelCase : Optional[int] = activation_dropout _lowerCamelCase : Tuple = attention_dropout _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Dict = initializer_range _lowerCamelCase : Optional[Any] = None _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[Any] = 2 _lowerCamelCase : str = 1 def UpperCamelCase_ ( self) -> int: return XGLMConfig.from_pretrained("""facebook/xglm-564M""") def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) , clip_value_min=0 , clip_value_max=3) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Tuple = self.get_config() _lowerCamelCase : Optional[int] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2) return ( config, input_ids, input_mask, head_mask, ) def UpperCamelCase_ ( self) -> Optional[int]: return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : str = config_and_inputs _lowerCamelCase : Optional[Any] = { """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () __UpperCAmelCase = (TFXGLMForCausalLM,) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Optional[Any] = TFXGLMModelTester(self) _lowerCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , n_embd=37) def UpperCamelCase_ ( self) -> Dict: self.config_tester.run_common_tests() @slow def UpperCamelCase_ ( self) -> List[Any]: for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""") def UpperCamelCase_ ( self) -> List[Any]: super().test_resize_token_embeddings() @require_tf class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=True) -> List[Any]: _lowerCamelCase : List[str] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Union[str, Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCamelCase : Dict = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on _lowerCamelCase : str = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: _lowerCamelCase : int = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") tf.random.set_seed(0) _lowerCamelCase : Union[str, Any] = tokenizer("""Today is a nice day and""" , return_tensors="""tf""") _lowerCamelCase : Any = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(""":/CPU:0"""): _lowerCamelCase : Any = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , seed=[7, 0]) _lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = ( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Any = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : List[Any] = """left""" # use different length sentences to test batching _lowerCamelCase : List[Any] = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""tf""" , padding=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = inputs["""input_ids"""] _lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , attention_mask=inputs["""attention_mask"""] , max_new_tokens=12) _lowerCamelCase : List[str] = tokenizer(sentences[0] , return_tensors="""tf""").input_ids _lowerCamelCase : Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Tuple = tokenizer(sentences[1] , return_tensors="""tf""").input_ids _lowerCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , [non_padded_sentence, padded_sentence])
88
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """google/switch-base-8""": """https://huggingface.co/google/switch-base-8/blob/main/config.json""", } class lowercase__ ( A_ ): __UpperCAmelCase = '''switch_transformers''' __UpperCAmelCase = ['''past_key_values'''] __UpperCAmelCase = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self , SCREAMING_SNAKE_CASE=3_2128 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=8 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=0.01 , SCREAMING_SNAKE_CASE="float32" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=0.0_01 , SCREAMING_SNAKE_CASE=0.0_01 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE="relu" , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=1 , **SCREAMING_SNAKE_CASE , ) -> Any: _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : str = d_model _lowerCamelCase : Tuple = d_kv _lowerCamelCase : Any = d_ff _lowerCamelCase : str = num_sparse_encoder_layers _lowerCamelCase : Tuple = num_layers _lowerCamelCase : List[Any] = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry _lowerCamelCase : Optional[int] = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: _lowerCamelCase : Union[str, Any] = self.num_layers // self.num_sparse_encoder_layers else: _lowerCamelCase : Union[str, Any] = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: _lowerCamelCase : str = self.num_decoder_layers // self.num_sparse_decoder_layers else: _lowerCamelCase : Tuple = self.num_decoder_layers # HACK: this will create 0 sparse layers _lowerCamelCase : Dict = num_heads _lowerCamelCase : List[Any] = num_experts _lowerCamelCase : Dict = expert_capacity _lowerCamelCase : Tuple = router_bias _lowerCamelCase : Any = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}') _lowerCamelCase : List[Any] = router_dtype _lowerCamelCase : List[Any] = router_ignore_padding_tokens _lowerCamelCase : Optional[int] = relative_attention_num_buckets _lowerCamelCase : List[str] = relative_attention_max_distance _lowerCamelCase : Tuple = dropout_rate _lowerCamelCase : List[Any] = layer_norm_epsilon _lowerCamelCase : Dict = initializer_factor _lowerCamelCase : List[Any] = feed_forward_proj _lowerCamelCase : Optional[Any] = use_cache _lowerCamelCase : str = add_router_probs _lowerCamelCase : Optional[Any] = router_z_loss_coef _lowerCamelCase : int = router_aux_loss_coef _lowerCamelCase : Union[str, Any] = self.feed_forward_proj.split("""-""") _lowerCamelCase : Any = act_info[-1] _lowerCamelCase : Any = act_info[0] == """gated""" if len(SCREAMING_SNAKE_CASE) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE) > 2: raise ValueError( F'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.' """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """'gated-gelu' or 'relu'""") # for backwards compatibility if feed_forward_proj == "gated-gelu": _lowerCamelCase : Dict = """gelu_new""" super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , is_encoder_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , )
88
"""simple docstring""" from collections import defaultdict def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : Tuple = first_str.lower().strip() _lowerCamelCase : int = second_str.lower().strip() # Remove whitespace _lowerCamelCase : Any = first_str.replace(""" """ , """""" ) _lowerCamelCase : List[str] = second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(__snake_case ) != len(__snake_case ): return False # Default values for count should be 0 _lowerCamelCase : defaultdict[str, int] = defaultdict(__snake_case ) # For each character in input strings, # increment count in the corresponding for i in range(len(__snake_case ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase = input("""Enter the first string """).strip() UpperCAmelCase = input("""Enter the second string """).strip() UpperCAmelCase = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
88
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available UpperCAmelCase = { """configuration_gpt_neo""": ["""GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoConfig""", """GPTNeoOnnxConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ """GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoForCausalLM""", """GPTNeoForQuestionAnswering""", """GPTNeoForSequenceClassification""", """GPTNeoForTokenClassification""", """GPTNeoModel""", """GPTNeoPreTrainedModel""", """load_tf_weights_in_gpt_neo""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ """FlaxGPTNeoForCausalLM""", """FlaxGPTNeoModel""", """FlaxGPTNeoPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _snake_case ( __snake_case : float , __snake_case : float , __snake_case : bool = False ): """simple docstring""" if radian_mode: return [magnitude * cos(__snake_case ), magnitude * sin(__snake_case )] return [magnitude * cos(radians(__snake_case ) ), magnitude * sin(radians(__snake_case ) )] def _snake_case ( __snake_case : NDArray[floataa] , __snake_case : NDArray[floataa] , __snake_case : float = 10**-1 ): """simple docstring""" _lowerCamelCase : NDArray[floataa] = cross(__snake_case , __snake_case ) _lowerCamelCase : float = sum(__snake_case ) return abs(__snake_case ) < eps if __name__ == "__main__": # Test to check if it works UpperCAmelCase = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg UpperCAmelCase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg UpperCAmelCase = array([[0, -2000], [0, -1200], [0, 1_5600], [0, -1_2400]]) UpperCAmelCase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
88
1
"""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""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } UpperCAmelCase = { """moussaKam/mbarthez""": 1024, """moussaKam/barthez""": 1024, """moussaKam/barthez-orangesum-title""": 1024, } UpperCAmelCase = """▁""" class lowercase__ ( A_ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['''input_ids''', '''attention_mask'''] def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE="<s>" , SCREAMING_SNAKE_CASE="</s>" , SCREAMING_SNAKE_CASE="</s>" , SCREAMING_SNAKE_CASE="<s>" , SCREAMING_SNAKE_CASE="<unk>" , SCREAMING_SNAKE_CASE="<pad>" , SCREAMING_SNAKE_CASE="<mask>" , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> None: # Mask token behave like a normal word, i.e. include the space before it _lowerCamelCase : List[str] = AddedToken(SCREAMING_SNAKE_CASE , lstrip=SCREAMING_SNAKE_CASE , rstrip=SCREAMING_SNAKE_CASE) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) else mask_token _lowerCamelCase : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE , eos_token=SCREAMING_SNAKE_CASE , unk_token=SCREAMING_SNAKE_CASE , sep_token=SCREAMING_SNAKE_CASE , cls_token=SCREAMING_SNAKE_CASE , pad_token=SCREAMING_SNAKE_CASE , mask_token=SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE , ) _lowerCamelCase : Optional[int] = vocab_file _lowerCamelCase : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(SCREAMING_SNAKE_CASE)) _lowerCamelCase : Union[str, Any] = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} _lowerCamelCase : Optional[int] = len(self.sp_model) - 1 _lowerCamelCase : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _lowerCamelCase : Dict = [self.cls_token_id] _lowerCamelCase : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE , token_ids_a=SCREAMING_SNAKE_CASE , already_has_special_tokens=SCREAMING_SNAKE_CASE) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE)) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE)) + [1] def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None) -> List[int]: _lowerCamelCase : Union[str, Any] = [self.sep_token_id] _lowerCamelCase : 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] @property def UpperCamelCase_ ( self) -> Union[str, Any]: return len(self.sp_model) def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Tuple = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE , out_type=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> str: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _lowerCamelCase : Optional[Any] = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE) return spm_id if spm_id else self.unk_token_id def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : Any = [] _lowerCamelCase : List[str] = """""" _lowerCamelCase : Optional[int] = 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(SCREAMING_SNAKE_CASE) + token _lowerCamelCase : Any = True _lowerCamelCase : Union[str, Any] = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE) return out_string.strip() def __getstate__( self) -> int: _lowerCamelCase : List[str] = self.__dict__.copy() _lowerCamelCase : int = None return state def __setstate__( self , SCREAMING_SNAKE_CASE) -> Dict: _lowerCamelCase : Optional[Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs"""): _lowerCamelCase : Any = {} _lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return _lowerCamelCase : Tuple = os.path.join( SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE , """wb""") as fi: _lowerCamelCase : List[str] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE) return (out_vocab_file,)
88
"""simple docstring""" import random def _snake_case ( __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = a[left_index] _lowerCamelCase : Dict = left_index + 1 for j in range(left_index + 1 , __snake_case ): if a[j] < pivot: _lowerCamelCase , _lowerCamelCase : List[str] = a[i], a[j] i += 1 _lowerCamelCase , _lowerCamelCase : Optional[int] = a[i - 1], a[left_index] return i - 1 def _snake_case ( __snake_case : Tuple , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" if left < right: _lowerCamelCase : Any = random.randint(__snake_case , right - 1 ) _lowerCamelCase , _lowerCamelCase : Optional[Any] = ( a[left], a[pivot], ) # switches the pivot with the left most bound _lowerCamelCase : List[str] = partition(__snake_case , __snake_case , __snake_case ) quick_sort_random( __snake_case , __snake_case , __snake_case ) # recursive quicksort to the left of the pivot point quick_sort_random( __snake_case , pivot_index + 1 , __snake_case ) # recursive quicksort to the right of the pivot point def _snake_case ( ): """simple docstring""" _lowerCamelCase : Union[str, Any] = input("""Enter numbers separated by a comma:\n""" ).strip() _lowerCamelCase : int = [int(__snake_case ) for item in user_input.split(""",""" )] quick_sort_random(__snake_case , 0 , len(__snake_case ) ) print(__snake_case ) if __name__ == "__main__": main()
88
1
"""simple docstring""" def _snake_case ( __snake_case : int ): """simple docstring""" _lowerCamelCase : Dict = int(__snake_case ) if n_element < 1: _lowerCamelCase : List[Any] = ValueError("""a should be a positive number""" ) raise my_error _lowerCamelCase : Dict = [1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Any = (0, 0, 0) _lowerCamelCase : Tuple = 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__": UpperCAmelCase = input("""Enter the last number (nth term) of the Hamming Number Series: """) print("""Formula of Hamming Number Series => 2^i * 3^j * 5^k""") UpperCAmelCase = hamming(int(n)) print("""-----------------------------------------------------""") print(f'''The list with nth numbers is: {hamming_numbers}''') print("""-----------------------------------------------------""")
88
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase = """\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } """ UpperCAmelCase = """\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). """ UpperCAmelCase = """ Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric(\"code_eval\") >>> test_cases = [\"assert add(2,3)==5\"] >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {'pass@1': 0.5, 'pass@2': 1.0} """ UpperCAmelCase = """ ################################################################################ !!!WARNING!!! ################################################################################ The \"code_eval\" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this with: >>> import os >>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\" ################################################################################\ """ UpperCAmelCase = """The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> str: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""")), """references""": datasets.Value("""string"""), }) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=[1, 10, 100] , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=3.0) -> Union[str, Any]: if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0) != "1": raise ValueError(_WARNING) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""") with ThreadPoolExecutor(max_workers=SCREAMING_SNAKE_CASE) as executor: _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Optional[int] = Counter() _lowerCamelCase : Any = 0 _lowerCamelCase : List[Any] = defaultdict(SCREAMING_SNAKE_CASE) for task_id, (candidates, test_case) in enumerate(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)): for candidate in candidates: _lowerCamelCase : Any = candidate + """\n""" + test_case _lowerCamelCase : Union[str, Any] = (test_program, timeout, task_id, completion_id[task_id]) _lowerCamelCase : List[str] = executor.submit(SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE) futures.append(SCREAMING_SNAKE_CASE) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(SCREAMING_SNAKE_CASE): _lowerCamelCase : int = future.result() results[result["task_id"]].append((result["""completion_id"""], result)) _lowerCamelCase , _lowerCamelCase : List[Any] = [], [] for result in results.values(): result.sort() _lowerCamelCase : List[str] = [r[1]["""passed"""] for r in result] total.append(len(SCREAMING_SNAKE_CASE)) correct.append(sum(SCREAMING_SNAKE_CASE)) _lowerCamelCase : List[Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = k _lowerCamelCase : Optional[Any] = {F'pass@{k}': estimate_pass_at_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).mean() for k in ks if (total >= k).all()} return pass_at_k, results def _snake_case ( __snake_case : List[str] , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" def estimator(__snake_case : int , __snake_case : int , __snake_case : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(__snake_case , __snake_case ): _lowerCamelCase : Optional[int] = itertools.repeat(__snake_case , len(__snake_case ) ) else: assert len(__snake_case ) == len(__snake_case ) _lowerCamelCase : List[str] = iter(__snake_case ) return np.array([estimator(int(__snake_case ) , int(__snake_case ) , __snake_case ) for n, c in zip(__snake_case , __snake_case )] )
88
1
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """speechbrain/m-ctc-t-large""": """https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json""", # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class lowercase__ ( A_ ): __UpperCAmelCase = '''mctct''' def __init__( self , SCREAMING_SNAKE_CASE=8065 , SCREAMING_SNAKE_CASE=1536 , SCREAMING_SNAKE_CASE=36 , SCREAMING_SNAKE_CASE=6144 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=384 , SCREAMING_SNAKE_CASE=920 , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE=0.3 , SCREAMING_SNAKE_CASE="relu" , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=0.3 , SCREAMING_SNAKE_CASE=0.3 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0.3 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=(7,) , SCREAMING_SNAKE_CASE=(3,) , SCREAMING_SNAKE_CASE=80 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE="sum" , SCREAMING_SNAKE_CASE=False , **SCREAMING_SNAKE_CASE , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE , pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = vocab_size _lowerCamelCase : Optional[Any] = hidden_size _lowerCamelCase : int = num_hidden_layers _lowerCamelCase : Tuple = intermediate_size _lowerCamelCase : Any = num_attention_heads _lowerCamelCase : List[str] = attention_head_dim _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : int = layer_norm_eps _lowerCamelCase : str = layerdrop _lowerCamelCase : Optional[Any] = hidden_act _lowerCamelCase : int = initializer_range _lowerCamelCase : List[str] = hidden_dropout_prob _lowerCamelCase : Union[str, Any] = attention_probs_dropout_prob _lowerCamelCase : Optional[Any] = pad_token_id _lowerCamelCase : List[str] = bos_token_id _lowerCamelCase : int = eos_token_id _lowerCamelCase : int = conv_glu_dim _lowerCamelCase : Any = conv_dropout _lowerCamelCase : int = num_conv_layers _lowerCamelCase : str = input_feat_per_channel _lowerCamelCase : int = input_channels _lowerCamelCase : List[Any] = conv_channels _lowerCamelCase : Optional[int] = ctc_loss_reduction _lowerCamelCase : Union[str, Any] = ctc_zero_infinity # prevents config testing fail with exporting to json _lowerCamelCase : List[Any] = list(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = list(SCREAMING_SNAKE_CASE) if len(self.conv_kernel) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """ F'but is `len(config.conv_kernel) = {len(self.conv_kernel)}`, ' F'`config.num_conv_layers = {self.num_conv_layers}`.')
88
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo UpperCAmelCase = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ UpperCAmelCase = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ UpperCAmelCase = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence"""), """references""": datasets.Sequence( datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence""") , id="""references"""), }) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 4 , ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=SCREAMING_SNAKE_CASE , hypotheses=SCREAMING_SNAKE_CASE , min_len=SCREAMING_SNAKE_CASE , max_len=SCREAMING_SNAKE_CASE) }
88
1
"""simple docstring""" from math import factorial def _snake_case ( __snake_case : int , __snake_case : int ): """simple docstring""" if n < k or k < 0: raise ValueError("""Please enter positive integers for n and k where n >= k""" ) return factorial(__snake_case ) // (factorial(__snake_case ) * factorial(n - k )) if __name__ == "__main__": print( """The number of five-card hands possible from a standard""", f'''fifty-two card deck is: {combinations(52, 5)}\n''', ) print( """If a class of 40 students must be arranged into groups of""", f'''4 for group projects, there are {combinations(40, 4)} ways''', """to arrange them.\n""", ) print( """If 10 teams are competing in a Formula One race, there""", f'''are {combinations(10, 3)} ways that first, second and''', """third place can be awarded.""", )
88
"""simple docstring""" def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : str = len(__snake_case ) _lowerCamelCase : Union[str, Any] = len(__snake_case ) _lowerCamelCase : int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] _lowerCamelCase : Union[str, Any] = True for i in range(__snake_case ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: _lowerCamelCase : Tuple = True if a[i].islower(): _lowerCamelCase : Tuple = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' ,'''False''' ) ) is not True ,reason='''Skipping test because should only be run when releasing minor transformers version''' ,) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.p3.16xlarge''', '''results''': {'''train_runtime''': 650, '''eval_accuracy''': 0.7, '''eval_loss''': 0.6}, }, { '''framework''': '''pytorch''', '''script''': '''run_ddp.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.p3.16xlarge''', '''results''': {'''train_runtime''': 600, '''eval_accuracy''': 0.7, '''eval_loss''': 0.6}, }, { '''framework''': '''tensorflow''', '''script''': '''run_tf_dist.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.p3.16xlarge''', '''results''': {'''train_runtime''': 600, '''eval_accuracy''': 0.6, '''eval_loss''': 0.7}, }, ] ) class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Union[str, Any]: if self.framework == "pytorch": subprocess.run( F'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split() , encoding="""utf-8""" , check=SCREAMING_SNAKE_CASE , ) assert hasattr(self , """env""") def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : Any = F'{self.env.base_job_name}-{instance_count}-{"ddp" if "ddp" in self.script else "smd"}' # distributed data settings _lowerCamelCase : Tuple = {"""smdistributed""": {"""dataparallel""": {"""enabled""": True}}} if self.script != """run_ddp.py""" else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=SCREAMING_SNAKE_CASE , instance_count=SCREAMING_SNAKE_CASE , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE , hyperparameters={**self.env.distributed_hyperparameters, """model_name_or_path""": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE , py_version="""py36""" , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> Any: TrainingJobAnalytics(SCREAMING_SNAKE_CASE).export_csv(F'{self.env.test_path}/{job_name}_metrics.csv') @parameterized.expand([(2,)]) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> Dict: # create estimator _lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE) # run training estimator.fit() # result dataframe _lowerCamelCase : str = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis _lowerCamelCase : int = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""]) _lowerCamelCase : str = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""]) # get train time from SageMaker job, this includes starting, preprocessing, stopping _lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get("""TrainingTimeInSeconds""" , 99_9999) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["""eval_accuracy"""] for t in eval_accuracy) assert all(t <= self.results["""eval_loss"""] for t in eval_loss) # dump tests result into json file to share in PR with open(F'{estimator.latest_training_job.name}.json' , """w""") as outfile: json.dump({"""train_time""": train_runtime, """eval_accuracy""": eval_accuracy, """eval_loss""": eval_loss} , SCREAMING_SNAKE_CASE)
88
"""simple docstring""" import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> None: warnings.warn( """The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ImageGPTImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE)
88
1
"""simple docstring""" import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class lowercase__ ( A_ ): def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : Dict = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """tf_padding""")) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """depth_multiplier""")) class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=0.25 , SCREAMING_SNAKE_CASE=8 , SCREAMING_SNAKE_CASE=8 , SCREAMING_SNAKE_CASE=6 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE="relu6" , SCREAMING_SNAKE_CASE=1280 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=None , ) -> Any: _lowerCamelCase : Optional[Any] = parent _lowerCamelCase : Tuple = batch_size _lowerCamelCase : Optional[Any] = num_channels _lowerCamelCase : Tuple = image_size _lowerCamelCase : Tuple = depth_multiplier _lowerCamelCase : int = depth_divisible_by _lowerCamelCase : Tuple = min_depth _lowerCamelCase : Any = expand_ratio _lowerCamelCase : int = tf_padding _lowerCamelCase : str = output_stride _lowerCamelCase : str = first_layer_is_expansion _lowerCamelCase : Optional[int] = finegrained_output _lowerCamelCase : Union[str, Any] = hidden_act _lowerCamelCase : Optional[int] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier) _lowerCamelCase : Any = classifier_dropout_prob _lowerCamelCase : Any = use_labels _lowerCamelCase : Optional[int] = is_training _lowerCamelCase : Tuple = num_labels _lowerCamelCase : int = initializer_range _lowerCamelCase : List[str] = scope def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) _lowerCamelCase : List[Any] = None _lowerCamelCase : str = None if self.use_labels: _lowerCamelCase : List[Any] = ids_tensor([self.batch_size] , self.num_labels) _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels) _lowerCamelCase : Dict = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self) -> str: return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : Tuple = MobileNetVaModel(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : str = model(SCREAMING_SNAKE_CASE) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Tuple: _lowerCamelCase : Tuple = self.num_labels _lowerCamelCase : Union[str, Any] = MobileNetVaForImageClassification(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : Tuple = self.num_labels _lowerCamelCase : List[str] = MobileNetVaForSemanticSegmentation(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) _lowerCamelCase : Tuple = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Tuple = self.prepare_config_and_inputs() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Tuple = config_and_inputs _lowerCamelCase : Optional[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { '''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification, '''image-segmentation''': MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : int = MobileNetVaModelTester(self) _lowerCamelCase : Dict = MobileNetVaConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Dict: self.config_tester.run_common_tests() @unittest.skip(reason="""MobileNetV2 does not use inputs_embeds""") def UpperCamelCase_ ( self) -> Optional[int]: pass @unittest.skip(reason="""MobileNetV2 does not support input and output embeddings""") def UpperCamelCase_ ( self) -> Dict: pass @unittest.skip(reason="""MobileNetV2 does not output attentions""") def UpperCamelCase_ ( self) -> Any: pass def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase , _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Union[str, Any] = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : Optional[Any] = [*signature.parameters.keys()] _lowerCamelCase : Optional[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[Any]: def check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : List[str] = model_class(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() with torch.no_grad(): _lowerCamelCase : List[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)) _lowerCamelCase : Optional[Any] = outputs.hidden_states _lowerCamelCase : Tuple = 16 self.assertEqual(len(SCREAMING_SNAKE_CASE) , SCREAMING_SNAKE_CASE) _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : List[str] = True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCamelCase : Optional[Any] = True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> Tuple: for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : str = MobileNetVaModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> Any: return ( MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v2_1.0_224""") if is_vision_available() else None ) @slow def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : List[str] = MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v2_1.0_224""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = self.default_image_processor _lowerCamelCase : int = prepare_img() _lowerCamelCase : Optional[Any] = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) # forward pass with torch.no_grad(): _lowerCamelCase : str = model(**SCREAMING_SNAKE_CASE) # verify the logits _lowerCamelCase : Optional[int] = torch.Size((1, 1001)) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = torch.tensor([0.24_45, -1.19_93, 0.19_05]).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4)) @slow def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[int] = MobileNetVaForSemanticSegmentation.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513""") _lowerCamelCase : str = model.to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = MobileNetVaImageProcessor.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513""") _lowerCamelCase : Union[str, Any] = prepare_img() _lowerCamelCase : Any = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) # forward pass with torch.no_grad(): _lowerCamelCase : List[Any] = model(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = outputs.logits # verify the logits _lowerCamelCase : Union[str, Any] = torch.Size((1, 21, 65, 65)) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = torch.tensor( [ [[17.57_90, 17.75_81, 18.33_55], [18.32_57, 18.42_30, 18.89_73], [18.61_69, 18.86_50, 19.21_87]], [[-2.15_95, -2.09_77, -2.37_41], [-2.42_26, -2.30_28, -2.68_35], [-2.78_19, -2.59_91, -2.77_06]], [[4.20_58, 4.83_17, 4.76_38], [4.41_36, 5.03_61, 4.93_83], [4.50_28, 4.96_44, 4.87_34]], ] , device=SCREAMING_SNAKE_CASE , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4))
88
"""simple docstring""" from math import isqrt, loga def _snake_case ( __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __snake_case , __snake_case ): _lowerCamelCase : Optional[int] = False return [i for i in range(2 , __snake_case ) if is_prime[i]] def _snake_case ( __snake_case : int = 800800 , __snake_case : int = 800800 ): """simple docstring""" _lowerCamelCase : Union[str, Any] = degree * loga(__snake_case ) _lowerCamelCase : Union[str, Any] = int(__snake_case ) _lowerCamelCase : Dict = calculate_prime_numbers(__snake_case ) _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : Any = 0 _lowerCamelCase : Any = len(__snake_case ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f'''{solution() = }''')
88
1
"""simple docstring""" from __future__ import annotations from math import ceil, floor, sqrt def _snake_case ( __snake_case : int = 2000000 ): """simple docstring""" _lowerCamelCase : list[int] = [0] _lowerCamelCase : int for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target _lowerCamelCase : int = 0 # the area corresponding to the grid that gives the product closest to target _lowerCamelCase : int = 0 # an estimate of b, using the quadratic formula _lowerCamelCase : float # the largest integer less than b_estimate _lowerCamelCase : int # the largest integer less than b_estimate _lowerCamelCase : int # the triangle number corresponding to b_floor _lowerCamelCase : int # the triangle number corresponding to b_ceil _lowerCamelCase : int for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): _lowerCamelCase : str = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 _lowerCamelCase : List[str] = floor(__snake_case ) _lowerCamelCase : Dict = ceil(__snake_case ) _lowerCamelCase : str = triangle_numbers[b_floor] _lowerCamelCase : Optional[Any] = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): _lowerCamelCase : List[str] = triangle_b_first_guess * triangle_a _lowerCamelCase : Optional[int] = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): _lowerCamelCase : List[str] = triangle_b_second_guess * triangle_a _lowerCamelCase : Union[str, Any] = idx_a * b_ceil return area if __name__ == "__main__": print(f'''{solution() = }''')
88
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionSAGPipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: torch.manual_seed(0) _lowerCamelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0) _lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : List[Any] = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> List[Any]: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""") _lowerCamelCase : Union[str, Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = """.""" _lowerCamelCase : int = torch.manual_seed(0) _lowerCamelCase : Tuple = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Dict = output.images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Optional[Any] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Dict = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = """.""" _lowerCamelCase : List[str] = torch.manual_seed(0) _lowerCamelCase : int = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Any = output.images _lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Optional[Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """.""" _lowerCamelCase : Union[str, Any] = torch.manual_seed(0) _lowerCamelCase : Optional[int] = sag_pipe( [prompt] , width=768 , height=512 , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) _lowerCamelCase : Union[str, Any] = output.images assert image.shape == (1, 512, 768, 3)
88
1
"""simple docstring""" def _snake_case ( __snake_case : float , __snake_case : float , __snake_case : int ): """simple docstring""" if principal <= 0: raise Exception("""Principal borrowed must be > 0""" ) if rate_per_annum < 0: raise Exception("""Rate of interest must be >= 0""" ) if years_to_repay <= 0 or not isinstance(__snake_case , __snake_case ): raise Exception("""Years to repay must be an integer > 0""" ) # Yearly rate is divided by 12 to get monthly rate _lowerCamelCase : Tuple = rate_per_annum / 12 # Years to repay is multiplied by 12 to get number of payments as payment is monthly _lowerCamelCase : str = years_to_repay * 12 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) ) if __name__ == "__main__": import doctest doctest.testmod()
88
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=64 , ) -> Optional[int]: _lowerCamelCase : List[str] = parent _lowerCamelCase : List[Any] = batch_size _lowerCamelCase : Tuple = is_training _lowerCamelCase : Tuple = use_auxiliary_loss _lowerCamelCase : Any = num_queries _lowerCamelCase : List[str] = num_channels _lowerCamelCase : List[str] = min_size _lowerCamelCase : Tuple = max_size _lowerCamelCase : str = num_labels _lowerCamelCase : Any = hidden_dim _lowerCamelCase : Dict = hidden_dim def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) > 0.5 ).float() _lowerCamelCase : Dict = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE) > 0.5).long() _lowerCamelCase : Optional[int] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCamelCase_ ( self) -> str: _lowerCamelCase : List[str] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _lowerCamelCase : Any = self.num_queries _lowerCamelCase : int = self.num_labels _lowerCamelCase : int = [1, 1, 1, 1] _lowerCamelCase : Any = self.num_channels _lowerCamelCase : Optional[Any] = 64 _lowerCamelCase : str = 128 _lowerCamelCase : Optional[Any] = self.hidden_dim _lowerCamelCase : Any = self.hidden_dim _lowerCamelCase : List[Any] = self.hidden_dim return config def UpperCamelCase_ ( self) -> Any: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = self.prepare_config_and_inputs() _lowerCamelCase : str = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : str = output.encoder_hidden_states _lowerCamelCase : int = output.pixel_decoder_hidden_states _lowerCamelCase : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , config.decoder_layers) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False) -> List[str]: with torch.no_grad(): _lowerCamelCase : Optional[int] = MaskaFormerModel(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[int] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = model(SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(output.encoder_last_hidden_state is not None) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : str = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(result.encoder_last_hidden_state is not None) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1)) with torch.no_grad(): _lowerCamelCase : List[Any] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model( pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape , torch.Size([1])) @require_torch class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = MaskaFormerModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> int: _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""") def UpperCamelCase_ ( self) -> Optional[int]: pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""") def UpperCamelCase_ ( self) -> Tuple: pass @unittest.skip(reason="""Mask2Former is not a generative model""") def UpperCamelCase_ ( self) -> List[Any]: pass @unittest.skip(reason="""Mask2Former does not use token embeddings""") def UpperCamelCase_ ( self) -> Any: pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""") def UpperCamelCase_ ( self) -> Dict: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""") def UpperCamelCase_ ( self) -> Optional[int]: pass def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : str = [*signature.parameters.keys()] _lowerCamelCase : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> Optional[int]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _lowerCamelCase : Optional[int] = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Dict = (self.model_tester.min_size,) * 2 _lowerCamelCase : str = { """pixel_values""": torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE), """mask_labels""": torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE), """class_labels""": torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE).long(), } _lowerCamelCase : List[str] = self.model_tester.get_config() _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE , output_attentions=SCREAMING_SNAKE_CASE) self.assertTrue(outputs.attentions is not None) def UpperCamelCase_ ( self) -> Optional[Any]: if not self.model_tester.is_training: return _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE).loss loss.backward() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : int = True _lowerCamelCase : Optional[Any] = True _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _lowerCamelCase : int = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _lowerCamelCase : str = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _lowerCamelCase : Optional[int] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(pixel_decoder_hidden_states.grad) self.assertIsNotNone(transformer_decoder_hidden_states.grad) self.assertIsNotNone(attentions.grad) UpperCAmelCase = 1e-4 def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def UpperCamelCase_ ( self) -> Union[str, Any]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Tuple = MaskaFormerModel.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : List[str] = prepare_img() _lowerCamelCase : Union[str, Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Any = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Dict = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : Optional[Any] = self.default_image_processor _lowerCamelCase : Any = prepare_img() _lowerCamelCase : Dict = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : List[str] = model(**SCREAMING_SNAKE_CASE) # masks_queries_logits _lowerCamelCase : str = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)) _lowerCamelCase : Any = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] _lowerCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) # class_queries_logits _lowerCamelCase : List[str] = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1)) _lowerCamelCase : Optional[Any] = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ]).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : Tuple = image_processor( [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors="""pt""" , ) _lowerCamelCase : Optional[Any] = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""mask_labels"""]] _lowerCamelCase : Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""class_labels"""]] with torch.no_grad(): _lowerCamelCase : Any = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None)
88
1
"""simple docstring""" import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase = 256 class lowercase__ ( A_ ): __UpperCAmelCase = ['''melgan'''] def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> None: super().__init__() # From MELGAN _lowerCamelCase : Dict = math.log(1e-5) # Matches MelGAN training. _lowerCamelCase : List[Any] = 4.0 # Largest value for most examples _lowerCamelCase : Dict = 128 self.register_modules( notes_encoder=SCREAMING_SNAKE_CASE , continuous_encoder=SCREAMING_SNAKE_CASE , decoder=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , melgan=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=(-1.0, 1.0) , SCREAMING_SNAKE_CASE=False) -> Any: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = output_range if clip: _lowerCamelCase : Optional[int] = torch.clip(SCREAMING_SNAKE_CASE , self.min_value , self.max_value) # Scale to [0, 1]. _lowerCamelCase : Optional[int] = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=(-1.0, 1.0) , SCREAMING_SNAKE_CASE=False) -> List[str]: _lowerCamelCase , _lowerCamelCase : str = input_range _lowerCamelCase : List[Any] = torch.clip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) if clip else outputs # Scale to [0, 1]. _lowerCamelCase : str = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Union[str, Any]: _lowerCamelCase : Tuple = input_tokens > 0 _lowerCamelCase , _lowerCamelCase : str = self.notes_encoder( encoder_input_tokens=SCREAMING_SNAKE_CASE , encoder_inputs_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase , _lowerCamelCase : Tuple = self.continuous_encoder( encoder_inputs=SCREAMING_SNAKE_CASE , encoder_inputs_mask=SCREAMING_SNAKE_CASE) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Union[str, Any]: _lowerCamelCase : Optional[int] = noise_time if not torch.is_tensor(SCREAMING_SNAKE_CASE): _lowerCamelCase : int = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device) elif torch.is_tensor(SCREAMING_SNAKE_CASE) and len(timesteps.shape) == 0: _lowerCamelCase : Tuple = timesteps[None].to(input_tokens.device) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _lowerCamelCase : Union[str, Any] = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device) _lowerCamelCase : List[str] = self.decoder( encodings_and_masks=SCREAMING_SNAKE_CASE , decoder_input_tokens=SCREAMING_SNAKE_CASE , decoder_noise_time=SCREAMING_SNAKE_CASE) return logits @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 100 , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = "numpy" , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 1 , ) -> Union[AudioPipelineOutput, Tuple]: if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) or callback_steps <= 0) ): raise ValueError( F'`callback_steps` has to be a positive integer but is {callback_steps} of type' F' {type(SCREAMING_SNAKE_CASE)}.') _lowerCamelCase : Optional[Any] = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa) _lowerCamelCase : Dict = np.zeros([1, 0, self.n_dims] , np.floataa) _lowerCamelCase : List[Any] = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=SCREAMING_SNAKE_CASE , device=self.device) for i, encoder_input_tokens in enumerate(SCREAMING_SNAKE_CASE): if i == 0: _lowerCamelCase : Any = torch.from_numpy(pred_mel[:1].copy()).to( device=self.device , dtype=self.decoder.dtype) # The first chunk has no previous context. _lowerCamelCase : Optional[int] = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=SCREAMING_SNAKE_CASE , device=self.device) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. _lowerCamelCase : Dict = ones _lowerCamelCase : List[Any] = self.scale_features( SCREAMING_SNAKE_CASE , output_range=[-1.0, 1.0] , clip=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens]).to(device=self.device) , continuous_inputs=SCREAMING_SNAKE_CASE , continuous_mask=SCREAMING_SNAKE_CASE , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop _lowerCamelCase : List[str] = randn_tensor( shape=encoder_continuous_inputs.shape , generator=SCREAMING_SNAKE_CASE , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps)): _lowerCamelCase : str = self.decode( encodings_and_masks=SCREAMING_SNAKE_CASE , input_tokens=SCREAMING_SNAKE_CASE , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 _lowerCamelCase : Tuple = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE).prev_sample _lowerCamelCase : Any = self.scale_to_features(SCREAMING_SNAKE_CASE , input_range=[-1.0, 1.0]) _lowerCamelCase : int = mel[:1] _lowerCamelCase : Optional[int] = mel.cpu().float().numpy() _lowerCamelCase : str = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) logger.info("""Generated segment""" , SCREAMING_SNAKE_CASE) if output_type == "numpy" and not is_onnx_available(): raise ValueError( """Cannot return output in 'np' format if ONNX is not available. Make sure to have ONNX installed or set 'output_type' to 'mel'.""") elif output_type == "numpy" and self.melgan is None: raise ValueError( """Cannot return output in 'np' format if melgan component is not defined. Make sure to define `self.melgan` or set 'output_type' to 'mel'.""") if output_type == "numpy": _lowerCamelCase : Union[str, Any] = self.melgan(input_features=full_pred_mel.astype(np.floataa)) else: _lowerCamelCase : Optional[Any] = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=SCREAMING_SNAKE_CASE)
88
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) UpperCAmelCase = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) UpperCAmelCase = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) UpperCAmelCase = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModel) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
88
1
"""simple docstring""" def _snake_case ( __snake_case : List[Any] , __snake_case : Tuple ): """simple docstring""" _lowerCamelCase : Any = [0 for i in range(r + 1 )] # nc0 = 1 _lowerCamelCase : List[Any] = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. _lowerCamelCase : str = min(__snake_case , __snake_case ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
88
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
88
1
"""simple docstring""" from argparse import ArgumentParser from .env import EnvironmentCommand def _snake_case ( ): """simple docstring""" _lowerCamelCase : Optional[Any] = ArgumentParser("""Diffusers CLI tool""" , usage="""diffusers-cli <command> [<args>]""" ) _lowerCamelCase : Dict = parser.add_subparsers(help="""diffusers-cli command helpers""" ) # Register commands EnvironmentCommand.register_subcommand(__snake_case ) # Let's go _lowerCamelCase : Any = parser.parse_args() if not hasattr(__snake_case , """func""" ): parser.print_help() exit(1 ) # Run _lowerCamelCase : List[str] = args.func(__snake_case ) service.run() if __name__ == "__main__": main()
88
"""simple docstring""" def _snake_case ( __snake_case : list[list[int]] , __snake_case : int , __snake_case : int , __snake_case : list[int] ): """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def _snake_case ( __snake_case : list[list[int]] , __snake_case : list[int] , __snake_case : int ): """simple docstring""" if curr_ind == len(__snake_case ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(__snake_case ) ): if valid_connection(__snake_case , __snake_case , __snake_case , __snake_case ): # Insert current vertex into path as next transition _lowerCamelCase : List[str] = next_ver # Validate created path if util_hamilton_cycle(__snake_case , __snake_case , curr_ind + 1 ): return True # Backtrack _lowerCamelCase : Tuple = -1 return False def _snake_case ( __snake_case : list[list[int]] , __snake_case : int = 0 ): """simple docstring""" _lowerCamelCase : Any = [-1] * (len(__snake_case ) + 1) # initialize start and end of path with starting index _lowerCamelCase : Optional[int] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__snake_case , __snake_case , 1 ) else []
88
1
"""simple docstring""" import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase__ ( A_ ,unittest.TestCase ): __UpperCAmelCase = None __UpperCAmelCase = BloomTokenizerFast __UpperCAmelCase = BloomTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = False __UpperCAmelCase = '''tokenizer_file''' __UpperCAmelCase = {'''bos_token''': '''<s>''', '''eos_token''': '''</s>''', '''unk_token''': '''<unk>''', '''pad_token''': '''<pad>'''} def UpperCamelCase_ ( self) -> int: super().setUp() _lowerCamelCase : Optional[int] = BloomTokenizerFast.from_pretrained("""bigscience/tokenizer""") tokenizer.save_pretrained(self.tmpdirname) def UpperCamelCase_ ( self , **SCREAMING_SNAKE_CASE) -> str: kwargs.update(self.special_tokens_map) return BloomTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Union[str, Any] = self.get_rust_tokenizer() _lowerCamelCase : List[str] = ["""The quick brown fox</s>""", """jumps over the lazy dog</s>"""] _lowerCamelCase : Union[str, Any] = [[2175, 2_3714, 7_3173, 14_4252, 2], [77, 13_2619, 3478, 368, 10_9586, 3_5433, 2]] _lowerCamelCase : Any = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE)["""input_ids"""] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=6) -> str: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'): _lowerCamelCase : Optional[int] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input _lowerCamelCase : Optional[Any] = """This is a simple input""" _lowerCamelCase : List[Any] = ["""This is a simple input 1""", """This is a simple input 2"""] _lowerCamelCase : List[Any] = ("""This is a simple input""", """This is a pair""") _lowerCamelCase : int = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests try: tokenizer_r.encode(SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE) tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE) tokenizer_r.batch_encode_plus(SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE) tokenizer_r.encode(SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE) tokenizer_r.batch_encode_plus(SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE) except ValueError: self.fail("""Bloom Tokenizer should be able to deal with padding""") _lowerCamelCase : Union[str, Any] = None # Hotfixing padding = None self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""") # Simple input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""") # Simple input self.assertRaises( SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" , ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""") # Pair input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""") # Pair input self.assertRaises( SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" , ) def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : Tuple = self.get_rust_tokenizer() _lowerCamelCase : int = load_dataset("""xnli""" , """all_languages""" , split="""test""" , streaming=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = next(iter(SCREAMING_SNAKE_CASE))["""premise"""] # pick up one data _lowerCamelCase : Optional[int] = list(sample_data.values()) _lowerCamelCase : str = list(map(tokenizer.encode , SCREAMING_SNAKE_CASE)) _lowerCamelCase : List[Any] = [tokenizer.decode(SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE) for x in output_tokens] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: # The test has to be overriden because BLOOM uses ALiBi positional embeddings that does not have # any sequence length constraints. This test of the parent class will fail since it relies on the # maximum sequence length of the positoonal embeddings. self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map) , 1) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values())[0]) , 1)
88
"""simple docstring""" import mpmath # for roots of unity import numpy as np class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None) -> Tuple: # Input as list _lowerCamelCase : Any = list(poly_a or [0])[:] _lowerCamelCase : Optional[Any] = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _lowerCamelCase : int = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() _lowerCamelCase : Union[str, Any] = len(self.polyB) # Add 0 to make lengths equal a power of 2 _lowerCamelCase : List[Any] = int( 2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1))) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform _lowerCamelCase : Optional[Any] = complex(mpmath.root(x=1 , n=self.c_max_length , k=1)) # The product _lowerCamelCase : int = self.__multiply() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Dict = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE) <= 1: return dft[0] # _lowerCamelCase : str = self.c_max_length // 2 while next_ncol > 0: _lowerCamelCase : Dict = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : Tuple = self.root**next_ncol # First half of next step _lowerCamelCase : int = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step _lowerCamelCase : Optional[int] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update _lowerCamelCase : Union[str, Any] = new_dft _lowerCamelCase : List[str] = next_ncol // 2 return dft[0] def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[Any] = self.__dft("""A""") _lowerCamelCase : List[str] = self.__dft("""B""") _lowerCamelCase : List[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT _lowerCamelCase : List[str] = 2 while next_ncol <= self.c_max_length: _lowerCamelCase : Any = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : List[Any] = self.root ** (next_ncol // 2) _lowerCamelCase : str = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root)) current_root *= root # Update _lowerCamelCase : Any = new_inverse_c next_ncol *= 2 # Unpack _lowerCamelCase : Optional[Any] = [round(x[0].real , 8) + round(x[0].imag , 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self) -> Any: _lowerCamelCase : Dict = """A = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A])) _lowerCamelCase : List[Any] = """B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B])) _lowerCamelCase : int = """A*B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.product)) return F'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" from __future__ import annotations from collections.abc import Callable def _snake_case ( __snake_case : Callable[[int | float], int | float] , __snake_case : int | float , __snake_case : int | float , __snake_case : int = 100 , ): """simple docstring""" _lowerCamelCase : Optional[int] = x_start _lowerCamelCase : Optional[int] = fnc(__snake_case ) _lowerCamelCase : Optional[int] = 0.0 for _ in range(__snake_case ): # Approximates small segments of curve as linear and solve # for trapezoidal area _lowerCamelCase : int = (x_end - x_start) / steps + xa _lowerCamelCase : List[Any] = fnc(__snake_case ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step _lowerCamelCase : List[Any] = xa _lowerCamelCase : Any = fxa return area if __name__ == "__main__": def _snake_case ( __snake_case : List[Any] ): """simple docstring""" return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") UpperCAmelCase = 10 while i <= 10_0000: print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 10
88
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase = { """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""VisionEncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""TFVisionEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""FlaxVisionEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
1
"""simple docstring""" def _snake_case ( __snake_case : int = 200 ): """simple docstring""" _lowerCamelCase : Dict = [1, 2, 5, 10, 20, 50, 100, 200] _lowerCamelCase : Union[str, Any] = [0] * (pence + 1) _lowerCamelCase : List[Any] = 1 # base case: 1 way to make 0 pence for coin in coins: for i in range(__snake_case , pence + 1 , 1 ): number_of_ways[i] += number_of_ways[i - coin] return number_of_ways[pence] if __name__ == "__main__": assert solution(200) == 7_3682
88
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def _snake_case ( __snake_case : List[str] ): """simple docstring""" for param in module.parameters(): _lowerCamelCase : Optional[Any] = False def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _lowerCamelCase : Any = """mps""" if device == "mps": print( """WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch""" """ errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues""" """ with generations.""" ) return device def _snake_case ( __snake_case : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = plt.imshow(__snake_case ) fig.axes.get_xaxis().set_visible(__snake_case ) fig.axes.get_yaxis().set_visible(__snake_case ) plt.show() def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = datetime.now() _lowerCamelCase : Optional[Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
88
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """facebook/xlm-roberta-xl""": """https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json""", """facebook/xlm-roberta-xxl""": """https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json""", # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl } class lowercase__ ( A_ ): __UpperCAmelCase = '''xlm-roberta-xl''' def __init__( self , SCREAMING_SNAKE_CASE=25_0880 , SCREAMING_SNAKE_CASE=2560 , SCREAMING_SNAKE_CASE=36 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=1_0240 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=514 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-0_5 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE , ) -> Optional[int]: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = vocab_size _lowerCamelCase : List[Any] = hidden_size _lowerCamelCase : Any = num_hidden_layers _lowerCamelCase : Any = num_attention_heads _lowerCamelCase : Optional[int] = hidden_act _lowerCamelCase : List[Any] = intermediate_size _lowerCamelCase : Dict = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : List[Any] = max_position_embeddings _lowerCamelCase : int = type_vocab_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Union[str, Any] = layer_norm_eps _lowerCamelCase : Optional[int] = position_embedding_type _lowerCamelCase : Optional[int] = use_cache _lowerCamelCase : List[str] = classifier_dropout class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : int = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCAmelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""") @dataclass class lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_mae""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. _lowerCamelCase : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = split["""test"""] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _lowerCamelCase : str = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = ViTMAEConfig() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) # adapt config config.update( { """mask_ratio""": model_args.mask_ratio, """norm_pix_loss""": model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionSAGPipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: torch.manual_seed(0) _lowerCamelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0) _lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : List[Any] = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> List[Any]: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""") _lowerCamelCase : Union[str, Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = """.""" _lowerCamelCase : int = torch.manual_seed(0) _lowerCamelCase : Tuple = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Dict = output.images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Optional[Any] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Dict = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = """.""" _lowerCamelCase : List[str] = torch.manual_seed(0) _lowerCamelCase : int = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Any = output.images _lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Optional[Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """.""" _lowerCamelCase : Union[str, Any] = torch.manual_seed(0) _lowerCamelCase : Optional[int] = sag_pipe( [prompt] , width=768 , height=512 , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) _lowerCamelCase : Union[str, Any] = output.images assert image.shape == (1, 512, 768, 3)
88
"""simple docstring""" import numpy as np def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return vector * sigmoid(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """microsoft/deberta-v2-xlarge""": """https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json""", """microsoft/deberta-v2-xxlarge""": """https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json""", """microsoft/deberta-v2-xlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json""" ), """microsoft/deberta-v2-xxlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''deberta-v2''' def __init__( self , SCREAMING_SNAKE_CASE=12_8100 , SCREAMING_SNAKE_CASE=1536 , SCREAMING_SNAKE_CASE=24 , SCREAMING_SNAKE_CASE=24 , SCREAMING_SNAKE_CASE=6144 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-7 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=-1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE="gelu" , **SCREAMING_SNAKE_CASE , ) -> Tuple: super().__init__(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = hidden_size _lowerCamelCase : Dict = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : int = intermediate_size _lowerCamelCase : List[str] = hidden_act _lowerCamelCase : List[str] = hidden_dropout_prob _lowerCamelCase : List[Any] = attention_probs_dropout_prob _lowerCamelCase : List[Any] = max_position_embeddings _lowerCamelCase : Tuple = type_vocab_size _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Optional[int] = relative_attention _lowerCamelCase : Optional[int] = max_relative_positions _lowerCamelCase : Optional[int] = pad_token_id _lowerCamelCase : Any = position_biased_input # Backwards compatibility if type(SCREAMING_SNAKE_CASE) == str: _lowerCamelCase : Optional[int] = [x.strip() for x in pos_att_type.lower().split("""|""")] _lowerCamelCase : int = pos_att_type _lowerCamelCase : Optional[Any] = vocab_size _lowerCamelCase : Optional[Any] = layer_norm_eps _lowerCamelCase : Optional[Any] = kwargs.get("""pooler_hidden_size""" , SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = pooler_dropout _lowerCamelCase : Optional[int] = pooler_hidden_act class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : List[str] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : int = {0: """batch""", 1: """sequence"""} if self._config.type_vocab_size > 0: return OrderedDict( [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)]) else: return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)]) @property def UpperCamelCase_ ( self) -> int: return 12 def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = -1 , SCREAMING_SNAKE_CASE = -1 , SCREAMING_SNAKE_CASE = -1 , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 3 , SCREAMING_SNAKE_CASE = 40 , SCREAMING_SNAKE_CASE = 40 , SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: _lowerCamelCase : int = super().generate_dummy_inputs(preprocessor=SCREAMING_SNAKE_CASE , framework=SCREAMING_SNAKE_CASE) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
88
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = HfArgumentParser(__snake_case ) _lowerCamelCase : int = parser.parse_args_into_dataclasses()[0] _lowerCamelCase : Dict = TensorFlowBenchmark(args=__snake_case ) try: _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: _lowerCamelCase : Union[str, Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" _lowerCamelCase : List[str] = """ """.join(str(__snake_case ).split(""" """ )[:-1] ) _lowerCamelCase : Dict = """""" _lowerCamelCase : List[Any] = eval(str(__snake_case ).split(""" """ )[-1] ) _lowerCamelCase : Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _lowerCamelCase : Tuple = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
88
1
"""simple docstring""" import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase = logging.get_logger() def _snake_case ( __snake_case : int , __snake_case : str , __snake_case : LevitConfig , __snake_case : Path , __snake_case : bool = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": _lowerCamelCase : List[str] = timm.create_model("""levit_128s""" , pretrained=__snake_case ) else: _lowerCamelCase : Any = timm.create_model("""levit_128""" , pretrained=__snake_case ) if hidden_sizes == 192: _lowerCamelCase : str = timm.create_model("""levit_192""" , pretrained=__snake_case ) if hidden_sizes == 256: _lowerCamelCase : Tuple = timm.create_model("""levit_256""" , pretrained=__snake_case ) if hidden_sizes == 384: _lowerCamelCase : List[Any] = timm.create_model("""levit_384""" , pretrained=__snake_case ) from_model.eval() _lowerCamelCase : List[Any] = LevitForImageClassificationWithTeacher(__snake_case ).eval() _lowerCamelCase : Union[str, Any] = OrderedDict() _lowerCamelCase : Union[str, Any] = from_model.state_dict() _lowerCamelCase : List[Any] = list(from_model.state_dict().keys() ) _lowerCamelCase : Any = list(our_model.state_dict().keys() ) print(len(__snake_case ) , len(__snake_case ) ) for i in range(len(__snake_case ) ): _lowerCamelCase : Optional[int] = weights[og_keys[i]] our_model.load_state_dict(__snake_case ) _lowerCamelCase : Dict = torch.randn((2, 3, 224, 224) ) _lowerCamelCase : Optional[int] = from_model(__snake_case ) _lowerCamelCase : Optional[int] = our_model(__snake_case ).logits assert torch.allclose(__snake_case , __snake_case ), "The model logits don't match the original one." _lowerCamelCase : str = name print(__snake_case ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) _lowerCamelCase : Optional[int] = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F'Pushed {checkpoint_name}' ) def _snake_case ( __snake_case : Path , __snake_case : str = None , __snake_case : bool = True ): """simple docstring""" _lowerCamelCase : str = """imagenet-1k-id2label.json""" _lowerCamelCase : Optional[Any] = 1000 _lowerCamelCase : Any = (1, num_labels) _lowerCamelCase : int = """huggingface/label-files""" _lowerCamelCase : Union[str, Any] = num_labels _lowerCamelCase : int = json.load(open(hf_hub_download(__snake_case , __snake_case , repo_type="""dataset""" ) , """r""" ) ) _lowerCamelCase : List[str] = {int(__snake_case ): v for k, v in idalabel.items()} _lowerCamelCase : str = idalabel _lowerCamelCase : Optional[int] = {v: k for k, v in idalabel.items()} _lowerCamelCase : int = partial(__snake_case , num_labels=__snake_case , idalabel=__snake_case , labelaid=__snake_case ) _lowerCamelCase : Optional[Any] = { """levit-128S""": 128, """levit-128""": 128, """levit-192""": 192, """levit-256""": 256, """levit-384""": 384, } _lowerCamelCase : Optional[Any] = { """levit-128S""": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), """levit-128""": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), """levit-192""": ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), """levit-256""": ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), """levit-384""": ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , __snake_case , names_to_config[model_name] , __snake_case , __snake_case ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , __snake_case , __snake_case , __snake_case , __snake_case ) return config, expected_shape if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help="""The name of the model you wish to convert, it must be one of the supported Levit* architecture,""", ) parser.add_argument( """--pytorch_dump_folder_path""", default="""levit-dump-folder/""", type=Path, required=False, help="""Path to the output PyTorch model directory.""", ) parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image processor to the hub""") parser.add_argument( """--no-push_to_hub""", dest="""push_to_hub""", action="""store_false""", help="""Do not push model and image processor to the hub""", ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
88
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""", """kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""", """kssteven/ibert-roberta-large-mnli""": ( """https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''ibert''' def __init__( self , SCREAMING_SNAKE_CASE=3_0522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="none" , **SCREAMING_SNAKE_CASE , ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Dict = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Dict = type_vocab_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : Any = quant_mode _lowerCamelCase : List[str] = force_dequant class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
1
"""simple docstring""" from math import ceil def _snake_case ( __snake_case : int = 1001 ): """simple docstring""" _lowerCamelCase : Dict = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): _lowerCamelCase : List[str] = 2 * i + 1 _lowerCamelCase : Optional[Any] = 2 * i _lowerCamelCase : int = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: UpperCAmelCase = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number""")
88
"""simple docstring""" from __future__ import annotations import queue class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : int = data _lowerCamelCase : List[str] = None _lowerCamelCase : Any = None def _snake_case ( ): """simple docstring""" print("""\n********Press N to stop entering at any point of time********\n""" ) _lowerCamelCase : Optional[int] = input("""Enter the value of the root node: """ ).strip().lower() _lowerCamelCase : queue.Queue = queue.Queue() _lowerCamelCase : Optional[int] = TreeNode(int(__snake_case ) ) q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Tuple = q.get() _lowerCamelCase : Any = F'Enter the left node of {node_found.data}: ' _lowerCamelCase : Union[str, Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : Dict = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[str] = left_node q.put(__snake_case ) _lowerCamelCase : Optional[int] = F'Enter the right node of {node_found.data}: ' _lowerCamelCase : Optional[Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : List[Any] = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[Any] = right_node q.put(__snake_case ) raise def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Any = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Optional[Any] = [] while not q.empty(): _lowerCamelCase : Dict = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__snake_case ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : Optional[int] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__snake_case ) _lowerCamelCase : Tuple = n.left # end of while means current node doesn't have left child _lowerCamelCase : Optional[Any] = stack.pop() # start to traverse its right child _lowerCamelCase : Dict = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : int = node while n or stack: while n: stack.append(__snake_case ) _lowerCamelCase : Any = n.left _lowerCamelCase : Optional[Any] = stack.pop() print(n.data , end=""",""" ) _lowerCamelCase : List[Any] = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase , _lowerCamelCase : Union[str, Any] = [], [] _lowerCamelCase : Optional[Any] = node stacka.append(__snake_case ) while stacka: # to find the reversed order of post order, store it in stack2 _lowerCamelCase : Union[str, Any] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__snake_case ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def _snake_case ( __snake_case : str = "" , __snake_case : Any=50 , __snake_case : List[str]="*" ): """simple docstring""" if not s: return "\n" + width * char _lowerCamelCase , _lowerCamelCase : Optional[int] = divmod(width - len(__snake_case ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
88
1
"""simple docstring""" import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowercase__ ( A_ ,unittest.TestCase ): __UpperCAmelCase = BioGptTokenizer __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Dict: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _lowerCamelCase : str = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] _lowerCamelCase : Optional[Any] = dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE)))) _lowerCamelCase : List[str] = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] _lowerCamelCase : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""]) _lowerCamelCase : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""]) with open(self.vocab_file , """w""") as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE)) with open(self.merges_file , """w""") as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> Union[str, Any]: _lowerCamelCase : Optional[int] = """lower newer""" _lowerCamelCase : Optional[Any] = """lower newer""" return input_text, output_text def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : Dict = BioGptTokenizer(self.vocab_file , self.merges_file) _lowerCamelCase : Dict = """lower""" _lowerCamelCase : List[Any] = ["""low""", """er</w>"""] _lowerCamelCase : Optional[Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : int = tokens + ["""<unk>"""] _lowerCamelCase : int = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE) , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : int = BioGptTokenizer.from_pretrained("""microsoft/biogpt""") _lowerCamelCase : int = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.assertTrue(encoded_sentence == [2] + text) self.assertTrue(encoded_pair == [2] + text + [2] + text_a)
88
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowercase__ : __UpperCAmelCase = XGLMConfig __UpperCAmelCase = {} __UpperCAmelCase = '''gelu''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=14 , SCREAMING_SNAKE_CASE=7 , 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=0.02 , ) -> List[str]: _lowerCamelCase : Optional[int] = parent _lowerCamelCase : int = batch_size _lowerCamelCase : str = seq_length _lowerCamelCase : Any = is_training _lowerCamelCase : int = use_input_mask _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : str = vocab_size _lowerCamelCase : List[str] = d_model _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : int = ffn_dim _lowerCamelCase : str = activation_function _lowerCamelCase : Optional[int] = activation_dropout _lowerCamelCase : Tuple = attention_dropout _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Dict = initializer_range _lowerCamelCase : Optional[Any] = None _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[Any] = 2 _lowerCamelCase : str = 1 def UpperCamelCase_ ( self) -> int: return XGLMConfig.from_pretrained("""facebook/xglm-564M""") def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) , clip_value_min=0 , clip_value_max=3) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Tuple = self.get_config() _lowerCamelCase : Optional[int] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2) return ( config, input_ids, input_mask, head_mask, ) def UpperCamelCase_ ( self) -> Optional[int]: return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : str = config_and_inputs _lowerCamelCase : Optional[Any] = { """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () __UpperCAmelCase = (TFXGLMForCausalLM,) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Optional[Any] = TFXGLMModelTester(self) _lowerCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , n_embd=37) def UpperCamelCase_ ( self) -> Dict: self.config_tester.run_common_tests() @slow def UpperCamelCase_ ( self) -> List[Any]: for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""") def UpperCamelCase_ ( self) -> List[Any]: super().test_resize_token_embeddings() @require_tf class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=True) -> List[Any]: _lowerCamelCase : List[str] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Union[str, Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCamelCase : Dict = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on _lowerCamelCase : str = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: _lowerCamelCase : int = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") tf.random.set_seed(0) _lowerCamelCase : Union[str, Any] = tokenizer("""Today is a nice day and""" , return_tensors="""tf""") _lowerCamelCase : Any = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(""":/CPU:0"""): _lowerCamelCase : Any = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , seed=[7, 0]) _lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = ( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Any = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : List[Any] = """left""" # use different length sentences to test batching _lowerCamelCase : List[Any] = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""tf""" , padding=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = inputs["""input_ids"""] _lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , attention_mask=inputs["""attention_mask"""] , max_new_tokens=12) _lowerCamelCase : List[str] = tokenizer(sentences[0] , return_tensors="""tf""").input_ids _lowerCamelCase : Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Tuple = tokenizer(sentences[1] , return_tensors="""tf""").input_ids _lowerCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , [non_padded_sentence, padded_sentence])
88
1
"""simple docstring""" UpperCAmelCase = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } def _snake_case ( __snake_case : dict , __snake_case : List[str] , __snake_case : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = set() # keep track of all the paths to be checked _lowerCamelCase : List[Any] = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue _lowerCamelCase : List[str] = queue.pop(0 ) # get the last node from the path _lowerCamelCase : Optional[Any] = path[-1] if node not in explored: _lowerCamelCase : int = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: _lowerCamelCase : Optional[Any] = list(__snake_case ) new_path.append(__snake_case ) queue.append(__snake_case ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(__snake_case ) # in case there's no path between the 2 nodes return [] def _snake_case ( __snake_case : dict , __snake_case : Union[str, Any] , __snake_case : Union[str, Any] ): """simple docstring""" if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 _lowerCamelCase : Any = [start] _lowerCamelCase : List[Any] = set(__snake_case ) # Keep tab on distances from `start` node. _lowerCamelCase : int = {start: 0, target: -1} while queue: _lowerCamelCase : List[Any] = queue.pop(0 ) if node == target: _lowerCamelCase : int = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(__snake_case ) queue.append(__snake_case ) _lowerCamelCase : Dict = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, """G""", """D""")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, """G""", """D""")) # returns 4
88
"""simple docstring""" from collections import defaultdict def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : Tuple = first_str.lower().strip() _lowerCamelCase : int = second_str.lower().strip() # Remove whitespace _lowerCamelCase : Any = first_str.replace(""" """ , """""" ) _lowerCamelCase : List[str] = second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(__snake_case ) != len(__snake_case ): return False # Default values for count should be 0 _lowerCamelCase : defaultdict[str, int] = defaultdict(__snake_case ) # For each character in input strings, # increment count in the corresponding for i in range(len(__snake_case ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase = input("""Enter the first string """).strip() UpperCAmelCase = input("""Enter the second string """).strip() UpperCAmelCase = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
88
1
"""simple docstring""" from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , SCREAMING_SNAKE_CASE=[1, 1, 2, 1] , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE="relu" , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , ) -> Any: _lowerCamelCase : Dict = parent _lowerCamelCase : Dict = batch_size _lowerCamelCase : Optional[Any] = image_size _lowerCamelCase : Any = num_channels _lowerCamelCase : Any = embeddings_size _lowerCamelCase : Optional[int] = hidden_sizes _lowerCamelCase : Tuple = depths _lowerCamelCase : List[Any] = is_training _lowerCamelCase : int = use_labels _lowerCamelCase : str = hidden_act _lowerCamelCase : Dict = num_labels _lowerCamelCase : int = scope _lowerCamelCase : Optional[Any] = len(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) _lowerCamelCase : Dict = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_labels) _lowerCamelCase : Tuple = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self) -> Dict: return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Any: _lowerCamelCase : Optional[int] = TFRegNetModel(config=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : Optional[Any] = self.num_labels _lowerCamelCase : List[str] = TFRegNetForImageClassification(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[int] = self.prepare_config_and_inputs() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = config_and_inputs _lowerCamelCase : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : str = TFRegNetModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: return @unittest.skip(reason="""RegNet does not use inputs_embeds""") def UpperCamelCase_ ( self) -> List[str]: pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""")) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) @slow def UpperCamelCase_ ( self) -> List[str]: super().test_keras_fit() @unittest.skip(reason="""RegNet does not support input and output embeddings""") def UpperCamelCase_ ( self) -> Optional[Any]: pass def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : Any = [*signature.parameters.keys()] _lowerCamelCase : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: def check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : int = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) , training=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _lowerCamelCase : Union[str, Any] = self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE) , expected_num_stages + 1) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _lowerCamelCase : Any = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: _lowerCamelCase : Union[str, Any] = layer_type _lowerCamelCase : List[Any] = True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCamelCase : Tuple = True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase , _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE={}): _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE).to_tuple() def recursive_check(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): if isinstance(SCREAMING_SNAKE_CASE , (List, Tuple)): for tuple_iterable_value, dict_iterable_value in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): recursive_check(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)) , msg=( """Tuple and dict output are not equal. Difference:""" F' {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}' ) , ) recursive_check(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) for model_class in self.all_model_classes: _lowerCamelCase : Tuple = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True}) _lowerCamelCase : int = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True}) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : List[str] = TFRegNetModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def _snake_case ( ): """simple docstring""" _lowerCamelCase : str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> Any: return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) _lowerCamelCase : Optional[int] = self.default_image_processor _lowerCamelCase : int = prepare_img() _lowerCamelCase : List[Any] = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="""tf""") # forward pass _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE) # verify the logits _lowerCamelCase : Tuple = tf.TensorShape((1, 1000)) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tf.constant([-0.41_80, -1.50_51, -3.48_36]) tf.debugging.assert_near(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4)
88
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _snake_case ( __snake_case : float , __snake_case : float , __snake_case : bool = False ): """simple docstring""" if radian_mode: return [magnitude * cos(__snake_case ), magnitude * sin(__snake_case )] return [magnitude * cos(radians(__snake_case ) ), magnitude * sin(radians(__snake_case ) )] def _snake_case ( __snake_case : NDArray[floataa] , __snake_case : NDArray[floataa] , __snake_case : float = 10**-1 ): """simple docstring""" _lowerCamelCase : NDArray[floataa] = cross(__snake_case , __snake_case ) _lowerCamelCase : float = sum(__snake_case ) return abs(__snake_case ) < eps if __name__ == "__main__": # Test to check if it works UpperCAmelCase = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg UpperCAmelCase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg UpperCAmelCase = array([[0, -2000], [0, -1200], [0, 1_5600], [0, -1_2400]]) UpperCAmelCase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
88
1
"""simple docstring""" import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL UpperCAmelCase = version.parse(version.parse(torch.__version__).base_version) < version.parse("""1.11""") def _snake_case ( __snake_case : str , __snake_case : tuple , __snake_case : Path , __snake_case : Tuple , __snake_case : List[str] , __snake_case : List[str] , __snake_case : List[Any] , __snake_case : Optional[Any]=False , ): """simple docstring""" output_path.parent.mkdir(parents=__snake_case , exist_ok=__snake_case ) # 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( __snake_case , __snake_case , f=output_path.as_posix() , input_names=__snake_case , output_names=__snake_case , dynamic_axes=__snake_case , do_constant_folding=__snake_case , use_external_data_format=__snake_case , enable_onnx_checker=__snake_case , opset_version=__snake_case , ) else: export( __snake_case , __snake_case , f=output_path.as_posix() , input_names=__snake_case , output_names=__snake_case , dynamic_axes=__snake_case , do_constant_folding=__snake_case , opset_version=__snake_case , ) @torch.no_grad() def _snake_case ( __snake_case : str , __snake_case : str , __snake_case : int , __snake_case : bool = False ): """simple docstring""" _lowerCamelCase : List[str] = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): _lowerCamelCase : Optional[Any] = """cuda""" elif fpaa and not torch.cuda.is_available(): raise ValueError("""`float16` model export is only supported on GPUs with CUDA""" ) else: _lowerCamelCase : Tuple = """cpu""" _lowerCamelCase : Optional[int] = Path(__snake_case ) # VAE DECODER _lowerCamelCase : List[Any] = AutoencoderKL.from_pretrained(model_path + """/vae""" ) _lowerCamelCase : List[str] = vae_decoder.config.latent_channels # forward only through the decoder part _lowerCamelCase : Dict = vae_decoder.decode onnx_export( __snake_case , model_args=( torch.randn(1 , __snake_case , 25 , 25 ).to(device=__snake_case , dtype=__snake_case ), 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=__snake_case , ) del vae_decoder if __name__ == "__main__": UpperCAmelCase = 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""") UpperCAmelCase = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print("""SD: Done: ONNX""")
88
"""simple docstring""" import random def _snake_case ( __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = a[left_index] _lowerCamelCase : Dict = left_index + 1 for j in range(left_index + 1 , __snake_case ): if a[j] < pivot: _lowerCamelCase , _lowerCamelCase : List[str] = a[i], a[j] i += 1 _lowerCamelCase , _lowerCamelCase : Optional[int] = a[i - 1], a[left_index] return i - 1 def _snake_case ( __snake_case : Tuple , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" if left < right: _lowerCamelCase : Any = random.randint(__snake_case , right - 1 ) _lowerCamelCase , _lowerCamelCase : Optional[Any] = ( a[left], a[pivot], ) # switches the pivot with the left most bound _lowerCamelCase : List[str] = partition(__snake_case , __snake_case , __snake_case ) quick_sort_random( __snake_case , __snake_case , __snake_case ) # recursive quicksort to the left of the pivot point quick_sort_random( __snake_case , pivot_index + 1 , __snake_case ) # recursive quicksort to the right of the pivot point def _snake_case ( ): """simple docstring""" _lowerCamelCase : Union[str, Any] = input("""Enter numbers separated by a comma:\n""" ).strip() _lowerCamelCase : int = [int(__snake_case ) for item in user_input.split(""",""" )] quick_sort_random(__snake_case , 0 , len(__snake_case ) ) print(__snake_case ) if __name__ == "__main__": main()
88
1
"""simple docstring""" import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser( description=( """Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned""" """ Distillation""" ) ) parser.add_argument("""--model_type""", default="""roberta""", choices=["""roberta""", """gpt2"""]) parser.add_argument("""--model_name""", default="""roberta-large""", type=str) parser.add_argument("""--dump_checkpoint""", default="""serialization_dir/tf_roberta_048131723.pth""", type=str) parser.add_argument("""--vocab_transform""", action="""store_true""") UpperCAmelCase = parser.parse_args() if args.model_type == "roberta": UpperCAmelCase = RobertaForMaskedLM.from_pretrained(args.model_name) UpperCAmelCase = """roberta""" elif args.model_type == "gpt2": UpperCAmelCase = GPTaLMHeadModel.from_pretrained(args.model_name) UpperCAmelCase = """transformer""" UpperCAmelCase = model.state_dict() UpperCAmelCase = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: UpperCAmelCase = state_dict[f'''{prefix}.{param_name}'''] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: UpperCAmelCase = f'''{prefix}.embeddings.{w}.weight''' UpperCAmelCase = state_dict[param_name] for w in ["weight", "bias"]: UpperCAmelCase = f'''{prefix}.embeddings.LayerNorm.{w}''' UpperCAmelCase = state_dict[param_name] # Transformer Blocks # UpperCAmelCase = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: UpperCAmelCase = state_dict[ f'''{prefix}.h.{teacher_idx}.{layer}.{w}''' ] UpperCAmelCase = state_dict[f'''{prefix}.h.{teacher_idx}.attn.bias'''] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: UpperCAmelCase = state_dict[ f'''{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}''' ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: UpperCAmelCase = state_dict[f'''{layer}'''] if args.vocab_transform: for w in ["weight", "bias"]: UpperCAmelCase = state_dict[f'''lm_head.dense.{w}'''] UpperCAmelCase = state_dict[f'''lm_head.layer_norm.{w}'''] elif args.model_type == "gpt2": for w in ["weight", "bias"]: UpperCAmelCase = state_dict[f'''{prefix}.ln_f.{w}'''] UpperCAmelCase = state_dict["""lm_head.weight"""] print(f'''N layers selected for distillation: {std_idx}''') print(f'''Number of params transferred for distillation: {len(compressed_sd.keys())}''') print(f'''Save transferred checkpoint to {args.dump_checkpoint}.''') torch.save(compressed_sd, args.dump_checkpoint)
88
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase = """\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } """ UpperCAmelCase = """\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). """ UpperCAmelCase = """ Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric(\"code_eval\") >>> test_cases = [\"assert add(2,3)==5\"] >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {'pass@1': 0.5, 'pass@2': 1.0} """ UpperCAmelCase = """ ################################################################################ !!!WARNING!!! ################################################################################ The \"code_eval\" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this with: >>> import os >>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\" ################################################################################\ """ UpperCAmelCase = """The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> str: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""")), """references""": datasets.Value("""string"""), }) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=[1, 10, 100] , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=3.0) -> Union[str, Any]: if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0) != "1": raise ValueError(_WARNING) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""") with ThreadPoolExecutor(max_workers=SCREAMING_SNAKE_CASE) as executor: _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Optional[int] = Counter() _lowerCamelCase : Any = 0 _lowerCamelCase : List[Any] = defaultdict(SCREAMING_SNAKE_CASE) for task_id, (candidates, test_case) in enumerate(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)): for candidate in candidates: _lowerCamelCase : Any = candidate + """\n""" + test_case _lowerCamelCase : Union[str, Any] = (test_program, timeout, task_id, completion_id[task_id]) _lowerCamelCase : List[str] = executor.submit(SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE) futures.append(SCREAMING_SNAKE_CASE) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(SCREAMING_SNAKE_CASE): _lowerCamelCase : int = future.result() results[result["task_id"]].append((result["""completion_id"""], result)) _lowerCamelCase , _lowerCamelCase : List[Any] = [], [] for result in results.values(): result.sort() _lowerCamelCase : List[str] = [r[1]["""passed"""] for r in result] total.append(len(SCREAMING_SNAKE_CASE)) correct.append(sum(SCREAMING_SNAKE_CASE)) _lowerCamelCase : List[Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = k _lowerCamelCase : Optional[Any] = {F'pass@{k}': estimate_pass_at_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).mean() for k in ks if (total >= k).all()} return pass_at_k, results def _snake_case ( __snake_case : List[str] , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" def estimator(__snake_case : int , __snake_case : int , __snake_case : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(__snake_case , __snake_case ): _lowerCamelCase : Optional[int] = itertools.repeat(__snake_case , len(__snake_case ) ) else: assert len(__snake_case ) == len(__snake_case ) _lowerCamelCase : List[str] = iter(__snake_case ) return np.array([estimator(int(__snake_case ) , int(__snake_case ) , __snake_case ) for n, c in zip(__snake_case , __snake_case )] )
88
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu UpperCAmelCase = False class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Optional[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase_ ( self) -> Optional[int]: return 12 @property def UpperCamelCase_ ( self) -> List[Any]: return 12 @property def UpperCamelCase_ ( self) -> Dict: return 32 @property def UpperCamelCase_ ( self) -> Dict: torch.manual_seed(0) _lowerCamelCase : Tuple = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=3 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : Union[str, Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") return tokenizer @property def UpperCamelCase_ ( self) -> Tuple: torch.manual_seed(0) _lowerCamelCase : List[str] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(SCREAMING_SNAKE_CASE) @property def UpperCamelCase_ ( self) -> Optional[int]: torch.manual_seed(0) _lowerCamelCase : Tuple = 12 _lowerCamelCase : List[Any] = 12 _lowerCamelCase : List[str] = { """attention_bias""": True, """cross_attention_dim""": 32, """attention_head_dim""": height * width, """num_attention_heads""": 1, """num_vector_embeds""": self.num_embed, """num_embeds_ada_norm""": self.num_embeds_ada_norm, """norm_num_groups""": 32, """sample_size""": width, """activation_fn""": """geglu-approximate""", } _lowerCamelCase : Dict = TransformeraDModel(**SCREAMING_SNAKE_CASE) return model def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[Any] = """cpu""" _lowerCamelCase : Optional[Any] = self.dummy_vqvae _lowerCamelCase : Dict = self.dummy_text_encoder _lowerCamelCase : int = self.dummy_tokenizer _lowerCamelCase : List[str] = self.dummy_transformer _lowerCamelCase : List[Any] = VQDiffusionScheduler(self.num_embed) _lowerCamelCase : Tuple = LearnedClassifierFreeSamplingEmbeddings(learnable=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = VQDiffusionPipeline( vqvae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , transformer=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , learned_classifier_free_sampling_embeddings=SCREAMING_SNAKE_CASE , ) _lowerCamelCase : str = pipe.to(SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = """teddy bear playing in the pool""" _lowerCamelCase : Union[str, Any] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(0) _lowerCamelCase : Dict = pipe([prompt] , generator=SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""") _lowerCamelCase : int = output.images _lowerCamelCase : int = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(0) _lowerCamelCase : Dict = pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , output_type="""np""" , return_dict=SCREAMING_SNAKE_CASE , num_inference_steps=2)[0] _lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] _lowerCamelCase : Tuple = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) _lowerCamelCase : Dict = np.array([0.65_51, 0.61_68, 0.50_08, 0.56_76, 0.56_59, 0.42_95, 0.60_73, 0.55_99, 0.49_92]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2 def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Dict = """cpu""" _lowerCamelCase : Optional[int] = self.dummy_vqvae _lowerCamelCase : Union[str, Any] = self.dummy_text_encoder _lowerCamelCase : Union[str, Any] = self.dummy_tokenizer _lowerCamelCase : Optional[int] = self.dummy_transformer _lowerCamelCase : Any = VQDiffusionScheduler(self.num_embed) _lowerCamelCase : Tuple = LearnedClassifierFreeSamplingEmbeddings( learnable=SCREAMING_SNAKE_CASE , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length) _lowerCamelCase : Dict = VQDiffusionPipeline( vqvae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , transformer=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , learned_classifier_free_sampling_embeddings=SCREAMING_SNAKE_CASE , ) _lowerCamelCase : Any = pipe.to(SCREAMING_SNAKE_CASE) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """teddy bear playing in the pool""" _lowerCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(0) _lowerCamelCase : Optional[int] = pipe([prompt] , generator=SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""") _lowerCamelCase : Union[str, Any] = output.images _lowerCamelCase : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(0) _lowerCamelCase : str = pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , output_type="""np""" , return_dict=SCREAMING_SNAKE_CASE , num_inference_steps=2)[0] _lowerCamelCase : Any = image[0, -3:, -3:, -1] _lowerCamelCase : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) _lowerCamelCase : List[str] = np.array([0.66_93, 0.60_75, 0.49_59, 0.57_01, 0.55_83, 0.43_33, 0.61_71, 0.56_84, 0.49_88]) assert np.abs(image_slice.flatten() - expected_slice).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2 @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Optional[int]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy""") _lowerCamelCase : Dict = VQDiffusionPipeline.from_pretrained("""microsoft/vq-diffusion-ithq""") _lowerCamelCase : List[Any] = pipeline.to(SCREAMING_SNAKE_CASE) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though _lowerCamelCase : Union[str, Any] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(0) _lowerCamelCase : List[Any] = pipeline( """teddy bear playing in the pool""" , num_images_per_prompt=1 , generator=SCREAMING_SNAKE_CASE , output_type="""np""" , ) _lowerCamelCase : str = output.images[0] assert image.shape == (256, 256, 3) assert np.abs(expected_image - image).max() < 2.0
88
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo UpperCAmelCase = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ UpperCAmelCase = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ UpperCAmelCase = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence"""), """references""": datasets.Sequence( datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence""") , id="""references"""), }) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 4 , ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=SCREAMING_SNAKE_CASE , hypotheses=SCREAMING_SNAKE_CASE , min_len=SCREAMING_SNAKE_CASE , max_len=SCREAMING_SNAKE_CASE) }
88
1
"""simple docstring""" import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class lowercase__ ( unittest.TestCase ): __UpperCAmelCase = MODEL_FOR_MASKED_LM_MAPPING __UpperCAmelCase = TF_MODEL_FOR_MASKED_LM_MAPPING def UpperCamelCase_ ( self) -> Tuple: super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : int = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""tf""") _lowerCamelCase : List[Any] = unmasker("""My name is <mask>""") self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6) , [ {"""sequence""": """My name is grouped""", """score""": 2.1e-0_5, """token""": 3_8015, """token_str""": """ grouped"""}, {"""sequence""": """My name is accuser""", """score""": 2.1e-0_5, """token""": 2_5506, """token_str""": """ accuser"""}, ] , ) _lowerCamelCase : Union[str, Any] = unmasker("""The largest city in France is <mask>""") self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6) , [ { """sequence""": """The largest city in France is grouped""", """score""": 2.1e-0_5, """token""": 3_8015, """token_str""": """ grouped""", }, { """sequence""": """The largest city in France is accuser""", """score""": 2.1e-0_5, """token""": 2_5506, """token_str""": """ accuser""", }, ] , ) _lowerCamelCase : Optional[int] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6) , [ {"""sequence""": """My name is Clara""", """score""": 2e-0_5, """token""": 1_3606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Patrick""", """score""": 2e-0_5, """token""": 3499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 1.9e-0_5, """token""": 2941, """token_str""": """ Te"""}, ] , ) @require_torch def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""pt""") _lowerCamelCase : Dict = unmasker("""My name is <mask>""") self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6) , [ {"""sequence""": """My name is Maul""", """score""": 2.2e-0_5, """token""": 3_5676, """token_str""": """ Maul"""}, {"""sequence""": """My name isELS""", """score""": 2.2e-0_5, """token""": 1_6416, """token_str""": """ELS"""}, ] , ) _lowerCamelCase : Tuple = unmasker("""The largest city in France is <mask>""") self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6) , [ { """sequence""": """The largest city in France is Maul""", """score""": 2.2e-0_5, """token""": 3_5676, """token_str""": """ Maul""", }, {"""sequence""": """The largest city in France isELS""", """score""": 2.2e-0_5, """token""": 1_6416, """token_str""": """ELS"""}, ] , ) _lowerCamelCase : Dict = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6) , [ {"""sequence""": """My name is Patrick""", """score""": 2.1e-0_5, """token""": 3499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 2e-0_5, """token""": 2941, """token_str""": """ Te"""}, {"""sequence""": """My name is Clara""", """score""": 2e-0_5, """token""": 1_3606, """token_str""": """ Clara"""}, ] , ) _lowerCamelCase : Union[str, Any] = unmasker("""My name is <mask> <mask>""" , top_k=2) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=6) , [ [ { """score""": 2.2e-0_5, """token""": 3_5676, """token_str""": """ Maul""", """sequence""": """<s>My name is Maul<mask></s>""", }, {"""score""": 2.2e-0_5, """token""": 1_6416, """token_str""": """ELS""", """sequence""": """<s>My name isELS<mask></s>"""}, ], [ { """score""": 2.2e-0_5, """token""": 3_5676, """token_str""": """ Maul""", """sequence""": """<s>My name is<mask> Maul</s>""", }, {"""score""": 2.2e-0_5, """token""": 1_6416, """token_str""": """ELS""", """sequence""": """<s>My name is<mask>ELS</s>"""}, ], ] , ) @require_torch_gpu def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[int] = pipeline("""fill-mask""" , model="""hf-internal-testing/tiny-random-distilbert""" , device=0 , framework="""pt""") # convert model to fp16 pipe.model.half() _lowerCamelCase : List[str] = pipe("""Paris is the [MASK] of France.""") # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) @slow @require_torch def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : Any = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""pt""") self.run_large_test(SCREAMING_SNAKE_CASE) @slow @require_tf def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Tuple = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""tf""") self.run_large_test(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> Tuple: _lowerCamelCase : Optional[int] = unmasker("""My name is <mask>""") self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE) , [ {"""sequence""": """My name is John""", """score""": 0.0_08, """token""": 610, """token_str""": """ John"""}, {"""sequence""": """My name is Chris""", """score""": 0.0_07, """token""": 1573, """token_str""": """ Chris"""}, ] , ) _lowerCamelCase : Tuple = unmasker("""The largest city in France is <mask>""") self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE) , [ { """sequence""": """The largest city in France is Paris""", """score""": 0.2_51, """token""": 2201, """token_str""": """ Paris""", }, { """sequence""": """The largest city in France is Lyon""", """score""": 0.2_14, """token""": 1_2790, """token_str""": """ Lyon""", }, ] , ) _lowerCamelCase : int = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE) , [ {"""sequence""": """My name is Patrick""", """score""": 0.0_05, """token""": 3499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Clara""", """score""": 0.0_00, """token""": 1_3606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Te""", """score""": 0.0_00, """token""": 2941, """token_str""": """ Te"""}, ] , ) @require_torch def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""pt""") _lowerCamelCase : int = None _lowerCamelCase : int = None self.run_pipeline_test(SCREAMING_SNAKE_CASE , []) @require_tf def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""tf""") _lowerCamelCase : Dict = None _lowerCamelCase : int = None self.run_pipeline_test(SCREAMING_SNAKE_CASE , []) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("""The provided tokenizer has no mask token, (probably reformer or wav2vec2)""") _lowerCamelCase : List[Any] = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = [ F'This is another {tokenizer.mask_token} test', ] return fill_masker, examples def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Any: _lowerCamelCase : Dict = fill_masker.tokenizer _lowerCamelCase : Union[str, Any] = fill_masker.model _lowerCamelCase : int = fill_masker( F'This is a {tokenizer.mask_token}' , ) self.assertEqual( SCREAMING_SNAKE_CASE , [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, ] , ) _lowerCamelCase : Optional[int] = fill_masker([F'This is a {tokenizer.mask_token}']) self.assertEqual( SCREAMING_SNAKE_CASE , [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, ] , ) _lowerCamelCase : Optional[int] = fill_masker([F'This is a {tokenizer.mask_token}', F'Another {tokenizer.mask_token} great test.']) self.assertEqual( SCREAMING_SNAKE_CASE , [ [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, ], [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, ], ] , ) with self.assertRaises(SCREAMING_SNAKE_CASE): fill_masker([None]) # No mask_token is not supported with self.assertRaises(SCREAMING_SNAKE_CASE): fill_masker("""This is""") self.run_test_top_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.run_test_targets(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.run_test_top_k_targets(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.fill_mask_with_duplicate_targets_and_top_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.fill_mask_with_multiple_masks(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[Any]: _lowerCamelCase : List[str] = tokenizer.get_vocab() _lowerCamelCase : Union[str, Any] = sorted(vocab.keys())[:2] # Pipeline argument _lowerCamelCase : int = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , targets=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = fill_masker(F'This is a {tokenizer.mask_token}') self.assertEqual( SCREAMING_SNAKE_CASE , [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, ] , ) _lowerCamelCase : Optional[int] = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = [tokenizer.decode([x]) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(SCREAMING_SNAKE_CASE)) # Call argument _lowerCamelCase : int = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = fill_masker(F'This is a {tokenizer.mask_token}' , targets=SCREAMING_SNAKE_CASE) self.assertEqual( SCREAMING_SNAKE_CASE , [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, ] , ) _lowerCamelCase : Dict = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = [tokenizer.decode([x]) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(SCREAMING_SNAKE_CASE)) # Score equivalence _lowerCamelCase : List[str] = fill_masker(F'This is a {tokenizer.mask_token}' , targets=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = [top_mask["""token_str"""] for top_mask in outputs] _lowerCamelCase : Dict = [top_mask["""score"""] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(SCREAMING_SNAKE_CASE) == set(SCREAMING_SNAKE_CASE): _lowerCamelCase : Optional[int] = fill_masker(F'This is a {tokenizer.mask_token}' , targets=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = [top_mask["""score"""] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE) , nested_simplify(SCREAMING_SNAKE_CASE)) # Raises with invalid with self.assertRaises(SCREAMING_SNAKE_CASE): _lowerCamelCase : str = fill_masker(F'This is a {tokenizer.mask_token}' , targets=[]) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(SCREAMING_SNAKE_CASE): _lowerCamelCase : Union[str, Any] = fill_masker(F'This is a {tokenizer.mask_token}' , targets=[""""""]) with self.assertRaises(SCREAMING_SNAKE_CASE): _lowerCamelCase : List[str] = fill_masker(F'This is a {tokenizer.mask_token}' , targets="""""") def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> List[Any]: _lowerCamelCase : List[str] = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , top_k=2) _lowerCamelCase : Any = fill_masker(F'This is a {tokenizer.mask_token}') self.assertEqual( SCREAMING_SNAKE_CASE , [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, ] , ) _lowerCamelCase : List[str] = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = fill_masker(F'This is a {tokenizer.mask_token}' , top_k=2) self.assertEqual( SCREAMING_SNAKE_CASE , [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, ] , ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE) , nested_simplify(SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : Optional[int] = tokenizer.get_vocab() _lowerCamelCase : str = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE) # top_k=2, ntargets=3 _lowerCamelCase : List[str] = sorted(vocab.keys())[:3] _lowerCamelCase : Optional[int] = fill_masker(F'This is a {tokenizer.mask_token}' , top_k=2 , targets=SCREAMING_SNAKE_CASE) # If we use the most probably targets, and filter differently, we should still # have the same results _lowerCamelCase : Optional[Any] = [el["""token_str"""] for el in sorted(SCREAMING_SNAKE_CASE , key=lambda SCREAMING_SNAKE_CASE: x["score"] , reverse=SCREAMING_SNAKE_CASE)] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(SCREAMING_SNAKE_CASE).issubset(SCREAMING_SNAKE_CASE): _lowerCamelCase : Any = fill_masker(F'This is a {tokenizer.mask_token}' , top_k=3 , targets=SCREAMING_SNAKE_CASE) # They should yield exactly the same result self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE) , nested_simplify(SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Any: _lowerCamelCase : Tuple = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = tokenizer.get_vocab() # String duplicates + id duplicates _lowerCamelCase : List[Any] = sorted(vocab.keys())[:3] _lowerCamelCase : str = [targets[0], targets[1], targets[0], targets[2], targets[1]] _lowerCamelCase : Union[str, Any] = fill_masker(F'My name is {tokenizer.mask_token}' , targets=SCREAMING_SNAKE_CASE , top_k=10) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(SCREAMING_SNAKE_CASE) , 3) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> List[Any]: _lowerCamelCase : Optional[int] = FillMaskPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = fill_masker( F'This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}' , top_k=2) self.assertEqual( SCREAMING_SNAKE_CASE , [ [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, ], [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, ], [ {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, {"""sequence""": ANY(SCREAMING_SNAKE_CASE), """score""": ANY(SCREAMING_SNAKE_CASE), """token""": ANY(SCREAMING_SNAKE_CASE), """token_str""": ANY(SCREAMING_SNAKE_CASE)}, ], ] , )
88
"""simple docstring""" def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : str = len(__snake_case ) _lowerCamelCase : Union[str, Any] = len(__snake_case ) _lowerCamelCase : int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] _lowerCamelCase : Union[str, Any] = True for i in range(__snake_case ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: _lowerCamelCase : Tuple = True if a[i].islower(): _lowerCamelCase : Tuple = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def _snake_case ( __snake_case : Optional[Any] , __snake_case : Any , __snake_case : List[Any] ): """simple docstring""" _lowerCamelCase : Dict = 1.5 _lowerCamelCase : List[Any] = int(factor * num_class_images ) _lowerCamelCase : List[str] = ClipClient( url="""https://knn.laion.ai/knn-service""" , indice_name="""laion_400m""" , num_images=__snake_case , aesthetic_weight=0.1 ) os.makedirs(F'{class_data_dir}/images' , exist_ok=__snake_case ) if len(list(Path(F'{class_data_dir}/images' ).iterdir() ) ) >= num_class_images: return while True: _lowerCamelCase : Optional[int] = client.query(text=__snake_case ) if len(__snake_case ) >= factor * num_class_images or num_images > 1E4: break else: _lowerCamelCase : Any = int(factor * num_images ) _lowerCamelCase : str = ClipClient( url="""https://knn.laion.ai/knn-service""" , indice_name="""laion_400m""" , num_images=__snake_case , aesthetic_weight=0.1 , ) _lowerCamelCase : Dict = 0 _lowerCamelCase : List[Any] = 0 _lowerCamelCase : Tuple = tqdm(desc="""downloading real regularization images""" , total=__snake_case ) with open(F'{class_data_dir}/caption.txt' , """w""" ) as fa, open(F'{class_data_dir}/urls.txt' , """w""" ) as fa, open( F'{class_data_dir}/images.txt' , """w""" ) as fa: while total < num_class_images: _lowerCamelCase : Dict = class_images[count] count += 1 try: _lowerCamelCase : Optional[Any] = requests.get(images["""url"""] ) if img.status_code == 200: _lowerCamelCase : Optional[int] = Image.open(BytesIO(img.content ) ) with open(F'{class_data_dir}/images/{total}.jpg' , """wb""" ) as f: f.write(img.content ) fa.write(images["""caption"""] + """\n""" ) fa.write(images["""url"""] + """\n""" ) fa.write(F'{class_data_dir}/images/{total}.jpg' + """\n""" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[str] = argparse.ArgumentParser("""""" , add_help=__snake_case ) parser.add_argument("""--class_prompt""" , help="""text prompt to retrieve images""" , required=__snake_case , type=__snake_case ) parser.add_argument("""--class_data_dir""" , help="""path to save images""" , required=__snake_case , type=__snake_case ) parser.add_argument("""--num_class_images""" , help="""number of images to download""" , default=200 , type=__snake_case ) return parser.parse_args() if __name__ == "__main__": UpperCAmelCase = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
88
"""simple docstring""" import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> None: warnings.warn( """The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ImageGPTImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE)
88
1
"""simple docstring""" import unittest import numpy as np from transformers import RobertaConfig, 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(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class lowercase__ ( unittest.TestCase ): 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=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=4 , ) -> str: _lowerCamelCase : str = parent _lowerCamelCase : Any = batch_size _lowerCamelCase : List[str] = seq_length _lowerCamelCase : Union[str, Any] = is_training _lowerCamelCase : Any = use_attention_mask _lowerCamelCase : Optional[int] = use_token_type_ids _lowerCamelCase : Any = use_labels _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Dict = hidden_size _lowerCamelCase : int = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : Optional[Any] = intermediate_size _lowerCamelCase : Any = hidden_act _lowerCamelCase : Optional[int] = hidden_dropout_prob _lowerCamelCase : int = attention_probs_dropout_prob _lowerCamelCase : List[str] = max_position_embeddings _lowerCamelCase : List[Any] = type_vocab_size _lowerCamelCase : Any = type_sequence_label_size _lowerCamelCase : Dict = initializer_range _lowerCamelCase : List[str] = num_choices def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _lowerCamelCase : Dict = None if self.use_attention_mask: _lowerCamelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : int = None if self.use_token_type_ids: _lowerCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) _lowerCamelCase : List[str] = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = self.prepare_config_and_inputs() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = config_and_inputs _lowerCamelCase : List[str] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : str = config_and_inputs _lowerCamelCase : List[str] = True _lowerCamelCase : Tuple = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) _lowerCamelCase : Tuple = 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 class lowercase__ ( A_ ,unittest.TestCase ): __UpperCAmelCase = True __UpperCAmelCase = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Tuple = FlaxRobertaModelTester(self) @slow def UpperCamelCase_ ( self) -> Dict: for model_class_name in self.all_model_classes: _lowerCamelCase : Any = model_class_name.from_pretrained("""roberta-base""" , from_pt=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE)
88
"""simple docstring""" from math import isqrt, loga def _snake_case ( __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __snake_case , __snake_case ): _lowerCamelCase : Optional[int] = False return [i for i in range(2 , __snake_case ) if is_prime[i]] def _snake_case ( __snake_case : int = 800800 , __snake_case : int = 800800 ): """simple docstring""" _lowerCamelCase : Union[str, Any] = degree * loga(__snake_case ) _lowerCamelCase : Union[str, Any] = int(__snake_case ) _lowerCamelCase : Dict = calculate_prime_numbers(__snake_case ) _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : Any = 0 _lowerCamelCase : Any = len(__snake_case ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f'''{solution() = }''')
88
1
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = HfArgumentParser(__snake_case ) _lowerCamelCase : int = parser.parse_args_into_dataclasses()[0] _lowerCamelCase : Dict = TensorFlowBenchmark(args=__snake_case ) try: _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: _lowerCamelCase : Union[str, Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" _lowerCamelCase : List[str] = """ """.join(str(__snake_case ).split(""" """ )[:-1] ) _lowerCamelCase : Dict = """""" _lowerCamelCase : List[Any] = eval(str(__snake_case ).split(""" """ )[-1] ) _lowerCamelCase : Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _lowerCamelCase : Tuple = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
88
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionSAGPipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: torch.manual_seed(0) _lowerCamelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0) _lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : List[Any] = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> List[Any]: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""") _lowerCamelCase : Union[str, Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = """.""" _lowerCamelCase : int = torch.manual_seed(0) _lowerCamelCase : Tuple = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Dict = output.images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Optional[Any] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Dict = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = """.""" _lowerCamelCase : List[str] = torch.manual_seed(0) _lowerCamelCase : int = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Any = output.images _lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Optional[Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """.""" _lowerCamelCase : Union[str, Any] = torch.manual_seed(0) _lowerCamelCase : Optional[int] = sag_pipe( [prompt] , width=768 , height=512 , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) _lowerCamelCase : Union[str, Any] = output.images assert image.shape == (1, 512, 768, 3)
88
1
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file UpperCAmelCase = """Run commands across TPU VMs for initial setup before running `accelerate launch`.""" def _snake_case ( __snake_case : Tuple=None ): """simple docstring""" if subparsers is not None: _lowerCamelCase : str = subparsers.add_parser("""tpu-config""" , description=_description ) else: _lowerCamelCase : Union[str, Any] = argparse.ArgumentParser("""Accelerate tpu-config command""" , description=_description ) # Core arguments _lowerCamelCase : Optional[int] = parser.add_argument_group( """Config Arguments""" , """Arguments that can be configured through `accelerate config`.""" ) config_args.add_argument( """--config_file""" , type=__snake_case , default=__snake_case , help="""Path to the config file to use for accelerate.""" , ) config_args.add_argument( """--tpu_name""" , default=__snake_case , help="""The name of the TPU to use. If not specified, will use the TPU specified in the config file.""" , ) config_args.add_argument( """--tpu_zone""" , default=__snake_case , help="""The zone of the TPU to use. If not specified, will use the zone specified in the config file.""" , ) _lowerCamelCase : List[Any] = parser.add_argument_group("""TPU Arguments""" , """Arguments for options ran inside the TPU.""" ) pod_args.add_argument( """--use_alpha""" , action="""store_true""" , help="""Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.""" , ) pod_args.add_argument( """--command_file""" , default=__snake_case , help="""The path to the file containing the commands to run on the pod on startup.""" , ) pod_args.add_argument( """--command""" , action="""append""" , nargs="""+""" , help="""A command to run on the pod. Can be passed multiple times.""" , ) pod_args.add_argument( """--install_accelerate""" , action="""store_true""" , help="""Whether to install accelerate on the pod. Defaults to False.""" , ) pod_args.add_argument( """--accelerate_version""" , default="""latest""" , help="""The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub.""" , ) pod_args.add_argument( """--debug""" , action="""store_true""" , help="""If set, will print the command that would be run instead of running it.""" ) if subparsers is not None: parser.set_defaults(func=__snake_case ) return parser def _snake_case ( __snake_case : int ): """simple docstring""" _lowerCamelCase : str = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(__snake_case ): _lowerCamelCase : Optional[int] = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: _lowerCamelCase : Dict = defaults.command_file if not args.command and defaults.commands is not None: _lowerCamelCase : List[Any] = defaults.commands if not args.tpu_name: _lowerCamelCase : Optional[Any] = defaults.tpu_name if not args.tpu_zone: _lowerCamelCase : Optional[Any] = defaults.tpu_zone if args.accelerate_version == "dev": _lowerCamelCase : Optional[int] = """git+https://github.com/huggingface/accelerate.git""" elif args.accelerate_version == "latest": _lowerCamelCase : Dict = """accelerate -U""" elif isinstance(parse(args.accelerate_version ) , __snake_case ): _lowerCamelCase : Any = F'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError("""You must specify either a command file or a command to run on the pod.""" ) if args.command_file: with open(args.command_file , """r""" ) as f: _lowerCamelCase : Dict = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , __snake_case ): _lowerCamelCase : Tuple = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate _lowerCamelCase : Optional[int] = ["""cd /usr/share"""] if args.install_accelerate: new_cmd += [F'pip install {args.accelerate_version}'] new_cmd += args.command _lowerCamelCase : List[str] = """; """.join(__snake_case ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess _lowerCamelCase : Dict = ["""gcloud"""] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'Running {" ".join(__snake_case )}' ) return subprocess.run(__snake_case ) print("""Successfully setup pod.""" ) def _snake_case ( ): """simple docstring""" _lowerCamelCase : Optional[int] = tpu_command_parser() _lowerCamelCase : Optional[Any] = parser.parse_args() tpu_command_launcher(__snake_case )
88
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=64 , ) -> Optional[int]: _lowerCamelCase : List[str] = parent _lowerCamelCase : List[Any] = batch_size _lowerCamelCase : Tuple = is_training _lowerCamelCase : Tuple = use_auxiliary_loss _lowerCamelCase : Any = num_queries _lowerCamelCase : List[str] = num_channels _lowerCamelCase : List[str] = min_size _lowerCamelCase : Tuple = max_size _lowerCamelCase : str = num_labels _lowerCamelCase : Any = hidden_dim _lowerCamelCase : Dict = hidden_dim def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) > 0.5 ).float() _lowerCamelCase : Dict = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE) > 0.5).long() _lowerCamelCase : Optional[int] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCamelCase_ ( self) -> str: _lowerCamelCase : List[str] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _lowerCamelCase : Any = self.num_queries _lowerCamelCase : int = self.num_labels _lowerCamelCase : int = [1, 1, 1, 1] _lowerCamelCase : Any = self.num_channels _lowerCamelCase : Optional[Any] = 64 _lowerCamelCase : str = 128 _lowerCamelCase : Optional[Any] = self.hidden_dim _lowerCamelCase : Any = self.hidden_dim _lowerCamelCase : List[Any] = self.hidden_dim return config def UpperCamelCase_ ( self) -> Any: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = self.prepare_config_and_inputs() _lowerCamelCase : str = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : str = output.encoder_hidden_states _lowerCamelCase : int = output.pixel_decoder_hidden_states _lowerCamelCase : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , config.decoder_layers) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False) -> List[str]: with torch.no_grad(): _lowerCamelCase : Optional[int] = MaskaFormerModel(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[int] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = model(SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(output.encoder_last_hidden_state is not None) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : str = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(result.encoder_last_hidden_state is not None) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1)) with torch.no_grad(): _lowerCamelCase : List[Any] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model( pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape , torch.Size([1])) @require_torch class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = MaskaFormerModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> int: _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""") def UpperCamelCase_ ( self) -> Optional[int]: pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""") def UpperCamelCase_ ( self) -> Tuple: pass @unittest.skip(reason="""Mask2Former is not a generative model""") def UpperCamelCase_ ( self) -> List[Any]: pass @unittest.skip(reason="""Mask2Former does not use token embeddings""") def UpperCamelCase_ ( self) -> Any: pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""") def UpperCamelCase_ ( self) -> Dict: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""") def UpperCamelCase_ ( self) -> Optional[int]: pass def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : str = [*signature.parameters.keys()] _lowerCamelCase : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> Optional[int]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _lowerCamelCase : Optional[int] = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Dict = (self.model_tester.min_size,) * 2 _lowerCamelCase : str = { """pixel_values""": torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE), """mask_labels""": torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE), """class_labels""": torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE).long(), } _lowerCamelCase : List[str] = self.model_tester.get_config() _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE , output_attentions=SCREAMING_SNAKE_CASE) self.assertTrue(outputs.attentions is not None) def UpperCamelCase_ ( self) -> Optional[Any]: if not self.model_tester.is_training: return _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE).loss loss.backward() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : int = True _lowerCamelCase : Optional[Any] = True _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _lowerCamelCase : int = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _lowerCamelCase : str = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _lowerCamelCase : Optional[int] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(pixel_decoder_hidden_states.grad) self.assertIsNotNone(transformer_decoder_hidden_states.grad) self.assertIsNotNone(attentions.grad) UpperCAmelCase = 1e-4 def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def UpperCamelCase_ ( self) -> Union[str, Any]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Tuple = MaskaFormerModel.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : List[str] = prepare_img() _lowerCamelCase : Union[str, Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Any = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Dict = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : Optional[Any] = self.default_image_processor _lowerCamelCase : Any = prepare_img() _lowerCamelCase : Dict = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : List[str] = model(**SCREAMING_SNAKE_CASE) # masks_queries_logits _lowerCamelCase : str = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)) _lowerCamelCase : Any = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] _lowerCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) # class_queries_logits _lowerCamelCase : List[str] = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1)) _lowerCamelCase : Optional[Any] = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ]).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : Tuple = image_processor( [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors="""pt""" , ) _lowerCamelCase : Optional[Any] = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""mask_labels"""]] _lowerCamelCase : Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""class_labels"""]] with torch.no_grad(): _lowerCamelCase : Any = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None)
88
1
"""simple docstring""" from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _snake_case ( __snake_case : List[str] ): """simple docstring""" return getitem, k def _snake_case ( __snake_case : List[Any] , __snake_case : int ): """simple docstring""" return setitem, k, v def _snake_case ( __snake_case : str ): """simple docstring""" return delitem, k def _snake_case ( __snake_case : int , __snake_case : Optional[Any] , *__snake_case : Any ): """simple docstring""" try: return fun(__snake_case , *__snake_case ), None except Exception as e: return None, e UpperCAmelCase = ( _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), ) UpperCAmelCase = [ _set("""key_a""", """val_a"""), _set("""key_a""", """val_b"""), ] UpperCAmelCase = [ _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), _del("""key_a"""), _del("""key_b"""), _set("""key_a""", """val_a"""), _del("""key_a"""), ] UpperCAmelCase = [ _get("""key_a"""), _del("""key_a"""), _set("""key_a""", """val_a"""), _del("""key_a"""), _del("""key_a"""), _get("""key_a"""), ] UpperCAmelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] UpperCAmelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set("""key_a""", """val_b"""), ] @pytest.mark.parametrize( """operations""" , ( pytest.param(_add_items , id="""add items""" ), pytest.param(_overwrite_items , id="""overwrite items""" ), pytest.param(_delete_items , id="""delete items""" ), pytest.param(_access_absent_items , id="""access absent items""" ), pytest.param(_add_with_resize_up , id="""add with resize up""" ), pytest.param(_add_with_resize_down , id="""add with resize down""" ), ) , ) def _snake_case ( __snake_case : Any ): """simple docstring""" _lowerCamelCase : str = HashMap(initial_block_size=4 ) _lowerCamelCase : List[Any] = {} for _, (fun, *args) in enumerate(__snake_case ): _lowerCamelCase , _lowerCamelCase : List[str] = _run_operation(__snake_case , __snake_case , *__snake_case ) _lowerCamelCase , _lowerCamelCase : Dict = _run_operation(__snake_case , __snake_case , *__snake_case ) assert my_res == py_res assert str(__snake_case ) == str(__snake_case ) assert set(__snake_case ) == set(__snake_case ) assert len(__snake_case ) == len(__snake_case ) assert set(my.items() ) == set(py.items() ) def _snake_case ( ): """simple docstring""" def is_public(__snake_case : str ) -> bool: return not name.startswith("""_""" ) _lowerCamelCase : Any = {name for name in dir({} ) if is_public(__snake_case )} _lowerCamelCase : Tuple = {name for name in dir(HashMap() ) if is_public(__snake_case )} assert dict_public_names > hash_public_names
88
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) UpperCAmelCase = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) UpperCAmelCase = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) UpperCAmelCase = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModel) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
88
1
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def _snake_case ( __snake_case : List[str] ): """simple docstring""" for param in module.parameters(): _lowerCamelCase : Optional[Any] = False def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _lowerCamelCase : Any = """mps""" if device == "mps": print( """WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch""" """ errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues""" """ with generations.""" ) return device def _snake_case ( __snake_case : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = plt.imshow(__snake_case ) fig.axes.get_xaxis().set_visible(__snake_case ) fig.axes.get_yaxis().set_visible(__snake_case ) plt.show() def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = datetime.now() _lowerCamelCase : Optional[Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
88
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
88
1
"""simple docstring""" import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class lowercase__ : @staticmethod def UpperCamelCase_ ( *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> Union[str, Any]: pass def _snake_case ( __snake_case : Image ): """simple docstring""" _lowerCamelCase : List[str] = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class lowercase__ ( unittest.TestCase ): __UpperCAmelCase = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[Any]: _lowerCamelCase : int = DepthEstimationPipeline(model=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Tuple = depth_estimator("""./tests/fixtures/tests_samples/COCO/000000039769.png""") self.assertEqual({"""predicted_depth""": ANY(torch.Tensor), """depth""": ANY(Image.Image)} , SCREAMING_SNAKE_CASE) import datasets _lowerCamelCase : str = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""") _lowerCamelCase : int = depth_estimator( [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ]) self.assertEqual( [ {"""predicted_depth""": ANY(torch.Tensor), """depth""": ANY(Image.Image)}, {"""predicted_depth""": ANY(torch.Tensor), """depth""": ANY(Image.Image)}, {"""predicted_depth""": ANY(torch.Tensor), """depth""": ANY(Image.Image)}, {"""predicted_depth""": ANY(torch.Tensor), """depth""": ANY(Image.Image)}, {"""predicted_depth""": ANY(torch.Tensor), """depth""": ANY(Image.Image)}, ] , SCREAMING_SNAKE_CASE , ) @require_tf @unittest.skip("""Depth estimation is not implemented in TF""") def UpperCamelCase_ ( self) -> Optional[Any]: pass @slow @require_torch def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Dict = """Intel/dpt-large""" _lowerCamelCase : str = pipeline("""depth-estimation""" , model=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = depth_estimator("""http://images.cocodataset.org/val2017/000000039769.jpg""") _lowerCamelCase : Any = hashimage(outputs["""depth"""]) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs["""predicted_depth"""].max().item()) , 29.3_04) self.assertEqual(nested_simplify(outputs["""predicted_depth"""].min().item()) , 2.6_62) @require_torch def UpperCamelCase_ ( self) -> List[Any]: # This is highly irregular to have no small tests. self.skipTest("""There is not hf-internal-testing tiny model for either GLPN nor DPT""")
88
"""simple docstring""" def _snake_case ( __snake_case : list[list[int]] , __snake_case : int , __snake_case : int , __snake_case : list[int] ): """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def _snake_case ( __snake_case : list[list[int]] , __snake_case : list[int] , __snake_case : int ): """simple docstring""" if curr_ind == len(__snake_case ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(__snake_case ) ): if valid_connection(__snake_case , __snake_case , __snake_case , __snake_case ): # Insert current vertex into path as next transition _lowerCamelCase : List[str] = next_ver # Validate created path if util_hamilton_cycle(__snake_case , __snake_case , curr_ind + 1 ): return True # Backtrack _lowerCamelCase : Tuple = -1 return False def _snake_case ( __snake_case : list[list[int]] , __snake_case : int = 0 ): """simple docstring""" _lowerCamelCase : Any = [-1] * (len(__snake_case ) + 1) # initialize start and end of path with starting index _lowerCamelCase : Optional[int] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__snake_case , __snake_case , 1 ) else []
88
1
"""simple docstring""" from jiwer import compute_measures import datasets UpperCAmelCase = """\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } """ UpperCAmelCase = """\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. """ UpperCAmelCase = """ Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = [\"this is the prediction\", \"there is an other sample\"] >>> references = [\"this is the reference\", \"there is another one\"] >>> wer = datasets.load_metric(\"wer\") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> Optional[int]: 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"""), }) , codebase_urls=["""https://github.com/jitsi/jiwer/"""] , reference_urls=[ """https://en.wikipedia.org/wiki/Word_error_rate""", ] , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=False) -> Union[str, Any]: if concatenate_texts: return compute_measures(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)["wer"] else: _lowerCamelCase : List[str] = 0 _lowerCamelCase : List[Any] = 0 for prediction, reference in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : Union[str, Any] = compute_measures(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
88
"""simple docstring""" import mpmath # for roots of unity import numpy as np class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None) -> Tuple: # Input as list _lowerCamelCase : Any = list(poly_a or [0])[:] _lowerCamelCase : Optional[Any] = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _lowerCamelCase : int = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() _lowerCamelCase : Union[str, Any] = len(self.polyB) # Add 0 to make lengths equal a power of 2 _lowerCamelCase : List[Any] = int( 2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1))) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform _lowerCamelCase : Optional[Any] = complex(mpmath.root(x=1 , n=self.c_max_length , k=1)) # The product _lowerCamelCase : int = self.__multiply() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Dict = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE) <= 1: return dft[0] # _lowerCamelCase : str = self.c_max_length // 2 while next_ncol > 0: _lowerCamelCase : Dict = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : Tuple = self.root**next_ncol # First half of next step _lowerCamelCase : int = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step _lowerCamelCase : Optional[int] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update _lowerCamelCase : Union[str, Any] = new_dft _lowerCamelCase : List[str] = next_ncol // 2 return dft[0] def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[Any] = self.__dft("""A""") _lowerCamelCase : List[str] = self.__dft("""B""") _lowerCamelCase : List[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT _lowerCamelCase : List[str] = 2 while next_ncol <= self.c_max_length: _lowerCamelCase : Any = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : List[Any] = self.root ** (next_ncol // 2) _lowerCamelCase : str = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root)) current_root *= root # Update _lowerCamelCase : Any = new_inverse_c next_ncol *= 2 # Unpack _lowerCamelCase : Optional[Any] = [round(x[0].real , 8) + round(x[0].imag , 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self) -> Any: _lowerCamelCase : Dict = """A = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A])) _lowerCamelCase : List[Any] = """B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B])) _lowerCamelCase : int = """A*B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.product)) return F'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" import argparse import json import os import torch from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _snake_case ( __snake_case : Dict , __snake_case : List[str] , __snake_case : List[Any] , __snake_case : int , __snake_case : Union[str, Any] ): """simple docstring""" with open(__snake_case ) as metadata_file: _lowerCamelCase : Optional[int] = json.load(__snake_case ) _lowerCamelCase : Any = LukeConfig(use_entity_aware_attention=__snake_case , **metadata["""model_config"""] ) # Load in the weights from the checkpoint_path _lowerCamelCase : List[Any] = torch.load(__snake_case , map_location="""cpu""" ) # Load the entity vocab file _lowerCamelCase : List[Any] = load_entity_vocab(__snake_case ) _lowerCamelCase : int = RobertaTokenizer.from_pretrained(metadata["""model_config"""]["""bert_model_name"""] ) # Add special tokens to the token vocabulary for downstream tasks _lowerCamelCase : int = AddedToken("""<ent>""" , lstrip=__snake_case , rstrip=__snake_case ) _lowerCamelCase : Optional[Any] = AddedToken("""<ent2>""" , lstrip=__snake_case , rstrip=__snake_case ) tokenizer.add_special_tokens({"""additional_special_tokens""": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'Saving tokenizer to {pytorch_dump_folder_path}' ) tokenizer.save_pretrained(__snake_case ) with open(os.path.join(__snake_case , LukeTokenizer.vocab_files_names["""entity_vocab_file"""] ) , """w""" ) as f: json.dump(__snake_case , __snake_case ) _lowerCamelCase : Optional[Any] = LukeTokenizer.from_pretrained(__snake_case ) # Initialize the embeddings of the special tokens _lowerCamelCase : str = state_dict["""embeddings.word_embeddings.weight"""] _lowerCamelCase : Union[str, Any] = word_emb[tokenizer.convert_tokens_to_ids(["""@"""] )[0]].unsqueeze(0 ) _lowerCamelCase : Tuple = word_emb[tokenizer.convert_tokens_to_ids(["""#"""] )[0]].unsqueeze(0 ) _lowerCamelCase : Dict = torch.cat([word_emb, ent_emb, enta_emb] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: _lowerCamelCase : Optional[int] = F'encoder.layer.{layer_index}.attention.self.' _lowerCamelCase : Any = state_dict[prefix + matrix_name] _lowerCamelCase : List[Any] = state_dict[prefix + matrix_name] _lowerCamelCase : Optional[int] = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks _lowerCamelCase : Dict = state_dict["""entity_embeddings.entity_embeddings.weight"""] _lowerCamelCase : Tuple = entity_emb[entity_vocab["""[MASK]"""]] _lowerCamelCase : List[str] = LukeModel(config=__snake_case ).eval() _lowerCamelCase , _lowerCamelCase : List[Any] = model.load_state_dict(__snake_case , strict=__snake_case ) if not (len(__snake_case ) == 1 and missing_keys[0] == "embeddings.position_ids"): raise ValueError(F'Missing keys {", ".join(__snake_case )}. Expected only missing embeddings.position_ids' ) if not (all(key.startswith("""entity_predictions""" ) or key.startswith("""lm_head""" ) for key in unexpected_keys )): raise ValueError( """Unexpected keys""" F' {", ".join([key for key in unexpected_keys if not (key.startswith("entity_predictions" ) or key.startswith("lm_head" ))] )}' ) # Check outputs _lowerCamelCase : Any = LukeTokenizer.from_pretrained(__snake_case , task="""entity_classification""" ) _lowerCamelCase : str = ( """Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the""" """ new world number one avoid a humiliating second- round exit at Wimbledon .""" ) _lowerCamelCase : Optional[Any] = (39, 42) _lowerCamelCase : str = tokenizer(__snake_case , entity_spans=[span] , add_prefix_space=__snake_case , return_tensors="""pt""" ) _lowerCamelCase : Optional[int] = model(**__snake_case ) # Verify word hidden states if model_size == "large": _lowerCamelCase : int = torch.Size((1, 42, 1024) ) _lowerCamelCase : Union[str, Any] = torch.tensor( [[0.0133, 0.0865, 0.0095], [0.3093, -0.2576, -0.7418], [-0.1720, -0.2117, -0.2869]] ) else: # base _lowerCamelCase : Union[str, Any] = torch.Size((1, 42, 768) ) _lowerCamelCase : str = torch.tensor([[0.0037, 0.1368, -0.0091], [0.1099, 0.3329, -0.1095], [0.0765, 0.5335, 0.1179]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , __snake_case , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": _lowerCamelCase : List[Any] = torch.Size((1, 1, 1024) ) _lowerCamelCase : int = torch.tensor([[0.0466, -0.0106, -0.0179]] ) else: # base _lowerCamelCase : Union[str, Any] = torch.Size((1, 1, 768) ) _lowerCamelCase : Union[str, Any] = torch.tensor([[0.1457, 0.1044, 0.0174]] ) if not (outputs.entity_last_hidden_state.shape != expected_shape): raise ValueError( F'Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is' F' {expected_shape}' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , __snake_case , atol=1E-4 ): raise ValueError # Finally, save our PyTorch model and tokenizer print("""Saving PyTorch model to {}""".format(__snake_case ) ) model.save_pretrained(__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" _lowerCamelCase : Dict = {} with open(__snake_case , """r""" , encoding="""utf-8""" ) as f: for index, line in enumerate(__snake_case ): _lowerCamelCase , _lowerCamelCase : Optional[Any] = line.rstrip().split("""\t""" ) _lowerCamelCase : Any = index return entity_vocab if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument("""--checkpoint_path""", type=str, help="""Path to a pytorch_model.bin file.""") parser.add_argument( """--metadata_path""", default=None, type=str, help="""Path to a metadata.json file, defining the configuration.""" ) parser.add_argument( """--entity_vocab_path""", default=None, type=str, help="""Path to an entity_vocab.tsv file, containing the entity vocabulary.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to where to dump the output PyTorch model.""" ) parser.add_argument( """--model_size""", default="""base""", type=str, choices=["""base""", """large"""], help="""Size of the model to be converted.""" ) UpperCAmelCase = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
88
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase = { """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""VisionEncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""TFVisionEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""FlaxVisionEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
1
"""simple docstring""" # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class lowercase__ ( A_ ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Any: super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE) @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]: _lowerCamelCase : Union[str, Any] = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=SCREAMING_SNAKE_CASE , ) _lowerCamelCase : Any = image.to(self.device) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE) for t in self.progress_bar(self.scheduler.timesteps): # 1. predict noise model_output _lowerCamelCase : Any = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).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 _lowerCamelCase : List[Any] = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).prev_sample _lowerCamelCase : List[str] = (image / 2 + 0.5).clamp(0 , 1) _lowerCamelCase : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": _lowerCamelCase : List[str] = self.numpy_to_pil(SCREAMING_SNAKE_CASE) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE), "This is a local test"
88
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def _snake_case ( __snake_case : List[str] ): """simple docstring""" for param in module.parameters(): _lowerCamelCase : Optional[Any] = False def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _lowerCamelCase : Any = """mps""" if device == "mps": print( """WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch""" """ errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues""" """ with generations.""" ) return device def _snake_case ( __snake_case : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = plt.imshow(__snake_case ) fig.axes.get_xaxis().set_visible(__snake_case ) fig.axes.get_yaxis().set_visible(__snake_case ) plt.show() def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = datetime.now() _lowerCamelCase : Optional[Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
88
1
"""simple docstring""" from __future__ import annotations def _snake_case ( __snake_case : str , __snake_case : list[str] | None = None ): """simple docstring""" _lowerCamelCase : List[str] = word_bank or [] # create a table _lowerCamelCase : int = len(__snake_case ) + 1 _lowerCamelCase : list[list[list[str]]] = [] for _ in range(__snake_case ): table.append([] ) # seed value _lowerCamelCase : List[Any] = [[]] # because empty string has empty combination # iterate through the indices for i in range(__snake_case ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(__snake_case )] == word: _lowerCamelCase : list[list[str]] = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(__snake_case )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(__snake_case )]: combination.reverse() return table[len(__snake_case )] if __name__ == "__main__": print(all_construct("""jwajalapa""", ["""jwa""", """j""", """w""", """a""", """la""", """lapa"""])) print(all_construct("""rajamati""", ["""s""", """raj""", """amat""", """raja""", """ma""", """i""", """t"""])) print( all_construct( """hexagonosaurus""", ["""h""", """ex""", """hex""", """ag""", """ago""", """ru""", """auru""", """rus""", """go""", """no""", """o""", """s"""], ) )
88
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCAmelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""") @dataclass class lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_mae""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. _lowerCamelCase : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = split["""test"""] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _lowerCamelCase : str = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = ViTMAEConfig() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) # adapt config config.update( { """mask_ratio""": model_args.mask_ratio, """norm_pix_loss""": model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
1
"""simple docstring""" from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase__ ( A_ ): __UpperCAmelCase = ['''image_processor''', '''tokenizer'''] __UpperCAmelCase = '''Pix2StructImageProcessor''' __UpperCAmelCase = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[Any]: _lowerCamelCase : Union[str, Any] = False super().__init__(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def __call__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 2048 , SCREAMING_SNAKE_CASE = 0 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> BatchEncoding: if images is None and text is None: raise ValueError("""You have to specify either images or text.""") # Get only text if images is None and not self.image_processor.is_vqa: _lowerCamelCase : List[Any] = self.tokenizer _lowerCamelCase : Any = self.tokenizer( text=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , stride=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , return_overflowing_tokens=SCREAMING_SNAKE_CASE , return_special_tokens_mask=SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , return_token_type_ids=SCREAMING_SNAKE_CASE , return_length=SCREAMING_SNAKE_CASE , verbose=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values _lowerCamelCase : Any = self.image_processor( SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , max_patches=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) else: # add pixel_values and bbox _lowerCamelCase : Union[str, Any] = self.image_processor( SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , max_patches=SCREAMING_SNAKE_CASE , header_text=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) if text is not None and not self.image_processor.is_vqa: _lowerCamelCase : Tuple = self.tokenizer( text=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , stride=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , return_overflowing_tokens=SCREAMING_SNAKE_CASE , return_special_tokens_mask=SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , return_token_type_ids=SCREAMING_SNAKE_CASE , return_length=SCREAMING_SNAKE_CASE , verbose=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) if "attention_mask" in text_encoding: _lowerCamelCase : int = text_encoding.pop("""attention_mask""") if "input_ids" in text_encoding: _lowerCamelCase : str = text_encoding.pop("""input_ids""") else: _lowerCamelCase : List[str] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE) return encoding_image_processor def UpperCamelCase_ ( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> int: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> int: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) @property def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : Any = self.tokenizer.model_input_names _lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
88
"""simple docstring""" import numpy as np def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return vector * sigmoid(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class lowercase__ ( unittest.TestCase ): __UpperCAmelCase = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __UpperCAmelCase = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Union[str, Any]: _lowerCamelCase : Tuple = TextaTextGenerationPipeline(model=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE) return generator, ["Something to write", "Something else"] def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : str = generator("""Something there""") self.assertEqual(SCREAMING_SNAKE_CASE , [{"""generated_text""": ANY(SCREAMING_SNAKE_CASE)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["""generated_text"""].startswith("""Something there""")) _lowerCamelCase : Dict = generator(["""This is great !""", """Something else"""] , num_return_sequences=2 , do_sample=SCREAMING_SNAKE_CASE) self.assertEqual( SCREAMING_SNAKE_CASE , [ [{"""generated_text""": ANY(SCREAMING_SNAKE_CASE)}, {"""generated_text""": ANY(SCREAMING_SNAKE_CASE)}], [{"""generated_text""": ANY(SCREAMING_SNAKE_CASE)}, {"""generated_text""": ANY(SCREAMING_SNAKE_CASE)}], ] , ) _lowerCamelCase : int = generator( ["""This is great !""", """Something else"""] , num_return_sequences=2 , batch_size=2 , do_sample=SCREAMING_SNAKE_CASE) self.assertEqual( SCREAMING_SNAKE_CASE , [ [{"""generated_text""": ANY(SCREAMING_SNAKE_CASE)}, {"""generated_text""": ANY(SCREAMING_SNAKE_CASE)}], [{"""generated_text""": ANY(SCREAMING_SNAKE_CASE)}, {"""generated_text""": ANY(SCREAMING_SNAKE_CASE)}], ] , ) with self.assertRaises(SCREAMING_SNAKE_CASE): generator(4) @require_torch def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Union[str, Any] = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""pt""") # do_sample=False necessary for reproducibility _lowerCamelCase : Union[str, Any] = generator("""Something there""" , do_sample=SCREAMING_SNAKE_CASE) self.assertEqual(SCREAMING_SNAKE_CASE , [{"""generated_text""": """"""}]) _lowerCamelCase : Dict = 3 _lowerCamelCase : List[str] = generator( """Something there""" , num_return_sequences=SCREAMING_SNAKE_CASE , num_beams=SCREAMING_SNAKE_CASE , ) _lowerCamelCase : Tuple = [ {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide"""}, {"""generated_text""": """"""}, ] self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = generator("""This is a test""" , do_sample=SCREAMING_SNAKE_CASE , num_return_sequences=2 , return_tensors=SCREAMING_SNAKE_CASE) self.assertEqual( SCREAMING_SNAKE_CASE , [ {"""generated_token_ids""": ANY(torch.Tensor)}, {"""generated_token_ids""": ANY(torch.Tensor)}, ] , ) _lowerCamelCase : Union[str, Any] = generator.model.config.eos_token_id _lowerCamelCase : List[Any] = """<pad>""" _lowerCamelCase : str = generator( ["""This is a test""", """This is a second test"""] , do_sample=SCREAMING_SNAKE_CASE , num_return_sequences=2 , batch_size=2 , return_tensors=SCREAMING_SNAKE_CASE , ) self.assertEqual( SCREAMING_SNAKE_CASE , [ [ {"""generated_token_ids""": ANY(torch.Tensor)}, {"""generated_token_ids""": ANY(torch.Tensor)}, ], [ {"""generated_token_ids""": ANY(torch.Tensor)}, {"""generated_token_ids""": ANY(torch.Tensor)}, ], ] , ) @require_tf def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = pipeline("""text2text-generation""" , model="""patrickvonplaten/t5-tiny-random""" , framework="""tf""") # do_sample=False necessary for reproducibility _lowerCamelCase : List[Any] = generator("""Something there""" , do_sample=SCREAMING_SNAKE_CASE) self.assertEqual(SCREAMING_SNAKE_CASE , [{"""generated_text""": """"""}])
88
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = HfArgumentParser(__snake_case ) _lowerCamelCase : int = parser.parse_args_into_dataclasses()[0] _lowerCamelCase : Dict = TensorFlowBenchmark(args=__snake_case ) try: _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: _lowerCamelCase : Union[str, Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" _lowerCamelCase : List[str] = """ """.join(str(__snake_case ).split(""" """ )[:-1] ) _lowerCamelCase : Dict = """""" _lowerCamelCase : List[Any] = eval(str(__snake_case ).split(""" """ )[-1] ) _lowerCamelCase : Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _lowerCamelCase : Tuple = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
88
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase = {"""configuration_focalnet""": ["""FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FocalNetConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ """FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """FocalNetForImageClassification""", """FocalNetForMaskedImageModeling""", """FocalNetBackbone""", """FocalNetModel""", """FocalNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""", """kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""", """kssteven/ibert-roberta-large-mnli""": ( """https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''ibert''' def __init__( self , SCREAMING_SNAKE_CASE=3_0522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="none" , **SCREAMING_SNAKE_CASE , ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Dict = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Dict = type_vocab_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : Any = quant_mode _lowerCamelCase : List[str] = force_dequant class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
1
"""simple docstring""" def _snake_case ( __snake_case : int = 10**9 ): """simple docstring""" _lowerCamelCase : Any = 1 _lowerCamelCase : int = 2 _lowerCamelCase : Tuple = 0 _lowerCamelCase : Any = 0 _lowerCamelCase : Optional[int] = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value _lowerCamelCase : str = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(f'''{solution() = }''')
88
"""simple docstring""" from __future__ import annotations import queue class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : int = data _lowerCamelCase : List[str] = None _lowerCamelCase : Any = None def _snake_case ( ): """simple docstring""" print("""\n********Press N to stop entering at any point of time********\n""" ) _lowerCamelCase : Optional[int] = input("""Enter the value of the root node: """ ).strip().lower() _lowerCamelCase : queue.Queue = queue.Queue() _lowerCamelCase : Optional[int] = TreeNode(int(__snake_case ) ) q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Tuple = q.get() _lowerCamelCase : Any = F'Enter the left node of {node_found.data}: ' _lowerCamelCase : Union[str, Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : Dict = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[str] = left_node q.put(__snake_case ) _lowerCamelCase : Optional[int] = F'Enter the right node of {node_found.data}: ' _lowerCamelCase : Optional[Any] = input(__snake_case ).strip().lower() or """n""" if check == "n": return tree_node _lowerCamelCase : List[Any] = TreeNode(int(__snake_case ) ) _lowerCamelCase : List[Any] = right_node q.put(__snake_case ) raise def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Any = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : queue.Queue = queue.Queue() q.put(__snake_case ) while not q.empty(): _lowerCamelCase : Optional[Any] = [] while not q.empty(): _lowerCamelCase : Dict = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__snake_case ) def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : Optional[int] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__snake_case ) _lowerCamelCase : Tuple = n.left # end of while means current node doesn't have left child _lowerCamelCase : Optional[Any] = stack.pop() # start to traverse its right child _lowerCamelCase : Dict = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase : list[TreeNode] = [] _lowerCamelCase : int = node while n or stack: while n: stack.append(__snake_case ) _lowerCamelCase : Any = n.left _lowerCamelCase : Optional[Any] = stack.pop() print(n.data , end=""",""" ) _lowerCamelCase : List[Any] = n.right def _snake_case ( __snake_case : TreeNode ): """simple docstring""" if not isinstance(__snake_case , __snake_case ) or not node: return _lowerCamelCase , _lowerCamelCase : Union[str, Any] = [], [] _lowerCamelCase : Optional[Any] = node stacka.append(__snake_case ) while stacka: # to find the reversed order of post order, store it in stack2 _lowerCamelCase : Union[str, Any] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__snake_case ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def _snake_case ( __snake_case : str = "" , __snake_case : Any=50 , __snake_case : List[str]="*" ): """simple docstring""" if not s: return "\n" + width * char _lowerCamelCase , _lowerCamelCase : Optional[int] = divmod(width - len(__snake_case ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
88
1
"""simple docstring""" from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): __UpperCAmelCase = ['''pixel_values'''] def __init__( self , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = 1 / 255 , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = 8 , **SCREAMING_SNAKE_CASE , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = do_rescale _lowerCamelCase : Optional[Any] = rescale_factor _lowerCamelCase : Any = do_pad _lowerCamelCase : Tuple = pad_size def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE) -> np.ndarray: return rescale(SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None) -> List[Any]: _lowerCamelCase , _lowerCamelCase : str = get_image_size(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = (old_height // size + 1) * size - old_height _lowerCamelCase : Any = (old_width // size + 1) * size - old_width return pad(SCREAMING_SNAKE_CASE , ((0, pad_height), (0, pad_width)) , mode="""symmetric""" , data_format=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE , ) -> Dict: _lowerCamelCase : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale _lowerCamelCase : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor _lowerCamelCase : Optional[int] = do_pad if do_pad is not None else self.do_pad _lowerCamelCase : Any = pad_size if pad_size is not None else self.pad_size _lowerCamelCase : List[str] = make_list_of_images(SCREAMING_SNAKE_CASE) if not valid_images(SCREAMING_SNAKE_CASE): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""") if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""") # All transformations expect numpy arrays. _lowerCamelCase : List[Any] = [to_numpy_array(SCREAMING_SNAKE_CASE) for image in images] if do_rescale: _lowerCamelCase : Dict = [self.rescale(image=SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE) for image in images] if do_pad: _lowerCamelCase : Optional[int] = [self.pad(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE) for image in images] _lowerCamelCase : List[Any] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) for image in images] _lowerCamelCase : Dict = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE , tensor_type=SCREAMING_SNAKE_CASE)
88
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowercase__ : __UpperCAmelCase = XGLMConfig __UpperCAmelCase = {} __UpperCAmelCase = '''gelu''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=14 , SCREAMING_SNAKE_CASE=7 , 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=0.02 , ) -> List[str]: _lowerCamelCase : Optional[int] = parent _lowerCamelCase : int = batch_size _lowerCamelCase : str = seq_length _lowerCamelCase : Any = is_training _lowerCamelCase : int = use_input_mask _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : str = vocab_size _lowerCamelCase : List[str] = d_model _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : int = ffn_dim _lowerCamelCase : str = activation_function _lowerCamelCase : Optional[int] = activation_dropout _lowerCamelCase : Tuple = attention_dropout _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Dict = initializer_range _lowerCamelCase : Optional[Any] = None _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[Any] = 2 _lowerCamelCase : str = 1 def UpperCamelCase_ ( self) -> int: return XGLMConfig.from_pretrained("""facebook/xglm-564M""") def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) , clip_value_min=0 , clip_value_max=3) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Tuple = self.get_config() _lowerCamelCase : Optional[int] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2) return ( config, input_ids, input_mask, head_mask, ) def UpperCamelCase_ ( self) -> Optional[int]: return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : str = config_and_inputs _lowerCamelCase : Optional[Any] = { """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () __UpperCAmelCase = (TFXGLMForCausalLM,) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Optional[Any] = TFXGLMModelTester(self) _lowerCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , n_embd=37) def UpperCamelCase_ ( self) -> Dict: self.config_tester.run_common_tests() @slow def UpperCamelCase_ ( self) -> List[Any]: for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""") def UpperCamelCase_ ( self) -> List[Any]: super().test_resize_token_embeddings() @require_tf class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=True) -> List[Any]: _lowerCamelCase : List[str] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Union[str, Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCamelCase : Dict = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on _lowerCamelCase : str = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: _lowerCamelCase : int = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") tf.random.set_seed(0) _lowerCamelCase : Union[str, Any] = tokenizer("""Today is a nice day and""" , return_tensors="""tf""") _lowerCamelCase : Any = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(""":/CPU:0"""): _lowerCamelCase : Any = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , seed=[7, 0]) _lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = ( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Any = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : List[Any] = """left""" # use different length sentences to test batching _lowerCamelCase : List[Any] = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""tf""" , padding=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = inputs["""input_ids"""] _lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , attention_mask=inputs["""attention_mask"""] , max_new_tokens=12) _lowerCamelCase : List[str] = tokenizer(sentences[0] , return_tensors="""tf""").input_ids _lowerCamelCase : Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Tuple = tokenizer(sentences[1] , return_tensors="""tf""").input_ids _lowerCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , [non_padded_sentence, padded_sentence])
88
1
"""simple docstring""" from collections import defaultdict def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : Tuple = first_str.lower().strip() _lowerCamelCase : int = second_str.lower().strip() # Remove whitespace _lowerCamelCase : Any = first_str.replace(""" """ , """""" ) _lowerCamelCase : List[str] = second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(__snake_case ) != len(__snake_case ): return False # Default values for count should be 0 _lowerCamelCase : defaultdict[str, int] = defaultdict(__snake_case ) # For each character in input strings, # increment count in the corresponding for i in range(len(__snake_case ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase = input("""Enter the first string """).strip() UpperCAmelCase = input("""Enter the second string """).strip() UpperCAmelCase = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
88
"""simple docstring""" from collections import defaultdict def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : Tuple = first_str.lower().strip() _lowerCamelCase : int = second_str.lower().strip() # Remove whitespace _lowerCamelCase : Any = first_str.replace(""" """ , """""" ) _lowerCamelCase : List[str] = second_str.replace(""" """ , """""" ) # Strings of different lengths are not anagrams if len(__snake_case ) != len(__snake_case ): return False # Default values for count should be 0 _lowerCamelCase : defaultdict[str, int] = defaultdict(__snake_case ) # For each character in input strings, # increment count in the corresponding for i in range(len(__snake_case ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase = input("""Enter the first string """).strip() UpperCAmelCase = input("""Enter the second string """).strip() UpperCAmelCase = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
88
1
"""simple docstring""" def _snake_case ( __snake_case : str ): """simple docstring""" _lowerCamelCase : Any = 0 # if input_string is "aba" than new_input_string become "a|b|a" _lowerCamelCase : List[Any] = """""" _lowerCamelCase : Union[str, Any] = """""" # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(__snake_case ) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring _lowerCamelCase , _lowerCamelCase : Optional[int] = 0, 0 # length[i] shows the length of palindromic substring with center i _lowerCamelCase : List[str] = [1 for i in range(len(__snake_case ) )] # for each character in new_string find corresponding palindromic string _lowerCamelCase : Optional[int] = 0 for j in range(len(__snake_case ) ): _lowerCamelCase : Dict = 1 if j > r else min(length[l + r - j] // 2 , r - j + 1 ) while ( j - k >= 0 and j + k < len(__snake_case ) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 _lowerCamelCase : Union[str, Any] = 2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: _lowerCamelCase : str = j - k + 1 # noqa: E741 _lowerCamelCase : Tuple = j + k - 1 # update max_length and start position if max_length < length[j]: _lowerCamelCase : Optional[int] = length[j] _lowerCamelCase : List[str] = j # create that string _lowerCamelCase : Optional[int] = new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod()
88
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _snake_case ( __snake_case : float , __snake_case : float , __snake_case : bool = False ): """simple docstring""" if radian_mode: return [magnitude * cos(__snake_case ), magnitude * sin(__snake_case )] return [magnitude * cos(radians(__snake_case ) ), magnitude * sin(radians(__snake_case ) )] def _snake_case ( __snake_case : NDArray[floataa] , __snake_case : NDArray[floataa] , __snake_case : float = 10**-1 ): """simple docstring""" _lowerCamelCase : NDArray[floataa] = cross(__snake_case , __snake_case ) _lowerCamelCase : float = sum(__snake_case ) return abs(__snake_case ) < eps if __name__ == "__main__": # Test to check if it works UpperCAmelCase = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg UpperCAmelCase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) UpperCAmelCase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg UpperCAmelCase = array([[0, -2000], [0, -1200], [0, 1_5600], [0, -1_2400]]) UpperCAmelCase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
88
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase = { """configuration_squeezebert""": [ """SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SqueezeBertConfig""", """SqueezeBertOnnxConfig""", ], """tokenization_squeezebert""": ["""SqueezeBertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""SqueezeBertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ """SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """SqueezeBertForMaskedLM""", """SqueezeBertForMultipleChoice""", """SqueezeBertForQuestionAnswering""", """SqueezeBertForSequenceClassification""", """SqueezeBertForTokenClassification""", """SqueezeBertModel""", """SqueezeBertModule""", """SqueezeBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_squeezebert import ( SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertOnnxConfig, ) from .tokenization_squeezebert import SqueezeBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_squeezebert import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, SqueezeBertModule, SqueezeBertPreTrainedModel, ) else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
"""simple docstring""" import random def _snake_case ( __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = a[left_index] _lowerCamelCase : Dict = left_index + 1 for j in range(left_index + 1 , __snake_case ): if a[j] < pivot: _lowerCamelCase , _lowerCamelCase : List[str] = a[i], a[j] i += 1 _lowerCamelCase , _lowerCamelCase : Optional[int] = a[i - 1], a[left_index] return i - 1 def _snake_case ( __snake_case : Tuple , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" if left < right: _lowerCamelCase : Any = random.randint(__snake_case , right - 1 ) _lowerCamelCase , _lowerCamelCase : Optional[Any] = ( a[left], a[pivot], ) # switches the pivot with the left most bound _lowerCamelCase : List[str] = partition(__snake_case , __snake_case , __snake_case ) quick_sort_random( __snake_case , __snake_case , __snake_case ) # recursive quicksort to the left of the pivot point quick_sort_random( __snake_case , pivot_index + 1 , __snake_case ) # recursive quicksort to the right of the pivot point def _snake_case ( ): """simple docstring""" _lowerCamelCase : Union[str, Any] = input("""Enter numbers separated by a comma:\n""" ).strip() _lowerCamelCase : int = [int(__snake_case ) for item in user_input.split(""",""" )] quick_sort_random(__snake_case , 0 , len(__snake_case ) ) print(__snake_case ) if __name__ == "__main__": main()
88
1
"""simple docstring""" def _snake_case ( __snake_case : str , __snake_case : list[str] ): """simple docstring""" _lowerCamelCase : int = """""" for word_or_phrase in separated: if not isinstance(__snake_case , __snake_case ): raise Exception("""join() accepts only strings to be joined""" ) joined += word_or_phrase + separator return joined.strip(__snake_case ) if __name__ == "__main__": from doctest import testmod testmod()
88
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase = """\ @misc{chen2021evaluating, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \ and William Saunders and Christopher Hesse and Andrew N. Carr \ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } """ UpperCAmelCase = """\ This metric implements the evaluation harness for the HumanEval problem solving dataset described in the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). """ UpperCAmelCase = """ Calculates how good are predictions given some references, using certain scores Args: predictions: list of candidates to evaluate. Each candidates should be a list of strings with several code candidates to solve the problem. references: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate. k: number of code candidates to consider in the evaluation (Default: [1, 10, 100]) num_workers: number of workers used to evaluate the canidate programs (Default: 4). timeout: Returns: pass_at_k: dict with pass rates for each k results: dict with granular results of each unittest Examples: >>> code_eval = datasets.load_metric(\"code_eval\") >>> test_cases = [\"assert add(2,3)==5\"] >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]] >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2]) >>> print(pass_at_k) {'pass@1': 0.5, 'pass@2': 1.0} """ UpperCAmelCase = """ ################################################################################ !!!WARNING!!! ################################################################################ The \"code_eval\" metric executes untrusted model-generated code in Python. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the paper \"Evaluating Large Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374). Once you have read this disclaimer and taken appropriate precautions, set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this with: >>> import os >>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\" ################################################################################\ """ UpperCAmelCase = """The MIT License Copyright (c) OpenAI (https://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> str: return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""")), """references""": datasets.Value("""string"""), }) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=[1, 10, 100] , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=3.0) -> Union[str, Any]: if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0) != "1": raise ValueError(_WARNING) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""") with ThreadPoolExecutor(max_workers=SCREAMING_SNAKE_CASE) as executor: _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Optional[int] = Counter() _lowerCamelCase : Any = 0 _lowerCamelCase : List[Any] = defaultdict(SCREAMING_SNAKE_CASE) for task_id, (candidates, test_case) in enumerate(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)): for candidate in candidates: _lowerCamelCase : Any = candidate + """\n""" + test_case _lowerCamelCase : Union[str, Any] = (test_program, timeout, task_id, completion_id[task_id]) _lowerCamelCase : List[str] = executor.submit(SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE) futures.append(SCREAMING_SNAKE_CASE) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(SCREAMING_SNAKE_CASE): _lowerCamelCase : int = future.result() results[result["task_id"]].append((result["""completion_id"""], result)) _lowerCamelCase , _lowerCamelCase : List[Any] = [], [] for result in results.values(): result.sort() _lowerCamelCase : List[str] = [r[1]["""passed"""] for r in result] total.append(len(SCREAMING_SNAKE_CASE)) correct.append(sum(SCREAMING_SNAKE_CASE)) _lowerCamelCase : List[Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = np.array(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = k _lowerCamelCase : Optional[Any] = {F'pass@{k}': estimate_pass_at_k(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE).mean() for k in ks if (total >= k).all()} return pass_at_k, results def _snake_case ( __snake_case : List[str] , __snake_case : List[str] , __snake_case : List[str] ): """simple docstring""" def estimator(__snake_case : int , __snake_case : int , __snake_case : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(__snake_case , __snake_case ): _lowerCamelCase : Optional[int] = itertools.repeat(__snake_case , len(__snake_case ) ) else: assert len(__snake_case ) == len(__snake_case ) _lowerCamelCase : List[str] = iter(__snake_case ) return np.array([estimator(int(__snake_case ) , int(__snake_case ) , __snake_case ) for n, c in zip(__snake_case , __snake_case )] )
88
1
"""simple docstring""" def _snake_case ( __snake_case : int ): """simple docstring""" if num <= 0: raise ValueError("""Input must be a positive integer""" ) _lowerCamelCase : Optional[Any] = [True] * (num + 1) _lowerCamelCase : Dict = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , __snake_case ): _lowerCamelCase : Any = False p += 1 return [prime for prime in range(2 , num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase = int(input("""Enter a positive integer: """).strip()) print(prime_sieve_eratosthenes(user_num))
88
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo UpperCAmelCase = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ UpperCAmelCase = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ UpperCAmelCase = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence"""), """references""": datasets.Sequence( datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence""") , id="""references"""), }) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 4 , ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=SCREAMING_SNAKE_CASE , hypotheses=SCREAMING_SNAKE_CASE , min_len=SCREAMING_SNAKE_CASE , max_len=SCREAMING_SNAKE_CASE) }
88
1
"""simple docstring""" class lowercase__ : # Public class to implement a graph def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> None: _lowerCamelCase : str = row _lowerCamelCase : Dict = col _lowerCamelCase : List[str] = graph def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> bool: return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> None: # Checking all 8 elements surrounding nth element _lowerCamelCase : Optional[int] = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order _lowerCamelCase : Union[str, Any] = [-1, 0, 1, -1, 1, -1, 0, 1] _lowerCamelCase : Union[str, Any] = True # Make those cells visited for k in range(8): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , SCREAMING_SNAKE_CASE): self.diffs(i + row_nbr[k] , j + col_nbr[k] , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> int: # And finally, count all islands. _lowerCamelCase : Tuple = [[False for j in range(self.COL)] for i in range(self.ROW)] _lowerCamelCase : int = 0 for i in range(self.ROW): for j in range(self.COL): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) count += 1 return count
88
"""simple docstring""" def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : str = len(__snake_case ) _lowerCamelCase : Union[str, Any] = len(__snake_case ) _lowerCamelCase : int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] _lowerCamelCase : Union[str, Any] = True for i in range(__snake_case ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: _lowerCamelCase : Tuple = True if a[i].islower(): _lowerCamelCase : Tuple = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def _snake_case ( __snake_case : dict ): """simple docstring""" return (data["data"], data["target"]) def _snake_case ( __snake_case : np.ndarray , __snake_case : np.ndarray , __snake_case : np.ndarray ): """simple docstring""" _lowerCamelCase : int = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(__snake_case , __snake_case ) # Predict target for test data _lowerCamelCase : str = xgb.predict(__snake_case ) _lowerCamelCase : Optional[Any] = predictions.reshape(len(__snake_case ) , 1 ) return predictions def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[Any] = fetch_california_housing() _lowerCamelCase , _lowerCamelCase : Union[str, Any] = data_handling(__snake_case ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = train_test_split( __snake_case , __snake_case , test_size=0.25 , random_state=1 ) _lowerCamelCase : List[str] = xgboost(__snake_case , __snake_case , __snake_case ) # Error printing print(F'Mean Absolute Error : {mean_absolute_error(__snake_case , __snake_case )}' ) print(F'Mean Square Error : {mean_squared_error(__snake_case , __snake_case )}' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
88
"""simple docstring""" import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> None: warnings.warn( """The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ImageGPTImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE)
88
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowercase__ ( metaclass=A_ ): __UpperCAmelCase = ['''torch''', '''scipy'''] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> str: requires_backends(self , ["""torch""", """scipy"""]) @classmethod def UpperCamelCase_ ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> Optional[int]: requires_backends(cls , ["""torch""", """scipy"""]) @classmethod def UpperCamelCase_ ( cls , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> int: requires_backends(cls , ["""torch""", """scipy"""])
88
"""simple docstring""" from math import isqrt, loga def _snake_case ( __snake_case : int ): """simple docstring""" _lowerCamelCase : List[str] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __snake_case , __snake_case ): _lowerCamelCase : Optional[int] = False return [i for i in range(2 , __snake_case ) if is_prime[i]] def _snake_case ( __snake_case : int = 800800 , __snake_case : int = 800800 ): """simple docstring""" _lowerCamelCase : Union[str, Any] = degree * loga(__snake_case ) _lowerCamelCase : Union[str, Any] = int(__snake_case ) _lowerCamelCase : Dict = calculate_prime_numbers(__snake_case ) _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : Any = 0 _lowerCamelCase : Any = len(__snake_case ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f'''{solution() = }''')
88
1
"""simple docstring""" import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_config_file""": """tokenizer_config.json""", } UpperCAmelCase = { """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""" ) }, } UpperCAmelCase = {"""facebook/blenderbot_small-90M""": 512} def _snake_case ( __snake_case : Tuple ): """simple docstring""" _lowerCamelCase : Optional[Any] = set() _lowerCamelCase : Any = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _lowerCamelCase : Tuple = char _lowerCamelCase : Tuple = set(__snake_case ) return pairs class lowercase__ ( A_ ): __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['''input_ids''', '''attention_mask'''] def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE="__start__" , SCREAMING_SNAKE_CASE="__end__" , SCREAMING_SNAKE_CASE="__unk__" , SCREAMING_SNAKE_CASE="__null__" , **SCREAMING_SNAKE_CASE , ) -> List[str]: super().__init__(unk_token=SCREAMING_SNAKE_CASE , bos_token=SCREAMING_SNAKE_CASE , eos_token=SCREAMING_SNAKE_CASE , pad_token=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) with open(SCREAMING_SNAKE_CASE , encoding="""utf-8""") as vocab_handle: _lowerCamelCase : List[str] = json.load(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = {v: k for k, v in self.encoder.items()} with open(SCREAMING_SNAKE_CASE , encoding="""utf-8""") as merges_handle: _lowerCamelCase : Dict = merges_handle.read().split("""\n""")[1:-1] _lowerCamelCase : Optional[int] = [tuple(merge.split()) for merge in merges] _lowerCamelCase : int = dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE)))) _lowerCamelCase : Dict = {} @property def UpperCamelCase_ ( self) -> int: return len(self.encoder) def UpperCamelCase_ ( self) -> Dict: return dict(self.encoder , **self.added_tokens_encoder) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> str: if token in self.cache: return self.cache[token] _lowerCamelCase : List[Any] = re.sub("""([.,!?()])""" , r""" \1""" , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = re.sub("""(')""" , r""" \1 """ , SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = re.sub(r"""\s{2,}""" , """ """ , SCREAMING_SNAKE_CASE) if "\n" in token: _lowerCamelCase : Tuple = token.replace("""\n""" , """ __newln__""") _lowerCamelCase : Any = token.split(""" """) _lowerCamelCase : str = [] for token in tokens: if not len(SCREAMING_SNAKE_CASE): continue _lowerCamelCase : str = token.lower() _lowerCamelCase : Any = tuple(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = tuple(list(word[:-1]) + [word[-1] + """</w>"""]) _lowerCamelCase : Tuple = get_pairs(SCREAMING_SNAKE_CASE) if not pairs: words.append(SCREAMING_SNAKE_CASE) continue while True: _lowerCamelCase : Optional[Any] = min(SCREAMING_SNAKE_CASE , key=lambda SCREAMING_SNAKE_CASE: self.bpe_ranks.get(SCREAMING_SNAKE_CASE , float("""inf"""))) if bigram not in self.bpe_ranks: break _lowerCamelCase , _lowerCamelCase : Tuple = bigram _lowerCamelCase : Dict = [] _lowerCamelCase : Union[str, Any] = 0 while i < len(SCREAMING_SNAKE_CASE): try: _lowerCamelCase : List[Any] = word.index(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) new_word.extend(word[i:j]) _lowerCamelCase : List[str] = j except ValueError: new_word.extend(word[i:]) break if word[i] == first and i < len(SCREAMING_SNAKE_CASE) - 1 and word[i + 1] == second: new_word.append(first + second) i += 2 else: new_word.append(word[i]) i += 1 _lowerCamelCase : Any = tuple(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = new_word if len(SCREAMING_SNAKE_CASE) == 1: break else: _lowerCamelCase : Optional[int] = get_pairs(SCREAMING_SNAKE_CASE) _lowerCamelCase : int = """@@ """.join(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = word[:-4] _lowerCamelCase : Dict = word words.append(SCREAMING_SNAKE_CASE) return " ".join(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Any = [] _lowerCamelCase : Any = re.findall(r"""\S+\n?""" , SCREAMING_SNAKE_CASE) for token in words: split_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE).split(""" """))) return split_tokens def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : Tuple = token.lower() return self.encoder.get(SCREAMING_SNAKE_CASE , self.encoder.get(self.unk_token)) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> str: return self.decoder.get(SCREAMING_SNAKE_CASE , self.unk_token) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : str = """ """.join(SCREAMING_SNAKE_CASE).replace("""@@ """ , """""").strip() return out_string def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return _lowerCamelCase : int = os.path.join( SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]) _lowerCamelCase : Tuple = os.path.join( SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]) with open(SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""") as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE , ensure_ascii=SCREAMING_SNAKE_CASE) + """\n""") _lowerCamelCase : List[Any] = 0 with open(SCREAMING_SNAKE_CASE , """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 SCREAMING_SNAKE_CASE: 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!""") _lowerCamelCase : int = token_index writer.write(""" """.join(SCREAMING_SNAKE_CASE) + """\n""") index += 1 return vocab_file, merge_file
88
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = StableDiffusionSAGPipeline __UpperCAmelCase = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: torch.manual_seed(0) _lowerCamelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _lowerCamelCase : int = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0) _lowerCamelCase : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0) _lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _lowerCamelCase : List[Any] = CLIPTextModel(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""") _lowerCamelCase : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0) -> List[Any]: if str(SCREAMING_SNAKE_CASE).startswith("""mps"""): _lowerCamelCase : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3) @slow @require_torch_gpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""") _lowerCamelCase : Union[str, Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = """.""" _lowerCamelCase : int = torch.manual_seed(0) _lowerCamelCase : Tuple = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Dict = output.images _lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Optional[Any] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Dict = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = """.""" _lowerCamelCase : List[str] = torch.manual_seed(0) _lowerCamelCase : int = sag_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""") _lowerCamelCase : Any = output.images _lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2 def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : int = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""") _lowerCamelCase : Optional[Any] = sag_pipe.to(SCREAMING_SNAKE_CASE) sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = """.""" _lowerCamelCase : Union[str, Any] = torch.manual_seed(0) _lowerCamelCase : Optional[int] = sag_pipe( [prompt] , width=768 , height=512 , generator=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) _lowerCamelCase : Union[str, Any] = output.images assert image.shape == (1, 512, 768, 3)
88
1
"""simple docstring""" import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging UpperCAmelCase = logging.get_logger(__name__) class lowercase__ ( A_ ): __UpperCAmelCase = ['''input_features''', '''is_longer'''] def __init__( self , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=4_8000 , SCREAMING_SNAKE_CASE=480 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=1024 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE = 0 , SCREAMING_SNAKE_CASE = 1_4000 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "fusion" , SCREAMING_SNAKE_CASE = "repeatpad" , **SCREAMING_SNAKE_CASE , ) -> Dict: super().__init__( feature_size=SCREAMING_SNAKE_CASE , sampling_rate=SCREAMING_SNAKE_CASE , padding_value=SCREAMING_SNAKE_CASE , return_attention_mask=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) _lowerCamelCase : List[Any] = top_db _lowerCamelCase : Dict = truncation _lowerCamelCase : str = padding _lowerCamelCase : Any = fft_window_size _lowerCamelCase : Dict = (fft_window_size >> 1) + 1 _lowerCamelCase : Optional[Any] = hop_length _lowerCamelCase : Any = max_length_s _lowerCamelCase : List[str] = max_length_s * sampling_rate _lowerCamelCase : List[str] = sampling_rate _lowerCamelCase : List[Any] = frequency_min _lowerCamelCase : str = frequency_max _lowerCamelCase : List[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=SCREAMING_SNAKE_CASE , min_frequency=SCREAMING_SNAKE_CASE , max_frequency=SCREAMING_SNAKE_CASE , sampling_rate=SCREAMING_SNAKE_CASE , norm=SCREAMING_SNAKE_CASE , mel_scale="""htk""" , ) _lowerCamelCase : Union[str, Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=SCREAMING_SNAKE_CASE , min_frequency=SCREAMING_SNAKE_CASE , max_frequency=SCREAMING_SNAKE_CASE , sampling_rate=SCREAMING_SNAKE_CASE , norm="""slaney""" , mel_scale="""slaney""" , ) def UpperCamelCase_ ( self) -> Dict[str, Any]: _lowerCamelCase : Optional[int] = copy.deepcopy(self.__dict__) _lowerCamelCase : Optional[Any] = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None) -> np.ndarray: _lowerCamelCase : Optional[Any] = spectrogram( SCREAMING_SNAKE_CASE , window_function(self.fft_window_size , """hann""") , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=SCREAMING_SNAKE_CASE , log_mel="""dB""" , ) return log_mel_spectrogram.T def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : int = np.array_split(list(range(0 , total_frames - chunk_frames + 1)) , 3) if len(ranges[1]) == 0: # if the audio is too short, we just use the first chunk _lowerCamelCase : List[Any] = [0] if len(ranges[2]) == 0: # if the audio is too short, we just use the first chunk _lowerCamelCase : List[Any] = [0] # randomly choose index for each part _lowerCamelCase : List[str] = np.random.choice(ranges[0]) _lowerCamelCase : Union[str, Any] = np.random.choice(ranges[1]) _lowerCamelCase : Any = np.random.choice(ranges[2]) _lowerCamelCase : Union[str, Any] = mel[idx_front : idx_front + chunk_frames, :] _lowerCamelCase : Union[str, Any] = mel[idx_middle : idx_middle + chunk_frames, :] _lowerCamelCase : Dict = mel[idx_back : idx_back + chunk_frames, :] _lowerCamelCase : Optional[int] = torch.tensor(mel[None, None, :]) _lowerCamelCase : Tuple = torch.nn.functional.interpolate( SCREAMING_SNAKE_CASE , size=[chunk_frames, 64] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = mel_shrink[0][0].numpy() _lowerCamelCase : List[str] = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0) return mel_fusion def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> np.array: if waveform.shape[0] > max_length: if truncation == "rand_trunc": _lowerCamelCase : Dict = True # random crop to max_length (for compatibility) -> this should be handled by self.pad _lowerCamelCase : List[str] = len(SCREAMING_SNAKE_CASE) - max_length _lowerCamelCase : str = np.random.randint(0 , overflow + 1) _lowerCamelCase : Any = waveform[idx : idx + max_length] _lowerCamelCase : Tuple = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE , self.mel_filters_slaney)[None, :] elif truncation == "fusion": _lowerCamelCase : str = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE , self.mel_filters) _lowerCamelCase : List[str] = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed _lowerCamelCase : List[str] = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. _lowerCamelCase : Dict = np.stack([mel, mel, mel, mel] , axis=0) _lowerCamelCase : List[Any] = False else: _lowerCamelCase : Tuple = self._random_mel_fusion(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = True else: raise NotImplementedError(F'data_truncating {truncation} not implemented') else: _lowerCamelCase : Union[str, Any] = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": _lowerCamelCase : Tuple = int(max_length / len(SCREAMING_SNAKE_CASE)) _lowerCamelCase : Union[str, Any] = np.stack(np.tile(SCREAMING_SNAKE_CASE , n_repeat + 1))[:max_length] if padding == "repeatpad": _lowerCamelCase : List[Any] = int(max_length / len(SCREAMING_SNAKE_CASE)) _lowerCamelCase : str = np.stack(np.tile(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)) _lowerCamelCase : str = np.pad(SCREAMING_SNAKE_CASE , (0, max_length - waveform.shape[0]) , mode="""constant""" , constant_values=0) if truncation == "fusion": _lowerCamelCase : Optional[Any] = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE , self.mel_filters) _lowerCamelCase : Optional[Any] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0) else: _lowerCamelCase : Tuple = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE , self.mel_filters_slaney)[None, :] return input_mel, longer def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> BatchFeature: _lowerCamelCase : Tuple = truncation if truncation is not None else self.truncation _lowerCamelCase : int = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F'The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a' F' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input' F' was sampled with {self.sampling_rate} and not {sampling_rate}.') else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""") _lowerCamelCase : Dict = isinstance(SCREAMING_SNAKE_CASE , np.ndarray) and len(raw_speech.shape) > 1 if is_batched_numpy and len(raw_speech.shape) > 2: raise ValueError(F'Only mono-channel audio is supported for input to {self}') _lowerCamelCase : Any = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE , (list, tuple)) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list))) ) if is_batched: _lowerCamelCase : Any = [np.asarray(SCREAMING_SNAKE_CASE , dtype=np.floataa) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE , np.ndarray): _lowerCamelCase : int = np.asarray(SCREAMING_SNAKE_CASE , dtype=np.floataa) elif isinstance(SCREAMING_SNAKE_CASE , np.ndarray) and raw_speech.dtype is np.dtype(np.floataa): _lowerCamelCase : str = raw_speech.astype(np.floataa) # always return batch if not is_batched: _lowerCamelCase : Dict = [np.asarray(SCREAMING_SNAKE_CASE)] # convert to mel spectrogram, truncate and pad if needed. _lowerCamelCase : int = [ self._get_input_mel(SCREAMING_SNAKE_CASE , max_length if max_length else self.nb_max_samples , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) for waveform in raw_speech ] _lowerCamelCase : Dict = [] _lowerCamelCase : Optional[int] = [] for mel, longer in padded_inputs: input_mel.append(SCREAMING_SNAKE_CASE) is_longer.append(SCREAMING_SNAKE_CASE) if truncation == "fusion" and sum(SCREAMING_SNAKE_CASE) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer _lowerCamelCase : Any = np.random.randint(0 , len(SCREAMING_SNAKE_CASE)) _lowerCamelCase : List[Any] = True if isinstance(input_mel[0] , SCREAMING_SNAKE_CASE): _lowerCamelCase : Any = [np.asarray(SCREAMING_SNAKE_CASE , dtype=np.floataa) for feature in input_mel] # is_longer is a list of bool _lowerCamelCase : Union[str, Any] = [[longer] for longer in is_longer] _lowerCamelCase : Optional[int] = {"""input_features""": input_mel, """is_longer""": is_longer} _lowerCamelCase : Optional[int] = BatchFeature(SCREAMING_SNAKE_CASE) if return_tensors is not None: _lowerCamelCase : List[Any] = input_features.convert_to_tensors(SCREAMING_SNAKE_CASE) return input_features
88
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=32 * 8 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=64 , ) -> Optional[int]: _lowerCamelCase : List[str] = parent _lowerCamelCase : List[Any] = batch_size _lowerCamelCase : Tuple = is_training _lowerCamelCase : Tuple = use_auxiliary_loss _lowerCamelCase : Any = num_queries _lowerCamelCase : List[str] = num_channels _lowerCamelCase : List[str] = min_size _lowerCamelCase : Tuple = max_size _lowerCamelCase : str = num_labels _lowerCamelCase : Any = hidden_dim _lowerCamelCase : Dict = hidden_dim def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE) > 0.5 ).float() _lowerCamelCase : Dict = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE) > 0.5).long() _lowerCamelCase : Optional[int] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def UpperCamelCase_ ( self) -> str: _lowerCamelCase : List[str] = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _lowerCamelCase : Any = self.num_queries _lowerCamelCase : int = self.num_labels _lowerCamelCase : int = [1, 1, 1, 1] _lowerCamelCase : Any = self.num_channels _lowerCamelCase : Optional[Any] = 64 _lowerCamelCase : str = 128 _lowerCamelCase : Optional[Any] = self.hidden_dim _lowerCamelCase : Any = self.hidden_dim _lowerCamelCase : List[Any] = self.hidden_dim return config def UpperCamelCase_ ( self) -> Any: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[str] = self.prepare_config_and_inputs() _lowerCamelCase : str = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[int]: _lowerCamelCase : str = output.encoder_hidden_states _lowerCamelCase : int = output.pixel_decoder_hidden_states _lowerCamelCase : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , len(config.backbone_config.depths)) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE) , config.decoder_layers) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False) -> List[str]: with torch.no_grad(): _lowerCamelCase : Optional[int] = MaskaFormerModel(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[int] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = model(SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(output.encoder_last_hidden_state is not None) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> str: _lowerCamelCase : str = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(result.encoder_last_hidden_state is not None) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1)) with torch.no_grad(): _lowerCamelCase : List[Any] = model(pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model( pixel_values=SCREAMING_SNAKE_CASE , pixel_mask=SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) comm_check_on_output(SCREAMING_SNAKE_CASE) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape , torch.Size([1])) @require_torch class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase : Optional[int] = MaskaFormerModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[str]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> int: _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""") def UpperCamelCase_ ( self) -> Optional[int]: pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""") def UpperCamelCase_ ( self) -> Tuple: pass @unittest.skip(reason="""Mask2Former is not a generative model""") def UpperCamelCase_ ( self) -> List[Any]: pass @unittest.skip(reason="""Mask2Former does not use token embeddings""") def UpperCamelCase_ ( self) -> Any: pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""") def UpperCamelCase_ ( self) -> Dict: pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""") def UpperCamelCase_ ( self) -> Optional[int]: pass def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : str = [*signature.parameters.keys()] _lowerCamelCase : int = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> Optional[int]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _lowerCamelCase : Optional[int] = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Dict = (self.model_tester.min_size,) * 2 _lowerCamelCase : str = { """pixel_values""": torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE), """mask_labels""": torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE), """class_labels""": torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE).long(), } _lowerCamelCase : List[str] = self.model_tester.get_config() _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE , output_attentions=SCREAMING_SNAKE_CASE) self.assertTrue(outputs.attentions is not None) def UpperCamelCase_ ( self) -> Optional[Any]: if not self.model_tester.is_training: return _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE).loss loss.backward() def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = self.all_model_classes[1] _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() _lowerCamelCase : int = True _lowerCamelCase : Optional[Any] = True _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) model.train() _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE , mask_labels=SCREAMING_SNAKE_CASE , class_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _lowerCamelCase : int = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _lowerCamelCase : str = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _lowerCamelCase : Optional[int] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(pixel_decoder_hidden_states.grad) self.assertIsNotNone(transformer_decoder_hidden_states.grad) self.assertIsNotNone(attentions.grad) UpperCAmelCase = 1e-4 def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def UpperCamelCase_ ( self) -> Union[str, Any]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Tuple = MaskaFormerModel.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : List[str] = prepare_img() _lowerCamelCase : Union[str, Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Any = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) _lowerCamelCase : Dict = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]]).to(SCREAMING_SNAKE_CASE) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : Optional[Any] = self.default_image_processor _lowerCamelCase : Any = prepare_img() _lowerCamelCase : Dict = image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) # check size self.assertEqual(SCREAMING_SNAKE_CASE , (1, 3, 384, 384)) with torch.no_grad(): _lowerCamelCase : List[str] = model(**SCREAMING_SNAKE_CASE) # masks_queries_logits _lowerCamelCase : str = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)) _lowerCamelCase : Any = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] _lowerCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) # class_queries_logits _lowerCamelCase : List[str] = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1)) _lowerCamelCase : Optional[Any] = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ]).to(SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE)) def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Tuple = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(SCREAMING_SNAKE_CASE).eval() _lowerCamelCase : str = self.default_image_processor _lowerCamelCase : Tuple = image_processor( [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors="""pt""" , ) _lowerCamelCase : Optional[Any] = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""mask_labels"""]] _lowerCamelCase : Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE) for el in inputs["""class_labels"""]] with torch.no_grad(): _lowerCamelCase : Any = model(**SCREAMING_SNAKE_CASE) self.assertTrue(outputs.loss is not None)
88
1
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) UpperCAmelCase = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) UpperCAmelCase = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) UpperCAmelCase = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModel) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
88
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) UpperCAmelCase = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) UpperCAmelCase = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) UpperCAmelCase = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) UpperCAmelCase = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModel) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class lowercase__ ( _BaseAutoModelClass ): __UpperCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
88
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class lowercase__ : __UpperCAmelCase = XGLMConfig __UpperCAmelCase = {} __UpperCAmelCase = '''gelu''' def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=14 , SCREAMING_SNAKE_CASE=7 , 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=0.02 , ) -> List[str]: _lowerCamelCase : Optional[int] = parent _lowerCamelCase : int = batch_size _lowerCamelCase : str = seq_length _lowerCamelCase : Any = is_training _lowerCamelCase : int = use_input_mask _lowerCamelCase : Union[str, Any] = use_labels _lowerCamelCase : str = vocab_size _lowerCamelCase : List[str] = d_model _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Dict = num_attention_heads _lowerCamelCase : int = ffn_dim _lowerCamelCase : str = activation_function _lowerCamelCase : Optional[int] = activation_dropout _lowerCamelCase : Tuple = attention_dropout _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Dict = initializer_range _lowerCamelCase : Optional[Any] = None _lowerCamelCase : Union[str, Any] = 0 _lowerCamelCase : List[Any] = 2 _lowerCamelCase : str = 1 def UpperCamelCase_ ( self) -> int: return XGLMConfig.from_pretrained("""facebook/xglm-564M""") def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) , clip_value_min=0 , clip_value_max=3) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Tuple = self.get_config() _lowerCamelCase : Optional[int] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2) return ( config, input_ids, input_mask, head_mask, ) def UpperCamelCase_ ( self) -> Optional[int]: return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : str = config_and_inputs _lowerCamelCase : Optional[Any] = { """input_ids""": input_ids, """head_mask""": head_mask, } return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () __UpperCAmelCase = (TFXGLMForCausalLM,) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Optional[Any] = TFXGLMModelTester(self) _lowerCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , n_embd=37) def UpperCamelCase_ ( self) -> Dict: self.config_tester.run_common_tests() @slow def UpperCamelCase_ ( self) -> List[Any]: for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Tuple = TFXGLMModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""") def UpperCamelCase_ ( self) -> List[Any]: super().test_resize_token_embeddings() @require_tf class lowercase__ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=True) -> List[Any]: _lowerCamelCase : List[str] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Union[str, Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCamelCase : Dict = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on _lowerCamelCase : str = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , num_beams=1) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: _lowerCamelCase : int = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Tuple = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") tf.random.set_seed(0) _lowerCamelCase : Union[str, Any] = tokenizer("""Today is a nice day and""" , return_tensors="""tf""") _lowerCamelCase : Any = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(""":/CPU:0"""): _lowerCamelCase : Any = model.generate(SCREAMING_SNAKE_CASE , do_sample=SCREAMING_SNAKE_CASE , seed=[7, 0]) _lowerCamelCase : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = ( """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due""" ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[Any] = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : Any = XGLMTokenizer.from_pretrained("""facebook/xglm-564M""") _lowerCamelCase : List[Any] = """left""" # use different length sentences to test batching _lowerCamelCase : List[Any] = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When""", """Hello, my dog is a little""", ] _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""tf""" , padding=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = inputs["""input_ids"""] _lowerCamelCase : List[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , attention_mask=inputs["""attention_mask"""] , max_new_tokens=12) _lowerCamelCase : List[str] = tokenizer(sentences[0] , return_tensors="""tf""").input_ids _lowerCamelCase : Optional[Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Tuple = tokenizer(sentences[1] , return_tensors="""tf""").input_ids _lowerCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE , max_new_tokens=12) _lowerCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = [ """This is an extremelly long sentence that only exists to test the ability of the model to cope with """ """left-padding, such as in batched generation. The output for the sequence below should be the same """ """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """ """a single""", """Hello, my dog is a little bit of a shy one, but he is very friendly""", ] self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) self.assertListEqual(SCREAMING_SNAKE_CASE , [non_padded_sentence, padded_sentence])
88
"""simple docstring""" # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
88
1
"""simple docstring""" import unittest from transformers import GPTNeoXJapaneseConfig, is_torch_available from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel class lowercase__ : 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=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=None , ) -> List[str]: _lowerCamelCase : Optional[Any] = parent _lowerCamelCase : str = batch_size _lowerCamelCase : Optional[int] = seq_length _lowerCamelCase : Optional[Any] = is_training _lowerCamelCase : Any = use_input_mask _lowerCamelCase : List[Any] = use_token_type_ids _lowerCamelCase : Dict = use_labels _lowerCamelCase : Dict = vocab_size _lowerCamelCase : Optional[int] = hidden_size _lowerCamelCase : Union[str, Any] = num_hidden_layers _lowerCamelCase : Tuple = num_attention_heads _lowerCamelCase : Tuple = intermediate_multiple_size _lowerCamelCase : str = hidden_act _lowerCamelCase : Dict = hidden_dropout _lowerCamelCase : str = attention_dropout _lowerCamelCase : Optional[int] = weight_tying _lowerCamelCase : Union[str, Any] = max_position_embeddings _lowerCamelCase : Tuple = type_vocab_size _lowerCamelCase : str = type_sequence_label_size _lowerCamelCase : int = initializer_range _lowerCamelCase : Union[str, Any] = num_labels _lowerCamelCase : List[str] = num_choices _lowerCamelCase : List[Any] = scope def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _lowerCamelCase : Any = None if self.use_input_mask: _lowerCamelCase : Optional[int] = random_attention_mask([self.batch_size, self.seq_length]) _lowerCamelCase : Optional[Any] = None if self.use_labels: _lowerCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) _lowerCamelCase : List[str] = self.get_config() return config, input_ids, input_mask, token_labels def UpperCamelCase_ ( self) -> Tuple: return GPTNeoXJapaneseConfig( 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_multiple_size=self.intermediate_multiple_size , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , weight_tying=self.weight_tying , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self) -> int: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = self.prepare_config_and_inputs() _lowerCamelCase : List[Any] = True return config, input_ids, input_mask, token_labels def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Tuple: _lowerCamelCase : Dict = GPTNeoXJapaneseModel(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : str = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Tuple: _lowerCamelCase : Optional[Any] = True _lowerCamelCase : int = GPTNeoXJapaneseModel(SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Any: _lowerCamelCase : Optional[Any] = GPTNeoXJapaneseForCausalLM(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() _lowerCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : Union[str, Any] = True _lowerCamelCase : List[Any] = GPTNeoXJapaneseForCausalLM(config=SCREAMING_SNAKE_CASE) model.to(SCREAMING_SNAKE_CASE) model.eval() # first forward pass _lowerCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _lowerCamelCase : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size) _lowerCamelCase : List[Any] = ids_tensor((self.batch_size, 3) , vocab_size=2) # append to next input_ids and _lowerCamelCase : List[str] = torch.cat([input_ids, next_tokens] , dim=-1) _lowerCamelCase : Tuple = torch.cat([input_mask, next_mask] , dim=-1) _lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = output_from_no_past["""hidden_states"""][0] _lowerCamelCase : Union[str, Any] = model( SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , past_key_values=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )["""hidden_states"""][0] # select random slice _lowerCamelCase : Dict = ids_tensor((1,) , output_from_past.shape[-1]).item() _lowerCamelCase : Dict = output_from_no_past[:, -3:, random_slice_idx].detach() _lowerCamelCase : List[str] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3)) def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Any = self.prepare_config_and_inputs() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[Any] = config_and_inputs _lowerCamelCase : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else () __UpperCAmelCase = (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else () __UpperCAmelCase = ( {'''feature-extraction''': GPTNeoXJapaneseModel, '''text-generation''': GPTNeoXJapaneseForCausalLM} if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : Optional[Any] = GPTNeoXJapaneseModelTester(self) _lowerCamelCase : List[str] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=37) def UpperCamelCase_ ( self) -> List[str]: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> str: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> int: # This regression test was failing with PyTorch < 1.3 _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() _lowerCamelCase : str = None self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: _lowerCamelCase : Tuple = """abeja/gpt-neox-japanese-2.7b""" _lowerCamelCase : Optional[int] = ["""データサイエンティストとは、""", """100年後に必要とされる会社は、""", """フルリモートの環境で働くために必要なことは、""", """国境の長いトンネルを抜けると""", """美味しい日本食といえば、"""] _lowerCamelCase : List[Any] = [ """データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。""", """100年後に必要とされる会社は、「人」が中心の会社です。""", """フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。""", """国境の長いトンネルを抜けると、そこは雪国だった。""", """美味しい日本食といえば、やっぱりお寿司ですよね。""", ] _lowerCamelCase : Optional[int] = GPTNeoXJapaneseTokenizer.from_pretrained(SCREAMING_SNAKE_CASE) _lowerCamelCase : int = GPTNeoXJapaneseForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = [] for prompt in prompts: _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="""pt""").input_ids _lowerCamelCase : List[Any] = model.generate(SCREAMING_SNAKE_CASE , max_length=50) _lowerCamelCase : Any = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE) predicted_outputs += generated_string self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)
88
"""simple docstring""" def _snake_case ( __snake_case : list[list[int]] , __snake_case : int , __snake_case : int , __snake_case : list[int] ): """simple docstring""" if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def _snake_case ( __snake_case : list[list[int]] , __snake_case : list[int] , __snake_case : int ): """simple docstring""" if curr_ind == len(__snake_case ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(__snake_case ) ): if valid_connection(__snake_case , __snake_case , __snake_case , __snake_case ): # Insert current vertex into path as next transition _lowerCamelCase : List[str] = next_ver # Validate created path if util_hamilton_cycle(__snake_case , __snake_case , curr_ind + 1 ): return True # Backtrack _lowerCamelCase : Tuple = -1 return False def _snake_case ( __snake_case : list[list[int]] , __snake_case : int = 0 ): """simple docstring""" _lowerCamelCase : Any = [-1] * (len(__snake_case ) + 1) # initialize start and end of path with starting index _lowerCamelCase : Optional[int] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(__snake_case , __snake_case , 1 ) else []
88
1
"""simple docstring""" import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput UpperCAmelCase = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE) -> str: super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = eval_examples _lowerCamelCase : Union[str, Any] = post_process_function _lowerCamelCase : List[str] = quant_trainer_args _lowerCamelCase : Optional[int] = 128 # default number of calibration samples def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=None) -> Tuple: if calib_dataset is None and self.calib_dataset is None: raise ValueError("""Trainer: calibration requires an calib_dataset.""") _lowerCamelCase : Union[str, Any] = calib_dataset if calib_dataset is not None else self.calib_dataset _lowerCamelCase : List[Any] = self._remove_unused_columns(SCREAMING_SNAKE_CASE , description="""Calibration""") return DataLoader( SCREAMING_SNAKE_CASE , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=SCREAMING_SNAKE_CASE , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=None) -> Optional[int]: _lowerCamelCase : List[str] = self.train_dataset if calib_dataset is None else calib_dataset _lowerCamelCase : Optional[Any] = self.get_calib_dataloader(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = self.model quant_trainer.configure_model(SCREAMING_SNAKE_CASE , self.quant_trainer_args , calib=SCREAMING_SNAKE_CASE) model.eval() quant_trainer.enable_calibration(SCREAMING_SNAKE_CASE) logger.info("""***** Running calibration *****""") logger.info(F' Num examples = {self.calib_num}') logger.info(F' Batch size = {calib_dataloader.batch_size}') for step, inputs in enumerate(SCREAMING_SNAKE_CASE): # Prediction step _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = self.prediction_step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , prediction_loss_only=SCREAMING_SNAKE_CASE) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(SCREAMING_SNAKE_CASE , self.quant_trainer_args) _lowerCamelCase : int = model def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE = "eval") -> Optional[Any]: _lowerCamelCase : Tuple = self.eval_dataset if eval_dataset is None else eval_dataset _lowerCamelCase : Optional[int] = self.get_eval_dataloader(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. _lowerCamelCase : List[Any] = self.compute_metrics _lowerCamelCase : Union[str, Any] = None _lowerCamelCase : List[Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: _lowerCamelCase : str = eval_loop( SCREAMING_SNAKE_CASE , description="""Evaluation""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=SCREAMING_SNAKE_CASE , ) finally: _lowerCamelCase : List[str] = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: _lowerCamelCase : Union[str, Any] = self.post_process_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , output.predictions) _lowerCamelCase : Union[str, Any] = self.compute_metrics(SCREAMING_SNAKE_CASE) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(F'{metric_key_prefix}_'): _lowerCamelCase : Tuple = metrics.pop(SCREAMING_SNAKE_CASE) self.log(SCREAMING_SNAKE_CASE) else: _lowerCamelCase : str = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) _lowerCamelCase : Dict = self.callback_handler.on_evaluate(self.args , self.state , self.control , SCREAMING_SNAKE_CASE) return metrics def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE = "test") -> Union[str, Any]: _lowerCamelCase : Union[str, Any] = self.get_test_dataloader(SCREAMING_SNAKE_CASE) # Temporarily disable metric computation, we will do it in the loop here. _lowerCamelCase : Optional[int] = self.compute_metrics _lowerCamelCase : Dict = None _lowerCamelCase : Dict = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: _lowerCamelCase : Optional[int] = eval_loop( SCREAMING_SNAKE_CASE , description="""Prediction""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=SCREAMING_SNAKE_CASE , ) finally: _lowerCamelCase : Optional[Any] = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output _lowerCamelCase : List[str] = self.post_process_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , output.predictions , """predict""") _lowerCamelCase : Any = self.compute_metrics(SCREAMING_SNAKE_CASE) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(F'{metric_key_prefix}_'): _lowerCamelCase : int = metrics.pop(SCREAMING_SNAKE_CASE) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE="./") -> Optional[Any]: _lowerCamelCase : Optional[int] = self.eval_dataset _lowerCamelCase : Any = self.get_eval_dataloader(SCREAMING_SNAKE_CASE) _lowerCamelCase : int = next(iter(SCREAMING_SNAKE_CASE)) # saving device - to make it consistent _lowerCamelCase : Optional[int] = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""") # convert to tuple _lowerCamelCase : Union[str, Any] = tuple(v.to(SCREAMING_SNAKE_CASE) for k, v in batch.items()) logger.info("""Converting model to be onnx compatible""") from pytorch_quantization.nn import TensorQuantizer _lowerCamelCase : Tuple = True _lowerCamelCase : str = self.model.to(SCREAMING_SNAKE_CASE) model.eval() model.float() _lowerCamelCase : List[Any] = model.module if hasattr(SCREAMING_SNAKE_CASE , """module""") else model quant_trainer.configure_model(SCREAMING_SNAKE_CASE , self.quant_trainer_args) _lowerCamelCase : Optional[Any] = os.path.join(SCREAMING_SNAKE_CASE , """model.onnx""") logger.info(F'exporting model to {output_model_file}') _lowerCamelCase : Union[str, Any] = {0: """batch_size""", 1: """seq_len"""} torch.onnx.export( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , export_params=SCREAMING_SNAKE_CASE , opset_version=13 , do_constant_folding=SCREAMING_SNAKE_CASE , input_names=["""input_ids""", """attention_mask""", """token_type_ids"""] , output_names=["""output_start_logits""", """output_end_logits"""] , dynamic_axes={ """input_ids""": axes, """attention_mask""": axes, """token_type_ids""": axes, """output_start_logits""": axes, """output_end_logits""": axes, } , verbose=SCREAMING_SNAKE_CASE , ) logger.info("""onnx export finished""")
88
"""simple docstring""" import mpmath # for roots of unity import numpy as np class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None) -> Tuple: # Input as list _lowerCamelCase : Any = list(poly_a or [0])[:] _lowerCamelCase : Optional[Any] = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _lowerCamelCase : int = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() _lowerCamelCase : Union[str, Any] = len(self.polyB) # Add 0 to make lengths equal a power of 2 _lowerCamelCase : List[Any] = int( 2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1))) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform _lowerCamelCase : Optional[Any] = complex(mpmath.root(x=1 , n=self.c_max_length , k=1)) # The product _lowerCamelCase : int = self.__multiply() def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Dict = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE) <= 1: return dft[0] # _lowerCamelCase : str = self.c_max_length // 2 while next_ncol > 0: _lowerCamelCase : Dict = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : Tuple = self.root**next_ncol # First half of next step _lowerCamelCase : int = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step _lowerCamelCase : Optional[int] = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(SCREAMING_SNAKE_CASE): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update _lowerCamelCase : Union[str, Any] = new_dft _lowerCamelCase : List[str] = next_ncol // 2 return dft[0] def UpperCamelCase_ ( self) -> str: _lowerCamelCase : Optional[Any] = self.__dft("""A""") _lowerCamelCase : List[str] = self.__dft("""B""") _lowerCamelCase : List[Any] = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT _lowerCamelCase : List[str] = 2 while next_ncol <= self.c_max_length: _lowerCamelCase : Any = [[] for i in range(SCREAMING_SNAKE_CASE)] _lowerCamelCase : List[Any] = self.root ** (next_ncol // 2) _lowerCamelCase : str = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root)) current_root *= root # Update _lowerCamelCase : Any = new_inverse_c next_ncol *= 2 # Unpack _lowerCamelCase : Optional[Any] = [round(x[0].real , 8) + round(x[0].imag , 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self) -> Any: _lowerCamelCase : Dict = """A = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A])) _lowerCamelCase : List[Any] = """B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B])) _lowerCamelCase : int = """A*B = """ + """ + """.join( F'{coef}*x^{i}' for coef, i in enumerate(self.product)) return F'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""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 typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase = { """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""VisionEncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""TFVisionEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ["""FlaxVisionEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
88
1
"""simple docstring""" import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """google/owlvit-base-patch32""": """https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json""", """google/owlvit-base-patch16""": """https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json""", """google/owlvit-large-patch14""": """https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json""", } class lowercase__ ( A_ ): __UpperCAmelCase = '''owlvit_text_model''' def __init__( self , SCREAMING_SNAKE_CASE=4_9408 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=8 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE="quick_gelu" , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=4_9406 , SCREAMING_SNAKE_CASE=4_9407 , **SCREAMING_SNAKE_CASE , ) -> Dict: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : List[str] = vocab_size _lowerCamelCase : str = hidden_size _lowerCamelCase : Optional[int] = intermediate_size _lowerCamelCase : Dict = num_hidden_layers _lowerCamelCase : Optional[int] = num_attention_heads _lowerCamelCase : str = max_position_embeddings _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : Any = layer_norm_eps _lowerCamelCase : Dict = attention_dropout _lowerCamelCase : Dict = initializer_range _lowerCamelCase : Dict = initializer_factor @classmethod def UpperCamelCase_ ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE) _lowerCamelCase , _lowerCamelCase : int = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) # get the text config dict if we are loading from OwlViTConfig if config_dict.get("""model_type""") == "owlvit": _lowerCamelCase : List[Any] = 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(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) class lowercase__ ( A_ ): __UpperCAmelCase = '''owlvit_vision_model''' def __init__( self , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE="quick_gelu" , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1.0 , **SCREAMING_SNAKE_CASE , ) -> Tuple: super().__init__(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = hidden_size _lowerCamelCase : Optional[Any] = intermediate_size _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : Optional[Any] = num_attention_heads _lowerCamelCase : List[str] = num_channels _lowerCamelCase : Optional[Any] = image_size _lowerCamelCase : Tuple = patch_size _lowerCamelCase : int = hidden_act _lowerCamelCase : Any = layer_norm_eps _lowerCamelCase : int = attention_dropout _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : Any = initializer_factor @classmethod def UpperCamelCase_ ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE) _lowerCamelCase , _lowerCamelCase : Optional[int] = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get("""model_type""") == "owlvit": _lowerCamelCase : Optional[int] = 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(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) class lowercase__ ( A_ ): __UpperCAmelCase = '''owlvit''' __UpperCAmelCase = True def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2.65_92 , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: super().__init__(**SCREAMING_SNAKE_CASE) if text_config is None: _lowerCamelCase : Dict = {} logger.info("""text_config is None. Initializing the OwlViTTextConfig with default values.""") if vision_config is None: _lowerCamelCase : Any = {} logger.info("""vision_config is None. initializing the OwlViTVisionConfig with default values.""") _lowerCamelCase : str = OwlViTTextConfig(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = OwlViTVisionConfig(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Union[str, Any] = projection_dim _lowerCamelCase : List[Any] = logit_scale_init_value _lowerCamelCase : List[str] = return_dict _lowerCamelCase : Optional[int] = 1.0 @classmethod def UpperCamelCase_ ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE) _lowerCamelCase , _lowerCamelCase : Dict = cls.get_config_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) 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(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) @classmethod def UpperCamelCase_ ( cls , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> Tuple: _lowerCamelCase : Tuple = {} _lowerCamelCase : Dict = text_config _lowerCamelCase : int = vision_config return cls.from_dict(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: _lowerCamelCase : Union[str, Any] = copy.deepcopy(self.__dict__) _lowerCamelCase : Dict = self.text_config.to_dict() _lowerCamelCase : Any = self.vision_config.to_dict() _lowerCamelCase : Optional[int] = self.__class__.model_type return output class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ]) @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""logits_per_image""", {0: """batch"""}), ("""logits_per_text""", {0: """batch"""}), ("""text_embeds""", {0: """batch"""}), ("""image_embeds""", {0: """batch"""}), ]) @property def UpperCamelCase_ ( self) -> float: return 1e-4 def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = -1 , SCREAMING_SNAKE_CASE = -1 , SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: _lowerCamelCase : List[str] = super().generate_dummy_inputs( processor.tokenizer , batch_size=SCREAMING_SNAKE_CASE , seq_length=SCREAMING_SNAKE_CASE , framework=SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = super().generate_dummy_inputs( processor.image_processor , batch_size=SCREAMING_SNAKE_CASE , framework=SCREAMING_SNAKE_CASE) return {**text_input_dict, **image_input_dict} @property def UpperCamelCase_ ( self) -> int: return 14
88
"""simple docstring""" from datetime import datetime import matplotlib.pyplot as plt import torch def _snake_case ( __snake_case : List[str] ): """simple docstring""" for param in module.parameters(): _lowerCamelCase : Optional[Any] = False def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): _lowerCamelCase : Any = """mps""" if device == "mps": print( """WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch""" """ errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues""" """ with generations.""" ) return device def _snake_case ( __snake_case : Union[str, Any] ): """simple docstring""" _lowerCamelCase : int = plt.imshow(__snake_case ) fig.axes.get_xaxis().set_visible(__snake_case ) fig.axes.get_yaxis().set_visible(__snake_case ) plt.show() def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = datetime.now() _lowerCamelCase : Optional[Any] = current_time.strftime("""%H:%M:%S""" ) return timestamp
88
1
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys UpperCAmelCase = subprocess.check_output("""git merge-base main HEAD""".split()).decode("""utf-8""") UpperCAmelCase = ( subprocess.check_output(f'''git diff --diff-filter=d --name-only {fork_point_sha}'''.split()).decode("""utf-8""").split() ) UpperCAmelCase = """|""".join(sys.argv[1:]) UpperCAmelCase = re.compile(rf'''^({joined_dirs}).*?\.py$''') UpperCAmelCase = [x for x in modified_files if regex.match(x)] print(""" """.join(relevant_modified_files), end="""""")
88
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCAmelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""") @dataclass class lowercase__ : __UpperCAmelCase = field( default='''cifar10''' ,metadata={'''help''': '''Name of a dataset from the datasets package'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''The column name of the images in the files.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the training data.'''} ) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''A folder containing the validation data.'''} ) __UpperCAmelCase = field( default=0.1_5 ,metadata={'''help''': '''Percent to split off of train for validation.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } ,) def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : Any = {} if self.train_dir is not None: _lowerCamelCase : int = self.train_dir if self.validation_dir is not None: _lowerCamelCase : Tuple = self.validation_dir _lowerCamelCase : Optional[int] = data_files if data_files else None @dataclass class lowercase__ : __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } ,) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''} ) __UpperCAmelCase = field( default='''main''' ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} ,) __UpperCAmelCase = field(default=A_ ,metadata={'''help''': '''Name or path of preprocessor config.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } ,) __UpperCAmelCase = field( default=0.7_5 ,metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''} ) __UpperCAmelCase = field( default=A_ ,metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''} ) @dataclass class lowercase__ ( A_ ): __UpperCAmelCase = field( default=1e-3 ,metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''} ) def _snake_case ( __snake_case : Optional[Any] ): """simple docstring""" _lowerCamelCase : int = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): """simple docstring""" _lowerCamelCase : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Dict = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_mae""" , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _lowerCamelCase : Union[str, Any] = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. _lowerCamelCase : List[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _lowerCamelCase : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. _lowerCamelCase : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _lowerCamelCase : Tuple = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _lowerCamelCase : List[str] = ds["""train"""].train_test_split(data_args.train_val_split ) _lowerCamelCase : Union[str, Any] = split["""train"""] _lowerCamelCase : Optional[int] = split["""test"""] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _lowerCamelCase : str = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: _lowerCamelCase : Dict = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Union[str, Any] = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Optional[Any] = ViTMAEConfig() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) # adapt config config.update( { """mask_ratio""": model_args.mask_ratio, """norm_pix_loss""": model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _lowerCamelCase : str = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _lowerCamelCase : Dict = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _lowerCamelCase : Union[str, Any] = ViTImageProcessor() # create model if model_args.model_name_or_path: _lowerCamelCase : List[Any] = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _lowerCamelCase : Union[str, Any] = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _lowerCamelCase : List[Any] = ds["""train"""].column_names else: _lowerCamelCase : Union[str, Any] = ds["""validation"""].column_names if data_args.image_column_name is not None: _lowerCamelCase : str = data_args.image_column_name elif "image" in column_names: _lowerCamelCase : Optional[Any] = """image""" elif "img" in column_names: _lowerCamelCase : List[Any] = """img""" else: _lowerCamelCase : str = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _lowerCamelCase : Dict = image_processor.size["""shortest_edge"""] else: _lowerCamelCase : List[Any] = (image_processor.size["""height"""], image_processor.size["""width"""]) _lowerCamelCase : Tuple = Compose( [ Lambda(lambda __snake_case : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case : Optional[Any] ): _lowerCamelCase : Dict = [transforms(__snake_case ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: _lowerCamelCase : int = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: _lowerCamelCase : Union[str, Any] = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _lowerCamelCase : Optional[Any] = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _lowerCamelCase : Tuple = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _lowerCamelCase : Optional[Any] = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds["""train"""] if training_args.do_train else None , eval_dataset=ds["""validation"""] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _lowerCamelCase : Any = None if training_args.resume_from_checkpoint is not None: _lowerCamelCase : List[Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _lowerCamelCase : Union[str, Any] = last_checkpoint _lowerCamelCase : Optional[Any] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics("""train""" , train_result.metrics ) trainer.save_metrics("""train""" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _lowerCamelCase : int = trainer.evaluate() trainer.log_metrics("""eval""" , __snake_case ) trainer.save_metrics("""eval""" , __snake_case ) # Write model card and (optionally) push to hub _lowerCamelCase : Optional[Any] = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case : Dict ): """simple docstring""" main() if __name__ == "__main__": main()
88
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = {"""ctrl""": """https://huggingface.co/ctrl/resolve/main/config.json"""} class lowercase__ ( A_ ): __UpperCAmelCase = '''ctrl''' __UpperCAmelCase = ['''past_key_values'''] __UpperCAmelCase = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , SCREAMING_SNAKE_CASE=24_6534 , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=1280 , SCREAMING_SNAKE_CASE=8192 , SCREAMING_SNAKE_CASE=48 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=1e-6 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> List[str]: _lowerCamelCase : Dict = vocab_size _lowerCamelCase : Tuple = n_positions _lowerCamelCase : Tuple = n_embd _lowerCamelCase : List[Any] = n_layer _lowerCamelCase : Union[str, Any] = n_head _lowerCamelCase : Tuple = dff _lowerCamelCase : List[Any] = resid_pdrop _lowerCamelCase : Tuple = embd_pdrop _lowerCamelCase : Tuple = layer_norm_epsilon _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : str = use_cache super().__init__(**SCREAMING_SNAKE_CASE)
88
"""simple docstring""" import numpy as np def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def _snake_case ( __snake_case : np.ndarray ): """simple docstring""" return vector * sigmoid(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
88
1
"""simple docstring""" import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = False, False, False @dataclass class lowercase__ : __UpperCAmelCase = None __UpperCAmelCase = True __UpperCAmelCase = True __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "dict" __UpperCAmelCase = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) __UpperCAmelCase = field(default='''Audio''' ,init=A_ ,repr=A_ ) def __call__( self) -> Optional[int]: return self.pa_type def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> dict: try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("""To support encoding audio data, please install 'soundfile'.""") from err if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): return {"bytes": None, "path": value} elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes _lowerCamelCase : str = BytesIO() sf.write(SCREAMING_SNAKE_CASE , value["""array"""] , value["""sampling_rate"""] , format="""wav""") return {"bytes": buffer.getvalue(), "path": None} elif value.get("""path""") is not None and os.path.isfile(value["""path"""]): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("""pcm"""): # "PCM" only has raw audio bytes if value.get("""sampling_rate""") is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("""To use PCM files, please specify a 'sampling_rate' in Audio object""") if value.get("""bytes"""): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) _lowerCamelCase : Dict = np.frombuffer(value["""bytes"""] , dtype=np.intaa).astype(np.floataa) / 3_2767 else: _lowerCamelCase : Optional[Any] = np.memmap(value["""path"""] , dtype="""h""" , mode="""r""").astype(np.floataa) / 3_2767 _lowerCamelCase : List[Any] = BytesIO(bytes()) sf.write(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , value["""sampling_rate"""] , format="""wav""") return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("""path""")} elif value.get("""bytes""") is not None or value.get("""path""") is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("""bytes"""), "path": value.get("""path""")} else: raise ValueError( F'An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.') def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None) -> dict: if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Audio(decode=True) instead.""") _lowerCamelCase , _lowerCamelCase : Optional[Any] = (value["""path"""], BytesIO(value["""bytes"""])) if value["""bytes"""] is not None else (value["""path"""], None) if path is None and file is None: raise ValueError(F'An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.') try: import librosa import soundfile as sf except ImportError as err: raise ImportError("""To support decoding audio files, please install 'librosa' and 'soundfile'.""") from err _lowerCamelCase : List[Any] = xsplitext(SCREAMING_SNAKE_CASE)[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( """Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, """ """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( """Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, """ """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """) if file is None: _lowerCamelCase : List[Any] = token_per_repo_id or {} _lowerCamelCase : Dict = path.split("""::""")[-1] try: _lowerCamelCase : str = string_to_dict(SCREAMING_SNAKE_CASE , config.HUB_DATASETS_URL)["""repo_id"""] _lowerCamelCase : Tuple = token_per_repo_id[repo_id] except (ValueError, KeyError): _lowerCamelCase : Tuple = None with xopen(SCREAMING_SNAKE_CASE , """rb""" , use_auth_token=SCREAMING_SNAKE_CASE) as f: _lowerCamelCase , _lowerCamelCase : Dict = sf.read(SCREAMING_SNAKE_CASE) else: _lowerCamelCase , _lowerCamelCase : Tuple = sf.read(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = array.T if self.mono: _lowerCamelCase : Optional[int] = librosa.to_mono(SCREAMING_SNAKE_CASE) if self.sampling_rate and self.sampling_rate != sampling_rate: _lowerCamelCase : Optional[Any] = librosa.resample(SCREAMING_SNAKE_CASE , orig_sr=SCREAMING_SNAKE_CASE , target_sr=self.sampling_rate) _lowerCamelCase : Dict = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def UpperCamelCase_ ( self) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value if self.decode: raise ValueError("""Cannot flatten a decoded Audio feature.""") return { "bytes": Value("""binary"""), "path": Value("""string"""), } def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> pa.StructArray: if pa.types.is_string(storage.type): _lowerCamelCase : Dict = pa.array([None] * len(SCREAMING_SNAKE_CASE) , type=pa.binary()) _lowerCamelCase : Optional[Any] = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null()) elif pa.types.is_binary(storage.type): _lowerCamelCase : List[Any] = pa.array([None] * len(SCREAMING_SNAKE_CASE) , type=pa.string()) _lowerCamelCase : List[Any] = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null()) elif pa.types.is_struct(storage.type) and storage.type.get_all_field_indices("""array"""): _lowerCamelCase : List[Any] = pa.array([Audio().encode_example(SCREAMING_SNAKE_CASE) if x is not None else None for x in storage.to_pylist()]) elif pa.types.is_struct(storage.type): if storage.type.get_field_index("""bytes""") >= 0: _lowerCamelCase : Any = storage.field("""bytes""") else: _lowerCamelCase : List[Any] = pa.array([None] * len(SCREAMING_SNAKE_CASE) , type=pa.binary()) if storage.type.get_field_index("""path""") >= 0: _lowerCamelCase : List[Any] = storage.field("""path""") else: _lowerCamelCase : List[str] = pa.array([None] * len(SCREAMING_SNAKE_CASE) , type=pa.string()) _lowerCamelCase : Tuple = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null()) return array_cast(SCREAMING_SNAKE_CASE , self.pa_type) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(SCREAMING_SNAKE_CASE): with xopen(SCREAMING_SNAKE_CASE , """rb""") as f: _lowerCamelCase : int = f.read() return bytes_ _lowerCamelCase : Any = pa.array( [ (path_to_bytes(x["""path"""]) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) _lowerCamelCase : Tuple = pa.array( [os.path.basename(SCREAMING_SNAKE_CASE) if path is not None else None for path in storage.field("""path""").to_pylist()] , type=pa.string() , ) _lowerCamelCase : Optional[Any] = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null()) return array_cast(SCREAMING_SNAKE_CASE , self.pa_type)
88
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _snake_case ( ): """simple docstring""" _lowerCamelCase : Any = HfArgumentParser(__snake_case ) _lowerCamelCase : int = parser.parse_args_into_dataclasses()[0] _lowerCamelCase : Dict = TensorFlowBenchmark(args=__snake_case ) try: _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: _lowerCamelCase : Union[str, Any] = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" _lowerCamelCase : List[str] = """ """.join(str(__snake_case ).split(""" """ )[:-1] ) _lowerCamelCase : Dict = """""" _lowerCamelCase : List[Any] = eval(str(__snake_case ).split(""" """ )[-1] ) _lowerCamelCase : Tuple = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__snake_case ) if len(__snake_case ) > 0: _lowerCamelCase : Tuple = full_error_msg + begin_error_msg + str(__snake_case ) raise ValueError(__snake_case ) benchmark.run() if __name__ == "__main__": main()
88
1
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = Dict[str, Any] UpperCAmelCase = List[Prediction] @add_end_docstrings(A_ ) class lowercase__ ( A_ ): def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> int: super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) if self.framework == "tf": raise ValueError(F'The {self.__class__} is only available in PyTorch.') requires_backends(self , """vision""") self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items())) def UpperCamelCase_ ( self , **SCREAMING_SNAKE_CASE) -> Optional[Any]: _lowerCamelCase : int = {} if "threshold" in kwargs: _lowerCamelCase : List[Any] = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) -> Union[Predictions, List[Prediction]]: return super().__call__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> Optional[Any]: _lowerCamelCase : int = load_image(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = torch.IntTensor([[image.height, image.width]]) _lowerCamelCase : Dict = self.image_processor(images=[image] , return_tensors="""pt""") if self.tokenizer is not None: _lowerCamelCase : Union[str, Any] = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""") _lowerCamelCase : Optional[Any] = target_size return inputs def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> Union[str, Any]: _lowerCamelCase : int = model_inputs.pop("""target_size""") _lowerCamelCase : Optional[Any] = self.model(**SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = outputs.__class__({"""target_size""": target_size, **outputs}) if self.tokenizer is not None: _lowerCamelCase : Union[str, Any] = model_inputs["""bbox"""] return model_outputs def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0.9) -> List[str]: _lowerCamelCase : Tuple = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. _lowerCamelCase , _lowerCamelCase : Union[str, Any] = target_size[0].tolist() def unnormalize(SCREAMING_SNAKE_CASE): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ])) _lowerCamelCase , _lowerCamelCase : List[Any] = model_outputs["""logits"""].squeeze(0).softmax(dim=-1).max(dim=-1) _lowerCamelCase : int = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] _lowerCamelCase : Any = [unnormalize(SCREAMING_SNAKE_CASE) for bbox in model_outputs["""bbox"""].squeeze(0)] _lowerCamelCase : str = ["""score""", """label""", """box"""] _lowerCamelCase : Optional[Any] = [dict(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)) for vals in zip(scores.tolist() , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel _lowerCamelCase : Union[str, Any] = self.image_processor.post_process_object_detection(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : List[Any] = raw_annotations[0] _lowerCamelCase : Tuple = raw_annotation["""scores"""] _lowerCamelCase : int = raw_annotation["""labels"""] _lowerCamelCase : Any = raw_annotation["""boxes"""] _lowerCamelCase : str = scores.tolist() _lowerCamelCase : Any = [self.model.config.idalabel[label.item()] for label in labels] _lowerCamelCase : List[str] = [self._get_bounding_box(SCREAMING_SNAKE_CASE) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] _lowerCamelCase : Optional[int] = ["""score""", """label""", """box"""] _lowerCamelCase : Any = [ dict(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""]) ] return annotation def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE) -> Dict[str, int]: if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""") _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Tuple = box.int().tolist() _lowerCamelCase : List[Any] = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
88
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """kssteven/ibert-roberta-base""": """https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json""", """kssteven/ibert-roberta-large""": """https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json""", """kssteven/ibert-roberta-large-mnli""": ( """https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json""" ), } class lowercase__ ( A_ ): __UpperCAmelCase = '''ibert''' def __init__( self , SCREAMING_SNAKE_CASE=3_0522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE="absolute" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="none" , **SCREAMING_SNAKE_CASE , ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Dict = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : Tuple = attention_probs_dropout_prob _lowerCamelCase : Any = max_position_embeddings _lowerCamelCase : Dict = type_vocab_size _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : Dict = layer_norm_eps _lowerCamelCase : List[Any] = position_embedding_type _lowerCamelCase : Any = quant_mode _lowerCamelCase : List[str] = force_dequant class lowercase__ ( A_ ): @property def UpperCamelCase_ ( self) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _lowerCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _lowerCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
88
1