code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def A_ ( snake_case_ : Optional[int] ,snake_case_ : Optional[int] ,snake_case_ : List[Any]=[] ): '''simple docstring''' UpperCamelCase : List[str] = size[0] - overlap_pixels * 2 UpperCamelCase : Optional[Any] = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCamelCase : List[Any] = np.ones((size_y, size_x) ,dtype=np.uinta ) * 2_5_5 UpperCamelCase : Any = np.pad(snake_case_ ,mode="""linear_ramp""" ,pad_width=snake_case_ ,end_values=0 ) if "l" in remove_borders: UpperCamelCase : int = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCamelCase : List[str] = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCamelCase : Union[str, Any] = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCamelCase : List[str] = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def A_ ( snake_case_ : Tuple ,snake_case_ : Any ,snake_case_ : Optional[Any] ): '''simple docstring''' return max(snake_case_ ,min(snake_case_ ,snake_case_ ) ) def A_ ( snake_case_ : [int] ,snake_case_ : [int] ,snake_case_ : [int] ): '''simple docstring''' return ( clamp(rect[0] ,min[0] ,max[0] ), clamp(rect[1] ,min[1] ,max[1] ), clamp(rect[2] ,min[0] ,max[0] ), clamp(rect[3] ,min[1] ,max[1] ), ) def A_ ( snake_case_ : [int] ,snake_case_ : int ,snake_case_ : [int] ): '''simple docstring''' UpperCamelCase : int = list(snake_case_ ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCamelCase : List[str] = clamp_rect(snake_case_ ,[0, 0] ,[image_size[0], image_size[1]] ) return rect def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int] ,snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : int = Image.new("""RGB""" ,(tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) ,Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) ,(0, 0) ,) result.paste(snake_case_ ,(original_slice, 0) ) return result def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[str] = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCamelCase : int = tile.crop(snake_case_ ) return tile def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Union[str, Any] = n % d return n - divisor class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 350 , ): super().__init__( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , low_res_scheduler=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , max_noise_level=SCREAMING_SNAKE_CASE_ , ) def a_ ( 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_ ): torch.manual_seed(0 ) UpperCamelCase : Dict = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCamelCase : Optional[int] = add_overlap_rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , image.size ) UpperCamelCase : Optional[int] = image.crop(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCamelCase : int = translated_slice_x - (original_image_slice / 2) UpperCamelCase : List[str] = max(0 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = squeeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = to_input.size UpperCamelCase : List[Any] = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCamelCase : Optional[int] = super(SCREAMING_SNAKE_CASE_ , self ).__call__(image=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).images[0] UpperCamelCase : Optional[Any] = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCamelCase : int = unsqueeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCamelCase : List[Any] = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) UpperCamelCase : Optional[Any] = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=SCREAMING_SNAKE_CASE_ ) , mode="""L""" , ) final_image.paste( SCREAMING_SNAKE_CASE_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 75 , SCREAMING_SNAKE_CASE_ = 9.0 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 128 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 32 , ): UpperCamelCase : int = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) UpperCamelCase : Optional[Any] = math.ceil(image.size[0] / tile_size ) UpperCamelCase : Optional[int] = math.ceil(image.size[1] / tile_size ) UpperCamelCase : Tuple = tcx * tcy UpperCamelCase : Optional[Any] = 0 for y in range(SCREAMING_SNAKE_CASE_ ): for x in range(SCREAMING_SNAKE_CASE_ ): self._process_tile( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , noise_level=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def A_ ( ): '''simple docstring''' # Run a demo UpperCamelCase : int = """stabilityai/stable-diffusion-x4-upscaler""" UpperCamelCase : Union[str, Any] = StableDiffusionTiledUpscalePipeline.from_pretrained(snake_case_ ,revision="""fp16""" ,torch_dtype=torch.floataa ) UpperCamelCase : Any = pipe.to("""cuda""" ) UpperCamelCase : List[Any] = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(snake_case_ : Any ): print(f'progress: {obj["progress"]:.4f}' ) obj["image"].save("""diffusers_library_progress.jpg""" ) UpperCamelCase : Optional[int] = pipe(image=snake_case_ ,prompt="""Black font, white background, vector""" ,noise_level=4_0 ,callback=snake_case_ ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
27
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : Any = use_input_lengths UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = gelu_activation UpperCamelCase : Dict = sinusoidal_embeddings UpperCamelCase : Optional[int] = causal UpperCamelCase : List[Any] = asm UpperCamelCase : int = n_langs UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = n_special UpperCamelCase : Dict = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : List[str] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[str] = scope UpperCamelCase : Dict = bos_token_id def a_ ( self ): UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Union[str, Any] = None if self.use_input_lengths: UpperCamelCase : str = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[str] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a_ ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def a_ ( 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_ , ): UpperCamelCase : Optional[int] = XLMModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , lengths=SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( 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_ , ): UpperCamelCase : Optional[Any] = XLMWithLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( 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_ , ): UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( 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_ , ): UpperCamelCase : int = XLMForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , p_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , ) ((UpperCamelCase) , ) : Union[str, Any] = result_with_labels.to_tuple() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , ) : Tuple = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def a_ ( 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_ , ): UpperCamelCase : Union[str, Any] = XLMForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( 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_ , ): UpperCamelCase : int = self.num_labels UpperCamelCase : int = XLMForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : 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.num_labels) ) def a_ ( 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_ , ): UpperCamelCase : List[Any] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[Any] = config_and_inputs UpperCamelCase : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase : Optional[Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) return inputs_dict def a_ ( self ): UpperCamelCase : List[Any] = XLMModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , emb_dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_attentions in attentions] , [True] * len(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : Tuple = min_length + idx + 1 UpperCamelCase : Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_hidden_states in hidden_states] , [True] * len(SCREAMING_SNAKE_CASE_ ) , ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : List[str] = min_length + idx + 1 UpperCamelCase : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) , ) pass @slow def a_ ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = XLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Dict = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # the president UpperCamelCase : List[Any] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def A_ ( snake_case_ : List[str] ,snake_case_ : str=None ): '''simple docstring''' UpperCamelCase : List[str] = None if token is not None: UpperCamelCase : Any = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'Bearer {token}'} UpperCamelCase : List[str] = f'https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100' UpperCamelCase : Optional[Any] = requests.get(snake_case_ ,headers=snake_case_ ).json() UpperCamelCase : List[Any] = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) UpperCamelCase : List[Any] = math.ceil((result["""total_count"""] - 1_0_0) / 1_0_0 ) for i in range(snake_case_ ): UpperCamelCase : List[Any] = requests.get(url + f'&page={i + 2}' ,headers=snake_case_ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f'Unknown error, could not fetch links:\n{traceback.format_exc()}' ) return {} def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : List[str]=None ): '''simple docstring''' UpperCamelCase : Optional[Any] = None if token is not None: UpperCamelCase : List[str] = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'Bearer {token}'} UpperCamelCase : Optional[int] = f'https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100' UpperCamelCase : Optional[int] = requests.get(snake_case_ ,headers=snake_case_ ).json() UpperCamelCase : Any = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) UpperCamelCase : Optional[int] = math.ceil((result["""total_count"""] - 1_0_0) / 1_0_0 ) for i in range(snake_case_ ): UpperCamelCase : Tuple = requests.get(url + f'&page={i + 2}' ,headers=snake_case_ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f'Unknown error, could not fetch links:\n{traceback.format_exc()}' ) return {} def A_ ( snake_case_ : Dict ,snake_case_ : Dict ,snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : int = None if token is not None: UpperCamelCase : int = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'Bearer {token}'} UpperCamelCase : int = requests.get(snake_case_ ,headers=snake_case_ ,allow_redirects=snake_case_ ) UpperCamelCase : Optional[Any] = result.headers["""Location"""] UpperCamelCase : Dict = requests.get(snake_case_ ,allow_redirects=snake_case_ ) UpperCamelCase : List[Any] = os.path.join(snake_case_ ,f'{artifact_name}.zip' ) with open(snake_case_ ,"""wb""" ) as fp: fp.write(response.content ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : List[str]=None ): '''simple docstring''' UpperCamelCase : Dict = [] UpperCamelCase : Optional[int] = [] UpperCamelCase : List[Any] = None with zipfile.ZipFile(snake_case_ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case_ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(snake_case_ ) as f: for line in f: UpperCamelCase : Union[str, Any] = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs UpperCamelCase : Union[str, Any] = line[: line.index(""": """ )] UpperCamelCase : Optional[int] = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed UpperCamelCase : str = line[len("""FAILED """ ) :] failed_tests.append(snake_case_ ) elif filename == "job_name.txt": UpperCamelCase : int = line if len(snake_case_ ) != len(snake_case_ ): raise ValueError( f'`errors` and `failed_tests` should have the same number of elements. Got {len(snake_case_ )} for `errors` ' f'and {len(snake_case_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some' """ problem.""" ) UpperCamelCase : Any = None if job_name and job_links: UpperCamelCase : List[str] = job_links.get(snake_case_ ,snake_case_ ) # A list with elements of the form (line of error, error, failed test) UpperCamelCase : Any = [x + [y] + [job_link] for x, y in zip(snake_case_ ,snake_case_ )] return result def A_ ( snake_case_ : List[str] ,snake_case_ : Tuple=None ): '''simple docstring''' UpperCamelCase : Optional[int] = [] UpperCamelCase : Optional[int] = [os.path.join(snake_case_ ,snake_case_ ) for p in os.listdir(snake_case_ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(snake_case_ ,job_links=snake_case_ ) ) return errors def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Optional[Any]=None ): '''simple docstring''' UpperCamelCase : Union[str, Any] = Counter() counter.update([x[1] for x in logs] ) UpperCamelCase : str = counter.most_common() UpperCamelCase : Dict = {} for error, count in counts: if error_filter is None or error not in error_filter: UpperCamelCase : Tuple = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} UpperCamelCase : Tuple = dict(sorted(r.items() ,key=lambda snake_case_ : item[1]["count"] ,reverse=snake_case_ ) ) return r def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Optional[Any] = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): UpperCamelCase : List[str] = test.split("""/""" )[2] else: UpperCamelCase : Optional[Any] = None return test def A_ ( snake_case_ : Tuple ,snake_case_ : List[str]=None ): '''simple docstring''' UpperCamelCase : List[str] = [(x[0], x[1], get_model(x[2] )) for x in logs] UpperCamelCase : str = [x for x in logs if x[2] is not None] UpperCamelCase : Optional[int] = {x[2] for x in logs} UpperCamelCase : int = {} for test in tests: UpperCamelCase : List[str] = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) UpperCamelCase : Union[str, Any] = counter.most_common() UpperCamelCase : List[Any] = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} UpperCamelCase : Union[str, Any] = sum(error_counts.values() ) if n_errors > 0: UpperCamelCase : List[Any] = {"""count""": n_errors, """errors""": error_counts} UpperCamelCase : str = dict(sorted(r.items() ,key=lambda snake_case_ : item[1]["count"] ,reverse=snake_case_ ) ) return r def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : Union[str, Any] = """| no. | error | status |""" UpperCamelCase : Any = """|-:|:-|:-|""" UpperCamelCase : Optional[Any] = [header, sep] for error in reduced_by_error: UpperCamelCase : Optional[Any] = reduced_by_error[error]["""count"""] UpperCamelCase : List[str] = f'| {count} | {error[:1_0_0]} | |' lines.append(snake_case_ ) return "\n".join(snake_case_ ) def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : int = """| model | no. of errors | major error | count |""" UpperCamelCase : Union[str, Any] = """|-:|-:|-:|-:|""" UpperCamelCase : int = [header, sep] for model in reduced_by_model: UpperCamelCase : Tuple = reduced_by_model[model]["""count"""] UpperCamelCase , UpperCamelCase : List[Any] = list(reduced_by_model[model]["""errors"""].items() )[0] UpperCamelCase : Optional[int] = f'| {model} | {count} | {error[:6_0]} | {_count} |' lines.append(snake_case_ ) return "\n".join(snake_case_ ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() # Required parameters parser.add_argument('''--workflow_run_id''', type=str, required=True, help='''A GitHub Actions workflow run id.''') parser.add_argument( '''--output_dir''', type=str, required=True, help='''Where to store the downloaded artifacts and other result files.''', ) parser.add_argument('''--token''', default=None, type=str, help='''A token that has actions:read permission.''') __A : Tuple = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) __A : Any = get_job_links(args.workflow_run_id, token=args.token) __A : int = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: __A : List[Any] = k.find(''' / ''') __A : Tuple = k[index + len(''' / ''') :] __A : Any = v with open(os.path.join(args.output_dir, '''job_links.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) __A : Any = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, '''artifacts.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) __A : Optional[int] = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error __A : Any = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors __A : Dict = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, '''errors.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) __A : str = reduce_by_error(errors) __A : str = reduce_by_model(errors) __A : List[Any] = make_github_table(reduced_by_error) __A : Tuple = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, '''reduced_by_error.txt'''), '''w''', encoding='''UTF-8''') as fp: fp.write(sa) with open(os.path.join(args.output_dir, '''reduced_by_model.txt'''), '''w''', encoding='''UTF-8''') as fp: fp.write(sa)
27
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
1
"""simple docstring""" import numpy as np import qiskit def A_ ( snake_case_ : int = 8 ,snake_case_ : int | None = None ): '''simple docstring''' UpperCamelCase : Dict = np.random.default_rng(seed=snake_case_ ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. UpperCamelCase : str = 6 * key_len # Measurement basis for Alice's qubits. UpperCamelCase : Union[str, Any] = rng.integers(2 ,size=snake_case_ ) # The set of states Alice will prepare. UpperCamelCase : int = rng.integers(2 ,size=snake_case_ ) # Measurement basis for Bob's qubits. UpperCamelCase : str = rng.integers(2 ,size=snake_case_ ) # Quantum Circuit to simulate BB84 UpperCamelCase : str = qiskit.QuantumCircuit(snake_case_ ,name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(snake_case_ ): if alice_state[index] == 1: bbaa_circ.x(snake_case_ ) if alice_basis[index] == 1: bbaa_circ.h(snake_case_ ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(snake_case_ ): if bob_basis[index] == 1: bbaa_circ.h(snake_case_ ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. UpperCamelCase : List[Any] = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. UpperCamelCase : Union[str, Any] = qiskit.execute(snake_case_ ,snake_case_ ,shots=1 ,seed_simulator=snake_case_ ) # Returns the result of measurement. UpperCamelCase : List[Any] = job.result().get_counts(snake_case_ ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. UpperCamelCase : Optional[int] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( snake_case_ ,snake_case_ ,snake_case_ ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. UpperCamelCase : Union[str, Any] = gen_key[:key_len] if len(snake_case_ ) >= key_len else gen_key.ljust(snake_case_ ,"""0""" ) return key if __name__ == "__main__": print(F'''The generated key is : {bbaa(8, seed=0)}''') from doctest import testmod testmod()
27
"""simple docstring""" import torch from transformers import AutoModel class lowerCamelCase ( torch.nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_="sayef/fsner-bert-base-uncased" ): super(SCREAMING_SNAKE_CASE_ , self ).__init__() UpperCamelCase : int = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.nn.CosineSimilarity(3 , 1e-08 ) UpperCamelCase : Any = torch.nn.Softmax(dim=1 ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return self.bert(**SCREAMING_SNAKE_CASE_ ).last_hidden_state def a_ ( self , SCREAMING_SNAKE_CASE_ ): return token_embeddings.sum(2 , keepdim=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 ): return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = W_supports["""sizes"""].tolist() UpperCamelCase : List[str] = W_supports["""start_token_id"""].item() UpperCamelCase : List[Any] = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase : List[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = W_supports["""input_ids"""] == start_token_id UpperCamelCase : Optional[Any] = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: UpperCamelCase : int = 0 else: UpperCamelCase : Optional[int] = support_sizes[i - 1] UpperCamelCase : Tuple = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase : int = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase : Tuple = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase : List[str] = torch.vstack((p_starts, p_start) ) UpperCamelCase : Optional[Any] = torch.vstack((p_ends, p_end) ) else: UpperCamelCase : Optional[int] = p_start UpperCamelCase : Tuple = p_end return p_starts, p_ends
27
1
"""simple docstring""" import os import re 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 __A : str = logging.get_logger(__name__) __A : List[str] = {'''vocab_file''': '''spiece.model'''} __A : List[Any] = { '''vocab_file''': { '''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model''', '''google/bigbird-roberta-large''': ( '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model''' ), '''google/bigbird-base-trivia-itc''': ( '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model''' ), } } __A : List[str] = { '''google/bigbird-roberta-base''': 4096, '''google/bigbird-roberta-large''': 4096, '''google/bigbird-base-trivia-itc''': 4096, } class lowerCamelCase ( _UpperCAmelCase ): lowercase : int = VOCAB_FILES_NAMES lowercase : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP lowercase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : List[str] = ['input_ids', 'attention_mask'] lowercase : List[int] = [] def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="[MASK]" , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[Any] = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else bos_token UpperCamelCase : Any = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else eos_token UpperCamelCase : Optional[int] = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else unk_token UpperCamelCase : int = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else pad_token UpperCamelCase : Dict = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else cls_token UpperCamelCase : Optional[int] = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it UpperCamelCase : Optional[int] = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token UpperCamelCase : str = {} 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_ , pad_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = vocab_file UpperCamelCase : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE_ ) @property def a_ ( self ): return self.sp_model.get_piece_size() def a_ ( self ): UpperCamelCase : Any = {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 __getstate__( self ): UpperCamelCase : Dict = self.__dict__.copy() UpperCamelCase : List[str] = None return state def __setstate__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): UpperCamelCase : Optional[Any] = {} UpperCamelCase : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.sp_model.encode(SCREAMING_SNAKE_CASE_ , out_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE_ ) return token def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = [] UpperCamelCase : Dict = """""" UpperCamelCase : Tuple = 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 UpperCamelCase : List[str] = True UpperCamelCase : str = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE_ ) return out_string.strip() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = True , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = kwargs.pop("""use_source_tokenizer""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 UpperCamelCase : Dict = [] UpperCamelCase : Union[str, Any] = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Any = [] sub_texts.append(SCREAMING_SNAKE_CASE_ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE_ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: UpperCamelCase : List[Any] = re.sub(r""" (\[(MASK|SEP)\])""" , r"""\1""" , """ """.join(SCREAMING_SNAKE_CASE_ ) ) else: UpperCamelCase : int = """""".join(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: UpperCamelCase : Union[str, Any] = self.clean_up_tokenization(SCREAMING_SNAKE_CASE_ ) return clean_text else: return text def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase : Optional[int] = 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: UpperCamelCase : Dict = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE_ ) return (out_vocab_file,) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCamelCase : Optional[int] = [self.cls_token_id] UpperCamelCase : Tuple = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): 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] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = [self.sep_token_id] UpperCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
27
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline __A : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): 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_ = 100 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = True , ): if audio_length_in_s is None: UpperCamelCase : Any = self.unet.config.sample_size / self.unet.config.sample_rate UpperCamelCase : int = audio_length_in_s * self.unet.config.sample_rate UpperCamelCase : Dict = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( f'{audio_length_in_s} is too small. Make sure it\'s bigger or equal to' f' {3 * down_scale_factor / self.unet.config.sample_rate}.' ) UpperCamelCase : Dict = int(SCREAMING_SNAKE_CASE_ ) if sample_size % down_scale_factor != 0: UpperCamelCase : Dict = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( f'{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled' f' by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising' """ process.""" ) UpperCamelCase : List[Any] = int(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = next(iter(self.unet.parameters() ) ).dtype UpperCamelCase : int = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size: raise ValueError( f'You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE_ )}, but requested an effective batch' f' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) UpperCamelCase : Optional[int] = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=audio.device ) UpperCamelCase : Optional[Any] = self.scheduler.timesteps.to(SCREAMING_SNAKE_CASE_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output UpperCamelCase : Dict = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # 2. compute previous image: x_t -> t_t-1 UpperCamelCase : Optional[Any] = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase : Any = audio.clamp(-1 , 1 ).float().cpu().numpy() UpperCamelCase : Dict = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
1
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : str = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
27
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
1
"""simple docstring""" import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class lowerCamelCase : 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_=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_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase : Dict = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[int] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Optional[Any] = use_token_type_ids UpperCamelCase : Any = use_input_mask UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = use_mc_token_ids UpperCamelCase : List[str] = vocab_size UpperCamelCase : int = hidden_size UpperCamelCase : Optional[int] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : Union[str, Any] = hidden_act UpperCamelCase : Optional[int] = hidden_dropout_prob UpperCamelCase : List[Any] = attention_probs_dropout_prob UpperCamelCase : Optional[int] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : List[Any] = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : int = num_labels UpperCamelCase : str = num_choices UpperCamelCase : int = scope UpperCamelCase : Any = self.vocab_size - 1 def a_ ( self ): UpperCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None if self.use_token_type_ids: UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : Optional[int] = None if self.use_mc_token_ids: UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) UpperCamelCase : str = None UpperCamelCase : List[Any] = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Any = self.get_config() UpperCamelCase : Union[str, Any] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def a_ ( self ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = CTRLModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , head_mask=SCREAMING_SNAKE_CASE_ ) model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = CTRLLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self ): UpperCamelCase : str = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Optional[Any] = config_and_inputs UpperCamelCase : Optional[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask} return config, inputs_dict def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : List[Any] = CTRLForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : List[str] = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () lowercase : str = (CTRLLMHeadModel,) if is_torch_available() else () lowercase : List[Any] = ( { 'feature-extraction': CTRLModel, 'text-classification': CTRLForSequenceClassification, 'text-generation': CTRLLMHeadModel, 'zero-shot': CTRLForSequenceClassification, } if is_torch_available() else {} ) lowercase : Optional[int] = True lowercase : Dict = False lowercase : List[str] = False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def a_ ( self ): UpperCamelCase : List[Any] = CTRLModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , n_embd=37 ) def a_ ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE_ ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def a_ ( self ): pass @slow def a_ ( self ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : List[Any] = CTRLModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @unittest.skip("""The model doesn't support left padding""" ) # and it's not used enough to be worth fixing :) def a_ ( self ): pass @require_torch class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def a_ ( self ): UpperCamelCase : Tuple = CTRLLMHeadModel.from_pretrained("""ctrl""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor( [[1_1859, 0, 1611, 8]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # Legal the president is UpperCamelCase : Any = [ 1_1859, 0, 1611, 8, 5, 150, 2_6449, 2, 19, 348, 469, 3, 2595, 48, 2_0740, 24_6533, 24_6533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a UpperCamelCase : Union[str, Any] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].tolist() , SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = AudioLDMPipeline lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS lowercase : Tuple = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Tuple = 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, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCamelCase : int = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) UpperCamelCase : Optional[int] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) UpperCamelCase : Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Any = self.get_dummy_components() UpperCamelCase : int = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Tuple = audio[:10] UpperCamelCase : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[str] = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) UpperCamelCase : Tuple = prompt_embeds # forward UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_components() UpperCamelCase : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * ["""this is a negative prompt"""] UpperCamelCase : List[Any] = negative_prompt UpperCamelCase : str = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : str = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[Any] = [] for p in [prompt, negative_prompt]: UpperCamelCase : int = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Union[str, Any] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = text_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Tuple = embeds # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Optional[int] = self.get_dummy_components() UpperCamelCase : List[str] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """egg cracking""" UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Union[str, Any] = audio[:10] UpperCamelCase : Dict = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Union[str, Any] = self.get_dummy_components() UpperCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) UpperCamelCase : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts UpperCamelCase : Dict = 2 UpperCamelCase : List[str] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt UpperCamelCase : List[str] = 2 UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts UpperCamelCase : Any = 2 UpperCamelCase : str = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config.sampling_rate UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 UpperCamelCase : Optional[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = ["""hey"""] UpperCamelCase : Dict = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : str = output.audios.shape assert audio_shape == (1, 256) UpperCamelCase : Optional[Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 UpperCamelCase : str = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : List[str] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) UpperCamelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def a_ ( self ): UpperCamelCase : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 25 UpperCamelCase : Optional[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[7_7230:7_7240] UpperCamelCase : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) UpperCamelCase : Any = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def a_ ( self ): UpperCamelCase : Any = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) UpperCamelCase : str = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[2_7780:2_7790] UpperCamelCase : Tuple = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) UpperCamelCase : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
27
1
"""simple docstring""" from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : int = int(number**0.5 ) return number == sq * sq def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : int ,snake_case_ : int ,snake_case_ : int ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den UpperCamelCase : int = x_den * y_den * z_den UpperCamelCase : int = gcd(snake_case_ ,snake_case_ ) top //= hcf bottom //= hcf return top, bottom def A_ ( snake_case_ : int = 3_5 ): '''simple docstring''' UpperCamelCase : set = set() UpperCamelCase : int UpperCamelCase : Fraction = Fraction(0 ) UpperCamelCase : tuple[int, int] for x_num in range(1 ,order + 1 ): for x_den in range(x_num + 1 ,order + 1 ): for y_num in range(1 ,order + 1 ): for y_den in range(y_num + 1 ,order + 1 ): # n=1 UpperCamelCase : Union[str, Any] = x_num * y_den + x_den * y_num UpperCamelCase : Any = x_den * y_den UpperCamelCase : List[str] = gcd(snake_case_ ,snake_case_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase : Union[str, Any] = add_three( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) unique_s.add(snake_case_ ) # n=2 UpperCamelCase : str = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) UpperCamelCase : int = x_den * x_den * y_den * y_den if is_sq(snake_case_ ) and is_sq(snake_case_ ): UpperCamelCase : Optional[Any] = int(sqrt(snake_case_ ) ) UpperCamelCase : int = int(sqrt(snake_case_ ) ) UpperCamelCase : Optional[int] = gcd(snake_case_ ,snake_case_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase : Union[str, Any] = add_three( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) unique_s.add(snake_case_ ) # n=-1 UpperCamelCase : Optional[Any] = x_num * y_num UpperCamelCase : Any = x_den * y_num + x_num * y_den UpperCamelCase : Optional[Any] = gcd(snake_case_ ,snake_case_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase : List[str] = add_three( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) unique_s.add(snake_case_ ) # n=2 UpperCamelCase : Union[str, Any] = x_num * x_num * y_num * y_num UpperCamelCase : List[Any] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(snake_case_ ) and is_sq(snake_case_ ): UpperCamelCase : List[str] = int(sqrt(snake_case_ ) ) UpperCamelCase : List[str] = int(sqrt(snake_case_ ) ) UpperCamelCase : str = gcd(snake_case_ ,snake_case_ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase : Optional[Any] = add_three( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) unique_s.add(snake_case_ ) for num, den in unique_s: total += Fraction(snake_case_ ,snake_case_ ) return total.denominator + total.numerator if __name__ == "__main__": print(F'''{solution() = }''')
27
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' # load dataset UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __A : Any = logging.get_logger(__name__) class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = True , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : Any = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = do_resize UpperCamelCase : Optional[int] = size UpperCamelCase : List[str] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Any = rescale_factor UpperCamelCase : Tuple = do_normalize UpperCamelCase : List[str] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase : str = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase : Any = do_convert_rgb def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}' ) UpperCamelCase : Any = (size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( 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_ = 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_ , ): UpperCamelCase : Any = do_resize if do_resize is not None else self.do_resize UpperCamelCase : str = resample if resample is not None else self.resample UpperCamelCase : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : int = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : List[str] = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : Any = image_std if image_std is not None else self.image_std UpperCamelCase : Optional[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase : Optional[int] = size if size is not None else self.size UpperCamelCase : Any = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : 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_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase : Optional[Any] = [convert_to_rgb(SCREAMING_SNAKE_CASE_ ) for image in images] # All transformations expect numpy arrays. UpperCamelCase : Any = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Optional[int] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : str = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : int = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Optional[Any] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : List[str] = BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE_ ) return encoded_outputs
27
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : str = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
27
1
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
27
1
"""simple docstring""" import warnings 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 lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = ['image_processor', 'tokenizer'] lowercase : int = 'FlavaImageProcessor' lowercase : Optional[Any] = ('BertTokenizer', 'BertTokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = kwargs.pop("""feature_extractor""" ) UpperCamelCase : Optional[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : 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_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , 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_ = True , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: UpperCamelCase : 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_token_type_ids=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_length=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) if images is not None: UpperCamelCase : Optional[Any] = self.image_processor( SCREAMING_SNAKE_CASE_ , return_image_mask=SCREAMING_SNAKE_CASE_ , return_codebook_pixels=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) if text is not None and images is not None: encoding.update(SCREAMING_SNAKE_CASE_ ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**SCREAMING_SNAKE_CASE_ ) , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def a_ ( self ): UpperCamelCase : Dict = self.tokenizer.model_input_names UpperCamelCase : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def a_ ( self ): warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , SCREAMING_SNAKE_CASE_ , ) return self.image_processor_class @property def a_ ( self ): warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , SCREAMING_SNAKE_CASE_ , ) return self.image_processor
27
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCamelCase ( _UpperCAmelCase ): 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_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Union[str, Any] = use_token_type_ids UpperCamelCase : Dict = use_labels UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : str = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : int = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Dict = num_labels UpperCamelCase : Tuple = num_choices UpperCamelCase : Optional[int] = scope UpperCamelCase : List[Any] = q_groups UpperCamelCase : Tuple = k_groups UpperCamelCase : Any = v_groups UpperCamelCase : List[str] = post_attention_groups UpperCamelCase : Tuple = intermediate_groups UpperCamelCase : int = output_groups def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = SqueezeBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = SqueezeBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = 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 a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = SqueezeBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : str = SqueezeBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = 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.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = SqueezeBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = config_and_inputs UpperCamelCase : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase : Dict = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : str = True lowercase : str = False def a_ ( self ): UpperCamelCase : Any = SqueezeBertModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = SqueezeBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) UpperCamelCase : Dict = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
1
"""simple docstring""" import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 __A : Union[str, Any] = { '''return_dict''': False, '''output_hidden_states''': True, '''output_attentions''': True, '''torchscript''': True, '''torch_dtype''': '''float16''', '''use_bfloat16''': True, '''tf_legacy_loss''': True, '''pruned_heads''': {'''a''': 1}, '''tie_word_embeddings''': False, '''is_decoder''': True, '''cross_attention_hidden_size''': 128, '''add_cross_attention''': True, '''tie_encoder_decoder''': True, '''max_length''': 50, '''min_length''': 3, '''do_sample''': True, '''early_stopping''': True, '''num_beams''': 3, '''num_beam_groups''': 3, '''diversity_penalty''': 0.5, '''temperature''': 2.0, '''top_k''': 10, '''top_p''': 0.7, '''typical_p''': 0.2, '''repetition_penalty''': 0.8, '''length_penalty''': 0.8, '''no_repeat_ngram_size''': 5, '''encoder_no_repeat_ngram_size''': 5, '''bad_words_ids''': [1, 2, 3], '''num_return_sequences''': 3, '''chunk_size_feed_forward''': 5, '''output_scores''': True, '''return_dict_in_generate''': True, '''forced_bos_token_id''': 2, '''forced_eos_token_id''': 3, '''remove_invalid_values''': True, '''architectures''': ['''BertModel'''], '''finetuning_task''': '''translation''', '''id2label''': {0: '''label'''}, '''label2id''': {'''label''': '''0'''}, '''tokenizer_class''': '''BertTokenizerFast''', '''prefix''': '''prefix''', '''bos_token_id''': 6, '''pad_token_id''': 7, '''eos_token_id''': 8, '''sep_token_id''': 9, '''decoder_start_token_id''': 10, '''exponential_decay_length_penalty''': (5, 1.01), '''suppress_tokens''': [0, 1], '''begin_suppress_tokens''': 2, '''task_specific_params''': {'''translation''': '''some_params'''}, '''problem_type''': '''regression''', } @is_staging_test class lowerCamelCase ( unittest.TestCase ): @classmethod def a_ ( cls ): UpperCamelCase : List[Any] = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def a_ ( cls ): try: delete_repo(token=cls._token , repo_id="""test-config""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-config-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-config""" ) except HTTPError: pass def a_ ( self ): UpperCamelCase : Any = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("""test-config""" , use_auth_token=self._token ) UpperCamelCase : str = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id="""test-config""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ , repo_id="""test-config""" , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase : Optional[int] = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): UpperCamelCase : int = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("""valid_org/test-config-org""" , use_auth_token=self._token ) UpperCamelCase : Optional[int] = BertConfig.from_pretrained("""valid_org/test-config-org""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-config-org""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id="""valid_org/test-config-org""" , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase : Union[str, Any] = BertConfig.from_pretrained("""valid_org/test-config-org""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): CustomConfig.register_for_auto_class() UpperCamelCase : Any = CustomConfig(attribute=42 ) config.push_to_hub("""test-dynamic-config""" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"""AutoConfig""": """custom_configuration.CustomConfig"""} ) UpperCamelCase : Dict = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=SCREAMING_SNAKE_CASE_ ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , """CustomConfig""" ) self.assertEqual(new_config.attribute , 42 ) class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : str = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated UpperCamelCase : Dict = c.n_embd + 1 # int UpperCamelCase : Dict = c.resid_pdrop + 1.0 # float UpperCamelCase : Union[str, Any] = not c.scale_attn_weights # bool UpperCamelCase : Tuple = c.summary_type + """foo""" # str c.update_from_string( f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' ) self.assertEqual(SCREAMING_SNAKE_CASE_ , c.n_embd , """mismatch for key: n_embd""" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , c.resid_pdrop , """mismatch for key: resid_pdrop""" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , c.scale_attn_weights , """mismatch for key: scale_attn_weights""" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , c.summary_type , """mismatch for key: summary_type""" ) def a_ ( self ): UpperCamelCase : Union[str, Any] = PretrainedConfig() UpperCamelCase : int = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( SCREAMING_SNAKE_CASE_ , ["""is_encoder_decoder""", """_name_or_path""", """_commit_hash""", """transformers_version"""] ) UpperCamelCase : Tuple = [key for key, value in config_common_kwargs.items() if value == getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )] if len(SCREAMING_SNAKE_CASE_ ) > 0: raise ValueError( """The following keys are set with the default values in""" """ `test_configuration_common.config_common_kwargs` pick another value for them:""" f' {", ".join(SCREAMING_SNAKE_CASE_ )}.' ) def a_ ( self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): # config is in subfolder, the following should not work without specifying the subfolder UpperCamelCase : List[Any] = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert-subfolder""" ) UpperCamelCase : Dict = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert-subfolder""" , subfolder="""bert""" ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): # A mock response for an HTTP head request to emulate server down UpperCamelCase : str = mock.Mock() UpperCamelCase : Union[str, Any] = 500 UpperCamelCase : Optional[int] = {} UpperCamelCase : List[Any] = HTTPError UpperCamelCase : Union[str, Any] = {} # Download this model to make sure it's in the cache. UpperCamelCase : Optional[Any] = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("""requests.Session.request""" , return_value=SCREAMING_SNAKE_CASE_ ) as mock_head: UpperCamelCase : Tuple = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) # This check we did call the fake head request mock_head.assert_called() def a_ ( self ): # This test is for deprecated behavior and can be removed in v5 UpperCamelCase : int = BertConfig.from_pretrained( """https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json""" ) def a_ ( self ): UpperCamelCase : Union[str, Any] = AutoConfig.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[Any] = ["""config.4.0.0.json"""] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 2 json.dump(configuration.to_dict() , open(os.path.join(SCREAMING_SNAKE_CASE_ , """config.4.0.0.json""" ) , """w""" ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 UpperCamelCase : Union[str, Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 UpperCamelCase : List[Any] = ["""config.42.0.0.json"""] UpperCamelCase : Optional[int] = 768 configuration.save_pretrained(SCREAMING_SNAKE_CASE_ ) shutil.move(os.path.join(SCREAMING_SNAKE_CASE_ , """config.4.0.0.json""" ) , os.path.join(SCREAMING_SNAKE_CASE_ , """config.42.0.0.json""" ) ) UpperCamelCase : List[str] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertEqual(new_configuration.hidden_size , 768 ) def a_ ( self ): # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. UpperCamelCase : List[Any] = """hf-internal-testing/test-two-configs""" import transformers as new_transformers UpperCamelCase : Optional[Any] = """v4.0.0""" UpperCamelCase , UpperCamelCase : Union[str, Any] = new_transformers.models.auto.AutoConfig.from_pretrained( SCREAMING_SNAKE_CASE_ , return_unused_kwargs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(SCREAMING_SNAKE_CASE_ , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers UpperCamelCase : Dict = """v3.0.0""" UpperCamelCase : int = old_transformers.models.auto.AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertEqual(old_configuration.hidden_size , 768 )
27
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __A : List[Any] = '''%20'''.join(argv[1:]) if len(argv) > 1 else quote(str(input('''Search: '''))) print('''Googling.....''') __A : Optional[Any] = F'''https://www.google.com/search?q={query}&num=100''' __A : Optional[int] = requests.get( url, headers={'''User-Agent''': str(UserAgent().random)}, ) try: __A : Optional[int] = ( BeautifulSoup(res.text, '''html.parser''') .find('''div''', attrs={'''class''': '''yuRUbf'''}) .find('''a''') .get('''href''') ) except AttributeError: __A : str = parse_qs( BeautifulSoup(res.text, '''html.parser''') .find('''div''', attrs={'''class''': '''kCrYT'''}) .find('''a''') .get('''href''') )['''url'''][0] webbrowser.open(link)
27
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Optional[int] = { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = 'mvp' lowercase : Optional[Any] = ['past_key_values'] lowercase : Union[str, Any] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , SCREAMING_SNAKE_CASE_=5_0267 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=800 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Dict = max_position_embeddings UpperCamelCase : Optional[int] = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : Any = encoder_layers UpperCamelCase : List[Any] = encoder_attention_heads UpperCamelCase : Optional[Any] = decoder_ffn_dim UpperCamelCase : Optional[int] = decoder_layers UpperCamelCase : Dict = decoder_attention_heads UpperCamelCase : List[str] = dropout UpperCamelCase : List[str] = attention_dropout UpperCamelCase : List[Any] = activation_dropout UpperCamelCase : Dict = activation_function UpperCamelCase : List[str] = init_std UpperCamelCase : int = encoder_layerdrop UpperCamelCase : Dict = decoder_layerdrop UpperCamelCase : Any = classifier_dropout UpperCamelCase : Tuple = use_cache UpperCamelCase : Dict = encoder_layers UpperCamelCase : Tuple = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase : Optional[Any] = use_prompt UpperCamelCase : Any = prompt_length UpperCamelCase : List[Any] = prompt_mid_dim super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , forced_eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' """The config can simply be saved and uploaded again to be fixed.""" )
27
1
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : Union[str, Any] = tempfile.mkdtemp() # fmt: off UpperCamelCase : str = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on UpperCamelCase : Any = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase : Dict = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] UpperCamelCase : Tuple = {"""unk_token""": """<unk>"""} UpperCamelCase : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Optional[int] = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } UpperCamelCase : List[Any] = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE_ ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return CLIPTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def a_ ( self ): shutil.rmtree(self.tmpdirname ) def a_ ( self ): UpperCamelCase : Optional[int] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] UpperCamelCase : Any = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def a_ ( self ): UpperCamelCase : List[Any] = self.get_tokenizer() UpperCamelCase : Optional[int] = self.get_rust_tokenizer() UpperCamelCase : int = self.get_image_processor() UpperCamelCase : Optional[int] = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) processor_slow.save_pretrained(self.tmpdirname ) UpperCamelCase : Dict = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) processor_fast.save_pretrained(self.tmpdirname ) UpperCamelCase : List[str] = CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase : str = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) UpperCamelCase : int = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) UpperCamelCase : Any = CLIPSegProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.get_image_processor() UpperCamelCase : Optional[int] = self.get_tokenizer() UpperCamelCase : Union[str, Any] = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = self.prepare_image_inputs() UpperCamelCase : Optional[Any] = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) UpperCamelCase : Optional[int] = processor(images=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a_ ( self ): UpperCamelCase : List[str] = self.get_image_processor() UpperCamelCase : List[Any] = self.get_tokenizer() UpperCamelCase : str = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = """lower newer""" UpperCamelCase : Tuple = processor(text=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = tokenizer(SCREAMING_SNAKE_CASE_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def a_ ( self ): UpperCamelCase : Dict = self.get_image_processor() UpperCamelCase : Optional[Any] = self.get_tokenizer() UpperCamelCase : List[Any] = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """lower newer""" UpperCamelCase : Tuple = self.prepare_image_inputs() UpperCamelCase : int = processor(text=SCREAMING_SNAKE_CASE_ , images=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE_ ): processor() def a_ ( self ): UpperCamelCase : int = self.get_image_processor() UpperCamelCase : Tuple = self.get_tokenizer() UpperCamelCase : Optional[Any] = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.prepare_image_inputs() UpperCamelCase : Dict = self.prepare_image_inputs() UpperCamelCase : Tuple = processor(images=SCREAMING_SNAKE_CASE_ , visual_prompt=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """conditional_pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE_ ): processor() def a_ ( self ): UpperCamelCase : Union[str, Any] = self.get_image_processor() UpperCamelCase : Dict = self.get_tokenizer() UpperCamelCase : Any = CLIPSegProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCamelCase : List[str] = processor.batch_decode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A : Optional[Any] = 16 __A : str = 32 def A_ ( snake_case_ : Accelerator ,snake_case_ : int = 1_6 ): '''simple docstring''' UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[int] = load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(snake_case_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : Union[str, Any] = tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=snake_case_ ,max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase : Optional[Any] = datasets.map( snake_case_ ,batched=snake_case_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase : str = tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(snake_case_ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase : Optional[Any] = 1_6 elif accelerator.mixed_precision != "no": UpperCamelCase : Any = 8 else: UpperCamelCase : Optional[Any] = None return tokenizer.pad( snake_case_ ,padding="""longest""" ,max_length=snake_case_ ,pad_to_multiple_of=snake_case_ ,return_tensors="""pt""" ,) # Instantiate dataloaders. UpperCamelCase : str = DataLoader( tokenized_datasets["""train"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) UpperCamelCase : Dict = DataLoader( tokenized_datasets["""validation"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A : int = mocked_dataloaders # noqa: F811 def A_ ( snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,snake_case_ ) == "1": UpperCamelCase : Union[str, Any] = 2 # New Code # UpperCamelCase : Dict = int(args.gradient_accumulation_steps ) UpperCamelCase : List[Any] = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=snake_case_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : Union[str, Any] = config["""lr"""] UpperCamelCase : int = int(config["""num_epochs"""] ) UpperCamelCase : int = int(config["""seed"""] ) UpperCamelCase : List[Any] = int(config["""batch_size"""] ) UpperCamelCase : Optional[int] = evaluate.load("""glue""" ,"""mrpc""" ) set_seed(snake_case_ ) UpperCamelCase , UpperCamelCase : Dict = get_dataloaders(snake_case_ ,snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" ,return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase : Tuple = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase : List[Any] = AdamW(params=model.parameters() ,lr=snake_case_ ) # Instantiate scheduler UpperCamelCase : str = get_linear_schedule_with_warmup( optimizer=snake_case_ ,num_warmup_steps=1_0_0 ,num_training_steps=(len(snake_case_ ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() with LocalSGD( accelerator=snake_case_ ,model=snake_case_ ,local_sgd_steps=snake_case_ ,enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case_ ): UpperCamelCase : Optional[Any] = model(**snake_case_ ) UpperCamelCase : Optional[int] = output.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase : Any = model(**snake_case_ ) UpperCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case_ ,references=snake_case_ ,) UpperCamelCase : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' ,snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" ,type=snake_case_ ,default=snake_case_ ,choices=["""no""", """fp16""", """bf16""", """fp8"""] ,help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" ,) # New Code # parser.add_argument( """--gradient_accumulation_steps""" ,type=snake_case_ ,default=1 ,help="""The number of minibatches to be ran before gradients are accumulated.""" ,) parser.add_argument( """--local_sgd_steps""" ,type=snake_case_ ,default=8 ,help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) UpperCamelCase : Dict = parser.parse_args() UpperCamelCase : List[Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
27
1
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' # load dataset UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __A : Any = logging.get_logger(__name__) __A : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __A : Any = {'''allegro/herbert-base-cased''': 514} __A : Optional[Any] = {} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_INIT_CONFIGURATION lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = HerbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = [self.cls_token_id] UpperCamelCase : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): 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] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[Any] = (DDIMParallelScheduler,) lowercase : Any = (('eta', 0.0), ('num_inference_steps', 5_0)) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = { """num_train_timesteps""": 1000, """beta_start""": 0.0001, """beta_end""": 0.02, """beta_schedule""": """linear""", """clip_sample""": True, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def a_ ( self , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.scheduler_classes[0] UpperCamelCase : Tuple = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Optional[Any] = 10, 0.0 UpperCamelCase : Optional[Any] = self.dummy_model() UpperCamelCase : Dict = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) for t in scheduler.timesteps: UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample return sample def a_ ( self ): for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.scheduler_classes[0] UpperCamelCase : Tuple = self.get_scheduler_config(steps_offset=1 ) UpperCamelCase : str = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def a_ ( self ): for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE_ , beta_end=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE_ , prediction_type=SCREAMING_SNAKE_CASE_ , sample_max_value=SCREAMING_SNAKE_CASE_ , ) def a_ ( self ): for t in [1, 10, 49]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.scheduler_classes[0] UpperCamelCase : Optional[int] = self.get_scheduler_config() UpperCamelCase : Any = scheduler_class(**SCREAMING_SNAKE_CASE_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1e-5 def a_ ( self ): UpperCamelCase : Dict = self.scheduler_classes[0] UpperCamelCase : str = self.get_scheduler_config() UpperCamelCase : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : int = 10, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.dummy_model() UpperCamelCase : Optional[int] = self.dummy_sample_deter UpperCamelCase : Optional[Any] = self.dummy_sample_deter + 0.1 UpperCamelCase : Any = self.dummy_sample_deter - 0.1 UpperCamelCase : Any = samplea.shape[0] UpperCamelCase : Any = torch.stack([samplea, samplea, samplea] , dim=0 ) UpperCamelCase : int = torch.arange(SCREAMING_SNAKE_CASE_ )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) UpperCamelCase : Optional[int] = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1147.7904 ) < 1e-2 assert abs(result_mean.item() - 0.4982 ) < 1e-3 def a_ ( self ): UpperCamelCase : Tuple = self.full_loop() UpperCamelCase : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : List[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 172.0067 ) < 1e-2 assert abs(result_mean.item() - 0.223967 ) < 1e-3 def a_ ( self ): UpperCamelCase : Tuple = self.full_loop(prediction_type="""v_prediction""" ) UpperCamelCase : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Dict = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 52.5302 ) < 1e-2 assert abs(result_mean.item() - 0.0684 ) < 1e-3 def a_ ( self ): # We specify different beta, so that the first alpha is 0.99 UpperCamelCase : Union[str, Any] = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) UpperCamelCase : Any = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : str = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 149.8295 ) < 1e-2 assert abs(result_mean.item() - 0.1951 ) < 1e-3 def a_ ( self ): # We specify different beta, so that the first alpha is 0.99 UpperCamelCase : Optional[Any] = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) UpperCamelCase : Union[str, Any] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : str = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 149.0784 ) < 1e-2 assert abs(result_mean.item() - 0.1941 ) < 1e-3
27
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase , UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A , __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A , __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
27
1
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
"""simple docstring""" import argparse import os import re __A : Any = '''src/transformers''' # Pattern that looks at the indentation in a line. __A : Tuple = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : List[Any] = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : str ,snake_case_ : str="" ,snake_case_ : Any=None ,snake_case_ : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Tuple = ["""\n""".join(lines[:index] )] else: UpperCamelCase : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Dict = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = [lines[index + 1]] index += 1 else: UpperCamelCase : str = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : List[Any] ): '''simple docstring''' def _inner(snake_case_ : List[str] ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Optional[int] ): return x if key is None: UpperCamelCase : List[str] = noop # Constants are all uppercase, they go first. UpperCamelCase : List[str] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : Tuple = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : int = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Union[str, Any] = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : Any ): UpperCamelCase : Union[str, Any] = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : str = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : Optional[int] = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : int = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Tuple = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : List[Any] = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : List[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : Optional[int] = keys[:-1] UpperCamelCase : Union[str, Any] = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : Any = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int=True ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : int = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Dict = main_blocks[block_idx] UpperCamelCase : Dict = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : List[str] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : Optional[Any] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Optional[Any] = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : List[Any] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Optional[Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Optional[Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Any = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : Union[str, Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Optional[int] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : List[Any] = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
1
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __A : List[Any] = logging.get_logger(__name__) __A : str = { '''CarlCochet/trajectory-transformer-halfcheetah-medium-v2''': ( '''https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json''' ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class lowerCamelCase ( _UpperCAmelCase ): lowercase : int = 'trajectory_transformer' lowercase : int = ['past_key_values'] lowercase : int = { 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=249 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=17 , SCREAMING_SNAKE_CASE_=25 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=128 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0006 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=5_0256 , SCREAMING_SNAKE_CASE_=5_0256 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[int] = vocab_size UpperCamelCase : List[str] = action_weight UpperCamelCase : Optional[Any] = reward_weight UpperCamelCase : Any = value_weight UpperCamelCase : Optional[int] = max_position_embeddings UpperCamelCase : int = block_size UpperCamelCase : List[str] = action_dim UpperCamelCase : Optional[int] = observation_dim UpperCamelCase : Any = transition_dim UpperCamelCase : Any = learning_rate UpperCamelCase : Any = n_layer UpperCamelCase : Any = n_head UpperCamelCase : List[str] = n_embd UpperCamelCase : Tuple = embd_pdrop UpperCamelCase : Optional[int] = attn_pdrop UpperCamelCase : List[str] = resid_pdrop UpperCamelCase : Tuple = initializer_range UpperCamelCase : List[str] = layer_norm_eps UpperCamelCase : int = kaiming_initializer_range UpperCamelCase : Optional[int] = use_cache super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A : List[str] = logging.get_logger(__name__) __A : List[str] = { '''microsoft/trocr-base-handwritten''': ( '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json''' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[str] = 'trocr' lowercase : int = ['past_key_values'] lowercase : Tuple = { 'num_attention_heads': 'decoder_attention_heads', 'hidden_size': 'd_model', 'num_hidden_layers': 'decoder_layers', } def __init__( self , SCREAMING_SNAKE_CASE_=5_0265 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = vocab_size UpperCamelCase : List[Any] = d_model UpperCamelCase : Dict = decoder_layers UpperCamelCase : List[Any] = decoder_attention_heads UpperCamelCase : Dict = decoder_ffn_dim UpperCamelCase : Dict = activation_function UpperCamelCase : Optional[int] = max_position_embeddings UpperCamelCase : str = dropout UpperCamelCase : Tuple = attention_dropout UpperCamelCase : Dict = activation_dropout UpperCamelCase : str = init_std UpperCamelCase : Optional[int] = decoder_layerdrop UpperCamelCase : List[Any] = use_cache UpperCamelCase : Union[str, Any] = scale_embedding UpperCamelCase : List[Any] = use_learned_position_embeddings UpperCamelCase : str = layernorm_embedding 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_ , )
27
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( 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_ = None , 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_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : 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_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
1
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. __A : Dict = abspath(join(dirname(dirname(__file__)), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' from diffusers.utils.testing_utils import pytest_terminal_summary_main UpperCamelCase : Dict = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(snake_case_ ,id=snake_case_ )
27
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
27
1
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : List[Any] = inspect.getfile(accelerate.test_utils ) UpperCamelCase : Union[str, Any] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps""", """test_metrics.py"""] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 UpperCamelCase : Optional[Any] = test_metrics @require_cpu def a_ ( self ): debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def a_ ( self ): debug_launcher(self.test_metrics.main ) @require_single_gpu def a_ ( self ): self.test_metrics.main() @require_multi_gpu def a_ ( self ): print(f'Found {torch.cuda.device_count()} devices.' ) UpperCamelCase : Union[str, Any] = ["""torchrun""", f'--nproc_per_node={torch.cuda.device_count()}', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() )
27
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def a_ ( self ): UpperCamelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : Dict = """xvjiarui/stable-diffusion-2-inpainting""" UpperCamelCase , UpperCamelCase : List[str] = FlaxStableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = jax.random.PRNGKey(0 ) UpperCamelCase : Tuple = 50 UpperCamelCase : Dict = jax.device_count() UpperCamelCase : Optional[int] = num_samples * [prompt] UpperCamelCase : int = num_samples * [init_image] UpperCamelCase : List[Any] = num_samples * [mask_image] UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = pipeline.prepare_inputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # shard inputs and rng UpperCamelCase : Optional[int] = replicate(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = jax.random.split(SCREAMING_SNAKE_CASE_ , jax.device_count() ) UpperCamelCase : str = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipeline( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , jit=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = output.images.reshape(SCREAMING_SNAKE_CASE_ , 512 , 512 , 3 ) UpperCamelCase : List[Any] = images[0, 253:256, 253:256, -1] UpperCamelCase : List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase : Dict = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
27
1
"""simple docstring""" from importlib import import_module from .logging import get_logger __A : str = get_logger(__name__) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): UpperCamelCase : str = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("""__""" ): setattr(self , SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : List[Any] = module._original_module if isinstance(SCREAMING_SNAKE_CASE_ , _PatchedModuleObj ) else module class lowerCamelCase : lowercase : Any = [] def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): UpperCamelCase : Dict = obj UpperCamelCase : Any = target UpperCamelCase : Any = new UpperCamelCase : Optional[Any] = target.split(""".""" )[0] UpperCamelCase : int = {} UpperCamelCase : List[str] = attrs or [] def __enter__( self ): *UpperCamelCase , UpperCamelCase : int = self.target.split(""".""" ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(SCREAMING_SNAKE_CASE_ ) ): try: UpperCamelCase : int = import_module(""".""".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): UpperCamelCase : Tuple = getattr(self.obj , SCREAMING_SNAKE_CASE_ ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(SCREAMING_SNAKE_CASE_ , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): UpperCamelCase : Optional[Any] = obj_attr # patch at top level setattr(self.obj , SCREAMING_SNAKE_CASE_ , _PatchedModuleObj(SCREAMING_SNAKE_CASE_ , attrs=self.attrs ) ) UpperCamelCase : Optional[Any] = getattr(self.obj , SCREAMING_SNAKE_CASE_ ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , _PatchedModuleObj(getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , attrs=self.attrs ) ) UpperCamelCase : Any = getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # finally set the target attribute setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: UpperCamelCase : Union[str, Any] = getattr(import_module(""".""".join(SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , SCREAMING_SNAKE_CASE_ ) is attr_value: UpperCamelCase : Union[str, Any] = getattr(self.obj , SCREAMING_SNAKE_CASE_ ) setattr(self.obj , SCREAMING_SNAKE_CASE_ , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" UpperCamelCase : str = globals()["""__builtins__"""][target_attr] setattr(self.obj , SCREAMING_SNAKE_CASE_ , self.new ) else: raise RuntimeError(f'Tried to patch attribute {target_attr} instead of a submodule.' ) def __exit__( self , *SCREAMING_SNAKE_CASE_ ): for attr in list(self.original ): setattr(self.obj , SCREAMING_SNAKE_CASE_ , self.original.pop(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): self.__enter__() self._active_patches.append(self ) def a_ ( self ): try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
27
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Optional[Any] = [1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" ,[2, -1] ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[Any] = [1, 2] UpperCamelCase : List[Any] = {"""a""": 1, """b""": 2} UpperCamelCase : List[str] = {"""a""": [1, 2], """b""": [3, 4]} UpperCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} UpperCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCamelCase : Optional[int] = [2, 3] UpperCamelCase : List[str] = {"""a""": 2, """b""": 3} UpperCamelCase : Any = {"""a""": [2, 3], """b""": [4, 5]} UpperCamelCase : Tuple = {"""a""": {"""1""": 2}, """b""": 3} UpperCamelCase : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa
27
1
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A : Optional[Any] = 16 __A : str = 32 def A_ ( snake_case_ : Accelerator ,snake_case_ : int = 1_6 ): '''simple docstring''' UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[int] = load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(snake_case_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : Union[str, Any] = tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=snake_case_ ,max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase : Optional[Any] = datasets.map( snake_case_ ,batched=snake_case_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase : str = tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(snake_case_ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase : Optional[Any] = 1_6 elif accelerator.mixed_precision != "no": UpperCamelCase : Any = 8 else: UpperCamelCase : Optional[Any] = None return tokenizer.pad( snake_case_ ,padding="""longest""" ,max_length=snake_case_ ,pad_to_multiple_of=snake_case_ ,return_tensors="""pt""" ,) # Instantiate dataloaders. UpperCamelCase : str = DataLoader( tokenized_datasets["""train"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) UpperCamelCase : Dict = DataLoader( tokenized_datasets["""validation"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A : int = mocked_dataloaders # noqa: F811 def A_ ( snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,snake_case_ ) == "1": UpperCamelCase : Union[str, Any] = 2 # New Code # UpperCamelCase : Dict = int(args.gradient_accumulation_steps ) UpperCamelCase : List[Any] = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=snake_case_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : Union[str, Any] = config["""lr"""] UpperCamelCase : int = int(config["""num_epochs"""] ) UpperCamelCase : int = int(config["""seed"""] ) UpperCamelCase : List[Any] = int(config["""batch_size"""] ) UpperCamelCase : Optional[int] = evaluate.load("""glue""" ,"""mrpc""" ) set_seed(snake_case_ ) UpperCamelCase , UpperCamelCase : Dict = get_dataloaders(snake_case_ ,snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" ,return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase : Tuple = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase : List[Any] = AdamW(params=model.parameters() ,lr=snake_case_ ) # Instantiate scheduler UpperCamelCase : str = get_linear_schedule_with_warmup( optimizer=snake_case_ ,num_warmup_steps=1_0_0 ,num_training_steps=(len(snake_case_ ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() with LocalSGD( accelerator=snake_case_ ,model=snake_case_ ,local_sgd_steps=snake_case_ ,enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case_ ): UpperCamelCase : Optional[Any] = model(**snake_case_ ) UpperCamelCase : Optional[int] = output.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase : Any = model(**snake_case_ ) UpperCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case_ ,references=snake_case_ ,) UpperCamelCase : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' ,snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" ,type=snake_case_ ,default=snake_case_ ,choices=["""no""", """fp16""", """bf16""", """fp8"""] ,help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" ,) # New Code # parser.add_argument( """--gradient_accumulation_steps""" ,type=snake_case_ ,default=1 ,help="""The number of minibatches to be ran before gradients are accumulated.""" ,) parser.add_argument( """--local_sgd_steps""" ,type=snake_case_ ,default=8 ,help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) UpperCamelCase : Dict = parser.parse_args() UpperCamelCase : List[Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
27
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : Any = use_input_lengths UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = gelu_activation UpperCamelCase : Dict = sinusoidal_embeddings UpperCamelCase : Optional[int] = causal UpperCamelCase : List[Any] = asm UpperCamelCase : int = n_langs UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = n_special UpperCamelCase : Dict = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : List[str] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[str] = scope UpperCamelCase : Dict = bos_token_id def a_ ( self ): UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Union[str, Any] = None if self.use_input_lengths: UpperCamelCase : str = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[str] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a_ ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def a_ ( 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_ , ): UpperCamelCase : Optional[int] = XLMModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , lengths=SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( 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_ , ): UpperCamelCase : Optional[Any] = XLMWithLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( 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_ , ): UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( 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_ , ): UpperCamelCase : int = XLMForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , p_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , ) ((UpperCamelCase) , ) : Union[str, Any] = result_with_labels.to_tuple() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , ) : Tuple = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def a_ ( 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_ , ): UpperCamelCase : Union[str, Any] = XLMForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( 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_ , ): UpperCamelCase : int = self.num_labels UpperCamelCase : int = XLMForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : 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.num_labels) ) def a_ ( 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_ , ): UpperCamelCase : List[Any] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[Any] = config_and_inputs UpperCamelCase : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase : Optional[Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) return inputs_dict def a_ ( self ): UpperCamelCase : List[Any] = XLMModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , emb_dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_attentions in attentions] , [True] * len(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : Tuple = min_length + idx + 1 UpperCamelCase : Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_hidden_states in hidden_states] , [True] * len(SCREAMING_SNAKE_CASE_ ) , ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : List[str] = min_length + idx + 1 UpperCamelCase : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) , ) pass @slow def a_ ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = XLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Dict = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # the president UpperCamelCase : List[Any] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def A_ ( snake_case_ : List[str] ,snake_case_ : Union[str, Any] ,snake_case_ : str=1_0_2_4 ,snake_case_ : List[str]=1_0_2_4 ,snake_case_ : Dict=False ,**snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = AutoTokenizer.from_pretrained(snake_case_ ) UpperCamelCase : int = SeqaSeqDataset(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,type_path="""train""" ,**snake_case_ ) UpperCamelCase : Any = tok.pad_token_id def get_lens(snake_case_ : str ): UpperCamelCase : Dict = tqdm( DataLoader(snake_case_ ,batch_size=5_1_2 ,num_workers=8 ,shuffle=snake_case_ ,collate_fn=ds.collate_fn ) ,desc=str(ds.len_file ) ,) UpperCamelCase : Optional[int] = [] for batch in dl: UpperCamelCase : Any = batch["""input_ids"""].ne(snake_case_ ).sum(1 ).tolist() UpperCamelCase : Dict = batch["""labels"""].ne(snake_case_ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(snake_case_ ,snake_case_ ): max_lens.append(max(snake_case_ ,snake_case_ ) ) else: max_lens.extend(snake_case_ ) return max_lens UpperCamelCase : Dict = get_lens(snake_case_ ) UpperCamelCase : int = SeqaSeqDataset(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,type_path="""val""" ,**snake_case_ ) UpperCamelCase : Any = get_lens(snake_case_ ) pickle_save(snake_case_ ,train_ds.len_file ) pickle_save(snake_case_ ,val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
27
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
1
"""simple docstring""" from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def A_ ( snake_case_ : str = "isbn/0140328726" ): '''simple docstring''' UpperCamelCase : str = olid.strip().strip("""/""" ) # Remove leading/trailing whitespace & slashes if new_olid.count("""/""" ) != 1: UpperCamelCase : Optional[Any] = f'{olid} is not a valid Open Library olid' raise ValueError(snake_case_ ) return requests.get(f'https://openlibrary.org/{new_olid}.json' ).json() def A_ ( snake_case_ : dict ): '''simple docstring''' UpperCamelCase : Any = { """title""": """Title""", """publish_date""": """Publish date""", """authors""": """Authors""", """number_of_pages""": """Number of pages:""", """first_sentence""": """First sentence""", """isbn_10""": """ISBN (10)""", """isbn_13""": """ISBN (13)""", } UpperCamelCase : Tuple = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} UpperCamelCase : List[str] = [ get_openlibrary_data(author["""key"""] )["""name"""] for author in data["""Authors"""] ] UpperCamelCase : Optional[Any] = data["""First sentence"""]["""value"""] for key, value in data.items(): if isinstance(snake_case_ ,snake_case_ ): UpperCamelCase : Optional[int] = """, """.join(snake_case_ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: __A : Tuple = input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F'''Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.''') continue print(F'''\nSearching Open Library for ISBN: {isbn}...\n''') try: __A : Union[str, Any] = summarize_book(get_openlibrary_data(F'''isbn/{isbn}''')) print('''\n'''.join(F'''{key}: {value}''' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F'''Sorry, there are no results for ISBN: {isbn}.''')
27
"""simple docstring""" import torch from transformers import AutoModel class lowerCamelCase ( torch.nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_="sayef/fsner-bert-base-uncased" ): super(SCREAMING_SNAKE_CASE_ , self ).__init__() UpperCamelCase : int = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.nn.CosineSimilarity(3 , 1e-08 ) UpperCamelCase : Any = torch.nn.Softmax(dim=1 ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return self.bert(**SCREAMING_SNAKE_CASE_ ).last_hidden_state def a_ ( self , SCREAMING_SNAKE_CASE_ ): return token_embeddings.sum(2 , keepdim=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 ): return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = W_supports["""sizes"""].tolist() UpperCamelCase : List[str] = W_supports["""start_token_id"""].item() UpperCamelCase : List[Any] = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase : List[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = W_supports["""input_ids"""] == start_token_id UpperCamelCase : Optional[Any] = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: UpperCamelCase : int = 0 else: UpperCamelCase : Optional[int] = support_sizes[i - 1] UpperCamelCase : Tuple = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase : int = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase : Tuple = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase : List[str] = torch.vstack((p_starts, p_start) ) UpperCamelCase : Optional[Any] = torch.vstack((p_ends, p_end) ) else: UpperCamelCase : Optional[int] = p_start UpperCamelCase : Tuple = p_end return p_starts, p_ends
27
1
"""simple docstring""" import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets __A : Optional[int] = datasets.logging.get_logger(__name__) __A : Tuple = '''\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } ''' __A : Dict = '''\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project\'s README at https://github.com/google-research/bleurt#readme for more information. ''' __A : Any = ''' BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: \'scores\': List of scores. Examples: >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> bleurt = datasets.load_metric("bleurt") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results["scores"]]) [1.03, 1.04] ''' __A : List[str] = { '''bleurt-tiny-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip''', '''bleurt-tiny-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip''', '''bleurt-base-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip''', '''bleurt-base-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip''', '''bleurt-large-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip''', '''bleurt-large-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip''', '''BLEURT-20-D3''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip''', '''BLEURT-20-D6''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip''', '''BLEURT-20-D12''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip''', '''BLEURT-20''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip''', } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase ( datasets.Metric ): def a_ ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/google-research/bleurt""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/google-research/bleurt"""] , reference_urls=["""https://github.com/google-research/bleurt""", """https://arxiv.org/abs/2004.04696"""] , ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): # check that config name specifies a valid BLEURT model if self.config_name == "default": logger.warning( """Using default BLEURT-Base checkpoint for sequence maximum length 128. """ """You can use a bigger model for better results with e.g.: datasets.load_metric('bleurt', 'bleurt-large-512').""" ) UpperCamelCase : Dict = """bleurt-base-128""" if self.config_name.lower() in CHECKPOINT_URLS: UpperCamelCase : int = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: UpperCamelCase : Tuple = self.config_name.upper() else: raise KeyError( f'{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}' ) # download the model checkpoint specified by self.config_name and set up the scorer UpperCamelCase : Any = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) UpperCamelCase : Optional[int] = score.BleurtScorer(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = self.scorer.score(references=SCREAMING_SNAKE_CASE_ , candidates=SCREAMING_SNAKE_CASE_ ) return {"scores": scores}
27
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
1
"""simple docstring""" import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL __A : Optional[Any] = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def A_ ( snake_case_ : Tuple ,snake_case_ : tuple ,snake_case_ : Path ,snake_case_ : Any ,snake_case_ : str ,snake_case_ : Optional[Any] ,snake_case_ : int ,snake_case_ : Tuple=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 A_ ( snake_case_ : str ,snake_case_ : str ,snake_case_ : int ,snake_case_ : bool = False ): '''simple docstring''' UpperCamelCase : Optional[int] = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): UpperCamelCase : List[Any] = """cuda""" elif fpaa and not torch.cuda.is_available(): raise ValueError("""`float16` model export is only supported on GPUs with CUDA""" ) else: UpperCamelCase : int = """cpu""" UpperCamelCase : Any = Path(snake_case_ ) # VAE DECODER UpperCamelCase : Tuple = AutoencoderKL.from_pretrained(model_path + """/vae""" ) UpperCamelCase : str = vae_decoder.config.latent_channels # forward only through the decoder part UpperCamelCase : List[Any] = vae_decoder.decode onnx_export( snake_case_ ,model_args=( torch.randn(1 ,snake_case_ ,2_5 ,2_5 ).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__": __A : Dict = 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''') __A : Any = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print('''SD: Done: ONNX''')
27
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
1
"""simple docstring""" import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Dict=False ): '''simple docstring''' try: UpperCamelCase : Optional[int] = os.environ[key] except KeyError: # KEY isn't set, default to `default`. UpperCamelCase : Any = default else: # KEY is set, convert it to True or False. try: UpperCamelCase : str = strtobool(snake_case_ ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f'If set, {key} must be yes or no.' ) return _value __A : int = parse_flag_from_env('''RUN_SLOW''', default=False) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skip("""Test was skipped""" )(snake_case_ ) def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' return unittest.skipUnless(_run_slow_tests ,"""test is slow""" )(snake_case_ ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' return unittest.skipUnless(not torch.cuda.is_available() ,"""test requires only a CPU""" )(snake_case_ ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless(torch.cuda.is_available() ,"""test requires a GPU""" )(snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' return unittest.skipUnless(is_xpu_available() ,"""test requires a XPU""" )(snake_case_ ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless(is_mps_available() ,"""test requires a `mps` backend support in `torch`""" )(snake_case_ ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless( is_transformers_available() and is_datasets_available() ,"""test requires the Hugging Face suite""" )(snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' return unittest.skipUnless(is_bnb_available() ,"""test requires the bitsandbytes library""" )(snake_case_ ) def A_ ( snake_case_ : Any ): '''simple docstring''' return unittest.skipUnless(is_tpu_available() ,"""test requires TPU""" )(snake_case_ ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() == 1 ,"""test requires a GPU""" )(snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() == 1 ,"""test requires a XPU""" )(snake_case_ ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() > 1 ,"""test requires multiple GPUs""" )(snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() > 1 ,"""test requires multiple XPUs""" )(snake_case_ ) def A_ ( snake_case_ : Dict ): '''simple docstring''' return unittest.skipUnless(is_safetensors_available() ,"""test requires safetensors""" )(snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' return unittest.skipUnless(is_deepspeed_available() ,"""test requires DeepSpeed""" )(snake_case_ ) def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' return unittest.skipUnless(is_torch_version(""">=""" ,"""1.12.0""" ) ,"""test requires torch version >= 1.12.0""" )(snake_case_ ) def A_ ( snake_case_ : Tuple=None ,snake_case_ : List[str]=None ): '''simple docstring''' if test_case is None: return partial(snake_case_ ,version=snake_case_ ) return unittest.skipUnless(is_torch_version(""">=""" ,snake_case_ ) ,f'test requires torch version >= {version}' )(snake_case_ ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless(is_tensorboard_available() ,"""test requires Tensorboard""" )(snake_case_ ) def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' return unittest.skipUnless(is_wandb_available() ,"""test requires wandb""" )(snake_case_ ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless(is_comet_ml_available() ,"""test requires comet_ml""" )(snake_case_ ) __A : int = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' return unittest.skipUnless( _atleast_one_tracker_available ,"""test requires at least one tracker to be available and for `comet_ml` to not be installed""" ,)(snake_case_ ) class lowerCamelCase ( unittest.TestCase ): lowercase : Optional[Any] = True @classmethod def a_ ( cls ): UpperCamelCase : Optional[Any] = tempfile.mkdtemp() @classmethod def a_ ( cls ): if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def a_ ( self ): if self.clear_on_setup: for path in Path(self.tmpdir ).glob("""**/*""" ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class lowerCamelCase ( unittest.TestCase ): def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = mocks if isinstance(SCREAMING_SNAKE_CASE_ , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : List[str] = AcceleratorState() UpperCamelCase : Dict = tensor[None].clone().to(state.device ) UpperCamelCase : Optional[Any] = gather(snake_case_ ).cpu() UpperCamelCase : Tuple = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i] ,snake_case_ ): return False return True class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = returncode UpperCamelCase : List[str] = stdout UpperCamelCase : Union[str, Any] = stderr async def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : List[str] ): '''simple docstring''' while True: UpperCamelCase : Any = await stream.readline() if line: callback(snake_case_ ) else: break async def A_ ( snake_case_ : List[str] ,snake_case_ : Tuple=None ,snake_case_ : int=None ,snake_case_ : str=None ,snake_case_ : Dict=False ,snake_case_ : List[str]=False ): '''simple docstring''' if echo: print("""\nRunning: """ ,""" """.join(snake_case_ ) ) UpperCamelCase : Any = await asyncio.create_subprocess_exec( cmd[0] ,*cmd[1:] ,stdin=snake_case_ ,stdout=asyncio.subprocess.PIPE ,stderr=asyncio.subprocess.PIPE ,env=snake_case_ ,) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) UpperCamelCase : List[Any] = [] UpperCamelCase : List[str] = [] def tee(snake_case_ : List[Any] ,snake_case_ : Tuple ,snake_case_ : int ,snake_case_ : str="" ): UpperCamelCase : Tuple = line.decode("""utf-8""" ).rstrip() sink.append(snake_case_ ) if not quiet: print(snake_case_ ,snake_case_ ,file=snake_case_ ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout ,lambda snake_case_ : tee(snake_case_ ,snake_case_ ,sys.stdout ,label="""stdout:""" ) ) ), asyncio.create_task(_read_stream(p.stderr ,lambda snake_case_ : tee(snake_case_ ,snake_case_ ,sys.stderr ,label="""stderr:""" ) ) ), ] ,timeout=snake_case_ ,) return _RunOutput(await p.wait() ,snake_case_ ,snake_case_ ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Optional[Any]=None ,snake_case_ : Dict=None ,snake_case_ : Any=1_8_0 ,snake_case_ : List[str]=False ,snake_case_ : Optional[Any]=True ): '''simple docstring''' UpperCamelCase : List[str] = asyncio.get_event_loop() UpperCamelCase : Dict = loop.run_until_complete( _stream_subprocess(snake_case_ ,env=snake_case_ ,stdin=snake_case_ ,timeout=snake_case_ ,quiet=snake_case_ ,echo=snake_case_ ) ) UpperCamelCase : int = """ """.join(snake_case_ ) if result.returncode > 0: UpperCamelCase : List[Any] = """\n""".join(result.stderr ) raise RuntimeError( f'\'{cmd_str}\' failed with returncode {result.returncode}\n\n' f'The combined stderr from workers follows:\n{stderr}' ) return result class lowerCamelCase ( _UpperCAmelCase ): pass def A_ ( snake_case_ : List[str] ,snake_case_ : Optional[int]=False ): '''simple docstring''' try: UpperCamelCase : Dict = subprocess.check_output(snake_case_ ,stderr=subprocess.STDOUT ) if return_stdout: if hasattr(snake_case_ ,"""decode""" ): UpperCamelCase : Optional[Any] = output.decode("""utf-8""" ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( f'Command `{" ".join(snake_case_ )}` failed with the following error:\n\n{e.output.decode()}' ) from e
27
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
1
"""simple docstring""" from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline __A : List[str] = logging.get_logger(__name__) @add_end_docstrings(_UpperCAmelCase ) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , **SCREAMING_SNAKE_CASE_ ): super().__init__(**SCREAMING_SNAKE_CASE_ ) if self.framework != "pt": raise ValueError(f'The {self.__class__} is only available in PyTorch.' ) # No specific FOR_XXX available yet def __call__( self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return super().__call__(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = {} if "candidate_labels" in kwargs: UpperCamelCase : Optional[int] = kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: UpperCamelCase : int = kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="This is a sound of {}." ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png UpperCamelCase : List[Any] = requests.get(SCREAMING_SNAKE_CASE_ ).content else: with open(SCREAMING_SNAKE_CASE_ , """rb""" ) as f: UpperCamelCase : Union[str, Any] = f.read() if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = ffmpeg_read(SCREAMING_SNAKE_CASE_ , self.feature_extractor.sampling_rate ) if not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) UpperCamelCase : int = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="""pt""" ) UpperCamelCase : Tuple = candidate_labels UpperCamelCase : Optional[int] = [hypothesis_template.format(SCREAMING_SNAKE_CASE_ ) for x in candidate_labels] UpperCamelCase : Union[str, Any] = self.tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors=self.framework , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = [text_inputs] return inputs def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = model_inputs.pop("""candidate_labels""" ) UpperCamelCase : Any = model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = text_inputs[0] else: # Batching case. UpperCamelCase : List[Any] = text_inputs[0][0] UpperCamelCase : Dict = self.model(**SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = { """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = model_outputs.pop("""candidate_labels""" ) UpperCamelCase : int = model_outputs["""logits"""][0] if self.framework == "pt": UpperCamelCase : Dict = logits.softmax(dim=0 ) UpperCamelCase : str = probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) UpperCamelCase : Dict = [ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , key=lambda SCREAMING_SNAKE_CASE_ : -x[0] ) ] return result
27
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = AudioLDMPipeline lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS lowercase : Tuple = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Tuple = 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, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCamelCase : int = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) UpperCamelCase : Optional[int] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) UpperCamelCase : Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Any = self.get_dummy_components() UpperCamelCase : int = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Tuple = audio[:10] UpperCamelCase : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[str] = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) UpperCamelCase : Tuple = prompt_embeds # forward UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_components() UpperCamelCase : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * ["""this is a negative prompt"""] UpperCamelCase : List[Any] = negative_prompt UpperCamelCase : str = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : str = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[Any] = [] for p in [prompt, negative_prompt]: UpperCamelCase : int = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Union[str, Any] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = text_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Tuple = embeds # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Optional[int] = self.get_dummy_components() UpperCamelCase : List[str] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """egg cracking""" UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Union[str, Any] = audio[:10] UpperCamelCase : Dict = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Union[str, Any] = self.get_dummy_components() UpperCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) UpperCamelCase : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts UpperCamelCase : Dict = 2 UpperCamelCase : List[str] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt UpperCamelCase : List[str] = 2 UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts UpperCamelCase : Any = 2 UpperCamelCase : str = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config.sampling_rate UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 UpperCamelCase : Optional[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = ["""hey"""] UpperCamelCase : Dict = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : str = output.audios.shape assert audio_shape == (1, 256) UpperCamelCase : Optional[Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 UpperCamelCase : str = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : List[str] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) UpperCamelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def a_ ( self ): UpperCamelCase : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 25 UpperCamelCase : Optional[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[7_7230:7_7240] UpperCamelCase : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) UpperCamelCase : Any = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def a_ ( self ): UpperCamelCase : Any = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) UpperCamelCase : str = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[2_7780:2_7790] UpperCamelCase : Tuple = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) UpperCamelCase : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
27
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Tuple = { '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/config.json''', '''distilbert-base-uncased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json''' ), '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/config.json''', '''distilbert-base-cased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json''' ), '''distilbert-base-german-cased''': '''https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json''', '''distilbert-base-multilingual-cased''': ( '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json''' ), '''distilbert-base-uncased-finetuned-sst-2-english''': ( '''https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json''' ), } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = 'distilbert' lowercase : str = { 'hidden_size': 'dim', 'num_attention_heads': 'n_heads', 'num_hidden_layers': 'n_layers', } def __init__( self , SCREAMING_SNAKE_CASE_=3_0522 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=4 * 768 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.2 , SCREAMING_SNAKE_CASE_=0 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[Any] = vocab_size UpperCamelCase : Optional[Any] = max_position_embeddings UpperCamelCase : List[str] = sinusoidal_pos_embds UpperCamelCase : str = n_layers UpperCamelCase : int = n_heads UpperCamelCase : int = dim UpperCamelCase : List[str] = hidden_dim UpperCamelCase : Optional[int] = dropout UpperCamelCase : int = attention_dropout UpperCamelCase : Dict = activation UpperCamelCase : Any = initializer_range UpperCamelCase : int = qa_dropout UpperCamelCase : Optional[int] = seq_classif_dropout super().__init__(**SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( _UpperCAmelCase ): @property def a_ ( self ): if self.task == "multiple-choice": UpperCamelCase : Tuple = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCamelCase : Optional[int] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
27
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' # load dataset UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'naver-clova-ix/donut-base-finetuned-docvqa' lowercase : str = ( 'This is a tool that answers a question about an document (pdf). It takes an input named `document` which ' 'should be the document containing the information, as well as a `question` that is the question about the ' 'document. It returns a text that contains the answer to the question.' ) lowercase : Dict = 'document_qa' lowercase : Optional[int] = AutoProcessor lowercase : List[Any] = VisionEncoderDecoderModel lowercase : Any = ['image', 'text'] lowercase : Any = ['text'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" UpperCamelCase : int = task_prompt.replace("""{user_input}""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.pre_processor.tokenizer( SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).input_ids UpperCamelCase : List[Any] = self.pre_processor(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=SCREAMING_SNAKE_CASE_ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=SCREAMING_SNAKE_CASE_ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=SCREAMING_SNAKE_CASE_ , ).sequences def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.pre_processor.batch_decode(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Dict = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) UpperCamelCase : Union[str, Any] = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) UpperCamelCase : int = re.sub(r"""<.*?>""" , """""" , SCREAMING_SNAKE_CASE_ , count=1 ).strip() # remove first task start token UpperCamelCase : Optional[Any] = self.pre_processor.tokenajson(SCREAMING_SNAKE_CASE_ ) return sequence["answer"]
27
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : str = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
27
1
"""simple docstring""" from __future__ import annotations def A_ ( snake_case_ : str ,snake_case_ : list[str] | None = None ,snake_case_ : dict[str, float] | None = None ,snake_case_ : bool = False ,): '''simple docstring''' UpperCamelCase : List[str] = cipher_alphabet or [chr(snake_case_ ) for i in range(9_7 ,1_2_3 )] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) UpperCamelCase : str = { """a""": 0.08497, """b""": 0.01492, """c""": 0.02202, """d""": 0.04253, """e""": 0.11162, """f""": 0.02228, """g""": 0.02015, """h""": 0.06094, """i""": 0.07546, """j""": 0.00153, """k""": 0.01292, """l""": 0.04025, """m""": 0.02406, """n""": 0.06749, """o""": 0.07507, """p""": 0.01929, """q""": 0.00095, """r""": 0.07587, """s""": 0.06327, """t""": 0.09356, """u""": 0.02758, """v""": 0.00978, """w""": 0.02560, """x""": 0.00150, """y""": 0.01994, """z""": 0.00077, } else: # Custom frequencies dictionary UpperCamelCase : Dict = frequencies_dict if not case_sensitive: UpperCamelCase : Tuple = ciphertext.lower() # Chi squared statistic values UpperCamelCase : dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(snake_case_ ) ): UpperCamelCase : Tuple = """""" # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet UpperCamelCase : Union[str, Any] = (alphabet_letters.index(letter.lower() ) - shift) % len( snake_case_ ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter UpperCamelCase : Any = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: UpperCamelCase : Union[str, Any] = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message UpperCamelCase : str = decrypted_with_shift.lower().count(snake_case_ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies UpperCamelCase : str = frequencies[letter] * occurrences # Complete the chi squared statistic formula UpperCamelCase : str = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message UpperCamelCase : Any = decrypted_with_shift.count(snake_case_ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies UpperCamelCase : Union[str, Any] = frequencies[letter] * occurrences # Complete the chi squared statistic formula UpperCamelCase : str = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary UpperCamelCase : Optional[int] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(snake_case_ : int ) -> tuple[float, str]: return chi_squared_statistic_values[key] UpperCamelCase : int = min( snake_case_ ,key=snake_case_ ,) # Get all the data from the most likely cipher (key, decoded message) ( ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Optional[int] = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
27
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
27
1
"""simple docstring""" from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): lowercase : Tuple = [R'h\.\d+\.attn\.bias', R'h\.\d+\.attn\.masked_bias'] @register_to_config def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 5_0257 , SCREAMING_SNAKE_CASE_ = 1024 , SCREAMING_SNAKE_CASE_ = 768 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = 12 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "gelu_new" , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 1e-5 , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , ): super().__init__() UpperCamelCase : Optional[Any] = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) UpperCamelCase : List[Any] = prefix_inner_dim UpperCamelCase : Optional[int] = prefix_hidden_dim UpperCamelCase : List[Any] = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) UpperCamelCase : Any = ( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE_ ) if self.prefix_hidden_dim is not None else nn.Identity() ) UpperCamelCase : Tuple = GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE_ , n_positions=SCREAMING_SNAKE_CASE_ , n_embd=SCREAMING_SNAKE_CASE_ , n_layer=SCREAMING_SNAKE_CASE_ , n_head=SCREAMING_SNAKE_CASE_ , n_inner=SCREAMING_SNAKE_CASE_ , activation_function=SCREAMING_SNAKE_CASE_ , resid_pdrop=SCREAMING_SNAKE_CASE_ , embd_pdrop=SCREAMING_SNAKE_CASE_ , attn_pdrop=SCREAMING_SNAKE_CASE_ , layer_norm_epsilon=SCREAMING_SNAKE_CASE_ , initializer_range=SCREAMING_SNAKE_CASE_ , scale_attn_weights=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE_ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : int = GPTaLMHeadModel(SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): UpperCamelCase : Union[str, Any] = self.transformer.transformer.wte(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = self.encode_prefix(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.decode_prefix(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: UpperCamelCase : List[str] = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) UpperCamelCase : List[str] = torch.cat((dummy_token, input_ids) , dim=1 ) UpperCamelCase : List[Any] = self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return torch.zeros(SCREAMING_SNAKE_CASE_ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.encode_prefix(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = torch.split(SCREAMING_SNAKE_CASE_ , 1 , dim=0 ) UpperCamelCase : Tuple = [] UpperCamelCase : Any = [] for feature in features: UpperCamelCase : Tuple = self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE_ ) ) # back to the clip feature # Only support beam search for now UpperCamelCase , UpperCamelCase : List[Any] = self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) UpperCamelCase : List[Any] = torch.stack(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = torch.stack(SCREAMING_SNAKE_CASE_ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = 5 , SCREAMING_SNAKE_CASE_ = 67 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = None , ): UpperCamelCase : Union[str, Any] = eos_token_id UpperCamelCase : str = None UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = torch.ones(SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=torch.int ) UpperCamelCase : str = torch.zeros(SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=torch.bool ) if input_embeds is not None: UpperCamelCase : Optional[int] = input_embeds else: UpperCamelCase : Any = self.transformer.transformer.wte(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = outputs.logits UpperCamelCase : List[str] = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) UpperCamelCase : List[Any] = logits.softmax(-1 ).log() if scores is None: UpperCamelCase , UpperCamelCase : Any = logits.topk(SCREAMING_SNAKE_CASE_ , -1 ) UpperCamelCase : Union[str, Any] = generated.expand(SCREAMING_SNAKE_CASE_ , *generated.shape[1:] ) UpperCamelCase , UpperCamelCase : List[str] = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: UpperCamelCase : Optional[Any] = next_tokens else: UpperCamelCase : Optional[Any] = tokens.expand(SCREAMING_SNAKE_CASE_ , *tokens.shape[1:] ) UpperCamelCase : Optional[Any] = torch.cat((tokens, next_tokens) , dim=1 ) else: UpperCamelCase : Union[str, Any] = -float(np.inf ) UpperCamelCase : Union[str, Any] = 0 UpperCamelCase : str = scores[:, None] + logits seq_lengths[~is_stopped] += 1 UpperCamelCase : str = scores_sum / seq_lengths[:, None] UpperCamelCase , UpperCamelCase : List[Any] = scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE_ , -1 ) UpperCamelCase : str = next_tokens // scores_sum.shape[1] UpperCamelCase : Union[str, Any] = seq_lengths[next_tokens_source] UpperCamelCase : Dict = next_tokens % scores_sum.shape[1] UpperCamelCase : Optional[int] = next_tokens.unsqueeze(1 ) UpperCamelCase : Tuple = tokens[next_tokens_source] UpperCamelCase : str = torch.cat((tokens, next_tokens) , dim=1 ) UpperCamelCase : Optional[Any] = generated[next_tokens_source] UpperCamelCase : Optional[int] = scores_sum_average * seq_lengths UpperCamelCase : Tuple = is_stopped[next_tokens_source] UpperCamelCase : int = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) UpperCamelCase : int = torch.cat((generated, next_token_embed) , dim=1 ) UpperCamelCase : Any = is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE_ ).squeeze() if is_stopped.all(): break UpperCamelCase : Optional[Any] = scores / seq_lengths UpperCamelCase : Tuple = scores.argsort(descending=SCREAMING_SNAKE_CASE_ ) # tokens tensors are already padded to max_seq_length UpperCamelCase : str = [tokens[i] for i in order] UpperCamelCase : List[Any] = torch.stack(SCREAMING_SNAKE_CASE_ , dim=0 ) UpperCamelCase : Dict = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
27
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCamelCase ( _UpperCAmelCase ): 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_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Union[str, Any] = use_token_type_ids UpperCamelCase : Dict = use_labels UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : str = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : int = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Dict = num_labels UpperCamelCase : Tuple = num_choices UpperCamelCase : Optional[int] = scope UpperCamelCase : List[Any] = q_groups UpperCamelCase : Tuple = k_groups UpperCamelCase : Any = v_groups UpperCamelCase : List[str] = post_attention_groups UpperCamelCase : Tuple = intermediate_groups UpperCamelCase : int = output_groups def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = SqueezeBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = SqueezeBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = 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 a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = SqueezeBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : str = SqueezeBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = 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.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = SqueezeBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = config_and_inputs UpperCamelCase : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase : Dict = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : str = True lowercase : str = False def a_ ( self ): UpperCamelCase : Any = SqueezeBertModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = SqueezeBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) UpperCamelCase : Dict = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowerCamelCase ( metaclass=_UpperCAmelCase ): lowercase : str = ['torch', 'transformers', 'onnx'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class lowerCamelCase ( metaclass=_UpperCAmelCase ): lowercase : int = ['torch', 'transformers', 'onnx'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class lowerCamelCase ( metaclass=_UpperCAmelCase ): lowercase : Any = ['torch', 'transformers', 'onnx'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class lowerCamelCase ( metaclass=_UpperCAmelCase ): lowercase : Tuple = ['torch', 'transformers', 'onnx'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class lowerCamelCase ( metaclass=_UpperCAmelCase ): lowercase : Optional[int] = ['torch', 'transformers', 'onnx'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class lowerCamelCase ( metaclass=_UpperCAmelCase ): lowercase : List[str] = ['torch', 'transformers', 'onnx'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] )
27
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" from heapq import heappop, heappush import numpy as np def A_ ( snake_case_ : np.ndarray ,snake_case_ : tuple[int, int] ,snake_case_ : tuple[int, int] ,snake_case_ : bool ,): '''simple docstring''' UpperCamelCase , UpperCamelCase : List[str] = grid.shape UpperCamelCase : Union[str, Any] = [-1, 1, 0, 0] UpperCamelCase : Any = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] UpperCamelCase , UpperCamelCase : Tuple = [(0, source)], set() UpperCamelCase : Any = np.full((rows, cols) ,np.inf ) UpperCamelCase : Any = 0 UpperCamelCase : Tuple = np.empty((rows, cols) ,dtype=snake_case_ ) UpperCamelCase : int = None while queue: ((UpperCamelCase) , (UpperCamelCase)) : int = heappop(snake_case_ ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: UpperCamelCase : str = [] while (x, y) != source: path.append((x, y) ) UpperCamelCase , UpperCamelCase : str = predecessors[x, y] path.append(snake_case_ ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(snake_case_ ) ): UpperCamelCase , UpperCamelCase : Optional[Any] = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: UpperCamelCase : Dict = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(snake_case_ ,(dist + 1, (nx, ny)) ) UpperCamelCase : Optional[int] = dist + 1 UpperCamelCase : Any = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
27
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Optional[int] = { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = 'mvp' lowercase : Optional[Any] = ['past_key_values'] lowercase : Union[str, Any] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , SCREAMING_SNAKE_CASE_=5_0267 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=800 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Dict = max_position_embeddings UpperCamelCase : Optional[int] = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : Any = encoder_layers UpperCamelCase : List[Any] = encoder_attention_heads UpperCamelCase : Optional[Any] = decoder_ffn_dim UpperCamelCase : Optional[int] = decoder_layers UpperCamelCase : Dict = decoder_attention_heads UpperCamelCase : List[str] = dropout UpperCamelCase : List[str] = attention_dropout UpperCamelCase : List[Any] = activation_dropout UpperCamelCase : Dict = activation_function UpperCamelCase : List[str] = init_std UpperCamelCase : int = encoder_layerdrop UpperCamelCase : Dict = decoder_layerdrop UpperCamelCase : Any = classifier_dropout UpperCamelCase : Tuple = use_cache UpperCamelCase : Dict = encoder_layers UpperCamelCase : Tuple = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase : Optional[Any] = use_prompt UpperCamelCase : Any = prompt_length UpperCamelCase : List[Any] = prompt_mid_dim super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , forced_eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' """The config can simply be saved and uploaded again to be fixed.""" )
27
1
"""simple docstring""" import re import string import numpy as np import datasets __A : Union[str, Any] = ''' Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. ''' __A : Optional[Any] = ''' Args: predictions: List of predicted texts. references: List of reference texts. regexes_to_ignore: List, defaults to None. Regex expressions of characters to ignore when calculating the exact matches. Note: these regexes are removed from the input data before the changes based on the options below (e.g. ignore_case, ignore_punctuation, ignore_numbers) are applied. ignore_case: Boolean, defaults to False. If true, turns everything to lowercase so that capitalization differences are ignored. ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. Returns: exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive. Examples: >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 25.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 50.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True) >>> print(round(results["exact_match"], 1)) 75.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["the cat", "theater", "YELLING", "agent007"] >>> preds = ["cat?", "theater", "yelling", "agent"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True) >>> print(round(results["exact_match"], 1)) 100.0 >>> exact_match = datasets.load_metric("exact_match") >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."] >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results["exact_match"], 1)) 33.3 ''' __A : Union[str, Any] = ''' ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase ( datasets.Metric ): def a_ ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , reference_urls=[] , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , ): if regexes_to_ignore is not None: for s in regexes_to_ignore: UpperCamelCase : Union[str, Any] = np.array([re.sub(SCREAMING_SNAKE_CASE_ , """""" , SCREAMING_SNAKE_CASE_ ) for x in predictions] ) UpperCamelCase : List[str] = np.array([re.sub(SCREAMING_SNAKE_CASE_ , """""" , SCREAMING_SNAKE_CASE_ ) for x in references] ) else: UpperCamelCase : List[Any] = np.asarray(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = np.asarray(SCREAMING_SNAKE_CASE_ ) if ignore_case: UpperCamelCase : Optional[int] = np.char.lower(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = np.char.lower(SCREAMING_SNAKE_CASE_ ) if ignore_punctuation: UpperCamelCase : int = string.punctuation.maketrans("""""" , """""" , string.punctuation ) UpperCamelCase : List[str] = np.char.translate(SCREAMING_SNAKE_CASE_ , table=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = np.char.translate(SCREAMING_SNAKE_CASE_ , table=SCREAMING_SNAKE_CASE_ ) if ignore_numbers: UpperCamelCase : Any = string.digits.maketrans("""""" , """""" , string.digits ) UpperCamelCase : Dict = np.char.translate(SCREAMING_SNAKE_CASE_ , table=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = np.char.translate(SCREAMING_SNAKE_CASE_ , table=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = predictions == references return {"exact_match": np.mean(SCREAMING_SNAKE_CASE_ ) * 100}
27
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A : Optional[Any] = 16 __A : str = 32 def A_ ( snake_case_ : Accelerator ,snake_case_ : int = 1_6 ): '''simple docstring''' UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[int] = load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(snake_case_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : Union[str, Any] = tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=snake_case_ ,max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase : Optional[Any] = datasets.map( snake_case_ ,batched=snake_case_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase : str = tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(snake_case_ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase : Optional[Any] = 1_6 elif accelerator.mixed_precision != "no": UpperCamelCase : Any = 8 else: UpperCamelCase : Optional[Any] = None return tokenizer.pad( snake_case_ ,padding="""longest""" ,max_length=snake_case_ ,pad_to_multiple_of=snake_case_ ,return_tensors="""pt""" ,) # Instantiate dataloaders. UpperCamelCase : str = DataLoader( tokenized_datasets["""train"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) UpperCamelCase : Dict = DataLoader( tokenized_datasets["""validation"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A : int = mocked_dataloaders # noqa: F811 def A_ ( snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,snake_case_ ) == "1": UpperCamelCase : Union[str, Any] = 2 # New Code # UpperCamelCase : Dict = int(args.gradient_accumulation_steps ) UpperCamelCase : List[Any] = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=snake_case_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : Union[str, Any] = config["""lr"""] UpperCamelCase : int = int(config["""num_epochs"""] ) UpperCamelCase : int = int(config["""seed"""] ) UpperCamelCase : List[Any] = int(config["""batch_size"""] ) UpperCamelCase : Optional[int] = evaluate.load("""glue""" ,"""mrpc""" ) set_seed(snake_case_ ) UpperCamelCase , UpperCamelCase : Dict = get_dataloaders(snake_case_ ,snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" ,return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase : Tuple = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase : List[Any] = AdamW(params=model.parameters() ,lr=snake_case_ ) # Instantiate scheduler UpperCamelCase : str = get_linear_schedule_with_warmup( optimizer=snake_case_ ,num_warmup_steps=1_0_0 ,num_training_steps=(len(snake_case_ ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() with LocalSGD( accelerator=snake_case_ ,model=snake_case_ ,local_sgd_steps=snake_case_ ,enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case_ ): UpperCamelCase : Optional[Any] = model(**snake_case_ ) UpperCamelCase : Optional[int] = output.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase : Any = model(**snake_case_ ) UpperCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case_ ,references=snake_case_ ,) UpperCamelCase : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' ,snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" ,type=snake_case_ ,default=snake_case_ ,choices=["""no""", """fp16""", """bf16""", """fp8"""] ,help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" ,) # New Code # parser.add_argument( """--gradient_accumulation_steps""" ,type=snake_case_ ,default=1 ,help="""The number of minibatches to be ran before gradients are accumulated.""" ,) parser.add_argument( """--local_sgd_steps""" ,type=snake_case_ ,default=8 ,help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) UpperCamelCase : Dict = parser.parse_args() UpperCamelCase : List[Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
27
1
"""simple docstring""" from typing import List, Optional, Union import numpy as np from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging __A : Dict = logging.get_logger(__name__) class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = ['input_values', 'padding_mask'] def __init__( self , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 2_4000 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = chunk_length_s UpperCamelCase : List[Any] = overlap @property def a_ ( self ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def a_ ( self ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided audio input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) if padding and truncation: raise ValueError("""Both padding and truncation were set. Make sure you only set one.""" ) elif padding is None: # by default let's pad the inputs UpperCamelCase : Optional[int] = True UpperCamelCase : Union[str, Any] = bool( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_audio[0] , (np.ndarray, tuple, list) )) ) if is_batched: UpperCamelCase : List[Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ).T for audio in raw_audio] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): UpperCamelCase : Optional[int] = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ): UpperCamelCase : Any = raw_audio.astype(np.floataa ) # always return batch if not is_batched: UpperCamelCase : Any = [np.asarray(SCREAMING_SNAKE_CASE_ ).T] # verify inputs are valid for idx, example in enumerate(SCREAMING_SNAKE_CASE_ ): if example.ndim > 2: raise ValueError(f'Expected input shape (channels, length) but got shape {example.shape}' ) if self.feature_size == 1 and example.ndim != 1: raise ValueError(f'Expected mono audio but example has {example.shape[-1]} channels' ) if self.feature_size == 2 and example.shape[-1] != 2: raise ValueError(f'Expected stereo audio but example has {example.shape[-1]} channels' ) UpperCamelCase : List[Any] = None UpperCamelCase : Dict = BatchFeature({"""input_values""": raw_audio} ) if self.chunk_stride is not None and self.chunk_length is not None and max_length is None: if truncation: UpperCamelCase : Tuple = min(array.shape[0] for array in raw_audio ) UpperCamelCase : List[str] = int(np.floor(max_length / self.chunk_stride ) ) UpperCamelCase : str = (nb_step - 1) * self.chunk_stride + self.chunk_length elif padding: UpperCamelCase : int = max(array.shape[0] for array in raw_audio ) UpperCamelCase : str = int(np.ceil(max_length / self.chunk_stride ) ) UpperCamelCase : Optional[int] = (nb_step - 1) * self.chunk_stride + self.chunk_length UpperCamelCase : int = """max_length""" else: UpperCamelCase : List[str] = input_values # normal padding on batch if padded_inputs is None: UpperCamelCase : List[Any] = self.pad( SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ) if padding: UpperCamelCase : int = padded_inputs.pop("""attention_mask""" ) UpperCamelCase : Optional[Any] = [] for example in padded_inputs.pop("""input_values""" ): if self.feature_size == 1: UpperCamelCase : Union[str, Any] = example[..., None] input_values.append(example.T ) UpperCamelCase : Dict = input_values if return_tensors is not None: UpperCamelCase : Any = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return padded_inputs
27
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __A : Any = logging.get_logger(__name__) __A : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __A : Any = {'''allegro/herbert-base-cased''': 514} __A : Optional[Any] = {} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_INIT_CONFIGURATION lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = HerbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = [self.cls_token_id] UpperCamelCase : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): 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] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[Any] = 'char' lowercase : Dict = 'bpe' lowercase : Optional[Any] = 'wp' __A : Dict = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = ['image_processor', 'char_tokenizer'] lowercase : int = 'ViTImageProcessor' lowercase : Dict = 'MgpstrTokenizer' def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[Any] = kwargs.pop("""feature_extractor""" ) UpperCamelCase : Optional[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) UpperCamelCase : Optional[int] = tokenizer UpperCamelCase : Optional[int] = AutoTokenizer.from_pretrained("""gpt2""" ) UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""bert-base-uncased""" ) super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __call__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: UpperCamelCase : Optional[Any] = self.image_processor(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if text is not None: UpperCamelCase : Dict = self.char_tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if text is None: return inputs elif images is None: return encodings else: UpperCamelCase : int = encodings["""input_ids"""] return inputs def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = sequences UpperCamelCase : Optional[int] = char_preds.size(0 ) UpperCamelCase , UpperCamelCase : List[str] = self._decode_helper(SCREAMING_SNAKE_CASE_ , """char""" ) UpperCamelCase , UpperCamelCase : Union[str, Any] = self._decode_helper(SCREAMING_SNAKE_CASE_ , """bpe""" ) UpperCamelCase , UpperCamelCase : Any = self._decode_helper(SCREAMING_SNAKE_CASE_ , """wp""" ) UpperCamelCase : Optional[int] = [] UpperCamelCase : Union[str, Any] = [] for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = [char_scores[i], bpe_scores[i], wp_scores[i]] UpperCamelCase : Union[str, Any] = [char_strs[i], bpe_strs[i], wp_strs[i]] UpperCamelCase : List[Any] = scores.index(max(SCREAMING_SNAKE_CASE_ ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) UpperCamelCase : Any = {} UpperCamelCase : List[str] = final_strs UpperCamelCase : Optional[int] = final_scores UpperCamelCase : List[str] = char_strs UpperCamelCase : Optional[Any] = bpe_strs UpperCamelCase : Dict = wp_strs return out def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if format == DecodeType.CHARACTER: UpperCamelCase : Any = self.char_decode UpperCamelCase : Union[str, Any] = 1 UpperCamelCase : Dict = """[s]""" elif format == DecodeType.BPE: UpperCamelCase : str = self.bpe_decode UpperCamelCase : List[Any] = 2 UpperCamelCase : Tuple = """#""" elif format == DecodeType.WORDPIECE: UpperCamelCase : Union[str, Any] = self.wp_decode UpperCamelCase : Union[str, Any] = 102 UpperCamelCase : int = """[SEP]""" else: raise ValueError(f'Format {format} is not supported.' ) UpperCamelCase , UpperCamelCase : Any = [], [] UpperCamelCase : Dict = pred_logits.size(0 ) UpperCamelCase : Optional[int] = pred_logits.size(1 ) UpperCamelCase , UpperCamelCase : List[str] = pred_logits.topk(1 , dim=-1 , largest=SCREAMING_SNAKE_CASE_ , sorted=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = preds_index.view(-1 , SCREAMING_SNAKE_CASE_ )[:, 1:] UpperCamelCase : Tuple = decoder(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = torch.nn.functional.softmax(SCREAMING_SNAKE_CASE_ , dim=2 ).max(dim=2 ) UpperCamelCase : Optional[int] = preds_max_prob[:, 1:] for index in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = preds_str[index].find(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = preds_str[index][:pred_eos] UpperCamelCase : List[str] = preds_index[index].cpu().tolist() UpperCamelCase : List[str] = pred_index.index(SCREAMING_SNAKE_CASE_ ) if eos_token in pred_index else -1 UpperCamelCase : Dict = preds_max_prob[index][: pred_eos_index + 1] UpperCamelCase : Optional[int] = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(SCREAMING_SNAKE_CASE_ ) conf_scores.append(SCREAMING_SNAKE_CASE_ ) return dec_strs, conf_scores def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = [seq.replace(""" """ , """""" ) for seq in self.char_tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ )] return decode_strs def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.bpe_tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = [seq.replace(""" """ , """""" ) for seq in self.wp_tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ )] return decode_strs
27
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase , UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A , __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A , __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
27
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A : List[str] = logging.get_logger(__name__) __A : Any = { '''microsoft/markuplm-base''': '''https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json''', '''microsoft/markuplm-large''': '''https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Any = 'markuplm' 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-12 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=216 , SCREAMING_SNAKE_CASE_=1001 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=50 , SCREAMING_SNAKE_CASE_="absolute" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = vocab_size UpperCamelCase : Optional[int] = hidden_size UpperCamelCase : Optional[Any] = num_hidden_layers UpperCamelCase : Optional[int] = num_attention_heads UpperCamelCase : List[str] = hidden_act UpperCamelCase : Optional[Any] = intermediate_size UpperCamelCase : Any = hidden_dropout_prob UpperCamelCase : Union[str, Any] = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : str = type_vocab_size UpperCamelCase : str = initializer_range UpperCamelCase : List[str] = layer_norm_eps UpperCamelCase : Tuple = position_embedding_type UpperCamelCase : List[str] = use_cache UpperCamelCase : List[str] = classifier_dropout # additional properties UpperCamelCase : List[str] = max_depth UpperCamelCase : Union[str, Any] = max_xpath_tag_unit_embeddings UpperCamelCase : List[Any] = max_xpath_subs_unit_embeddings UpperCamelCase : str = tag_pad_id UpperCamelCase : Dict = subs_pad_id UpperCamelCase : Tuple = xpath_unit_hidden_size
27
"""simple docstring""" import argparse import os import re __A : Any = '''src/transformers''' # Pattern that looks at the indentation in a line. __A : Tuple = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : List[Any] = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : str ,snake_case_ : str="" ,snake_case_ : Any=None ,snake_case_ : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Tuple = ["""\n""".join(lines[:index] )] else: UpperCamelCase : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Dict = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = [lines[index + 1]] index += 1 else: UpperCamelCase : str = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : List[Any] ): '''simple docstring''' def _inner(snake_case_ : List[str] ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Optional[int] ): return x if key is None: UpperCamelCase : List[str] = noop # Constants are all uppercase, they go first. UpperCamelCase : List[str] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : Tuple = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : int = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Union[str, Any] = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : Any ): UpperCamelCase : Union[str, Any] = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : str = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : Optional[int] = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : int = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Tuple = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : List[Any] = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : List[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : Optional[int] = keys[:-1] UpperCamelCase : Union[str, Any] = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : Any = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int=True ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : int = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Dict = main_blocks[block_idx] UpperCamelCase : Dict = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : List[str] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : Optional[Any] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Optional[Any] = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : List[Any] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Optional[Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Optional[Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Any = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : Union[str, Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Optional[int] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : List[Any] = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A : int = { '''configuration_graphormer''': ['''GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GraphormerConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ '''GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GraphormerForGraphClassification''', '''GraphormerModel''', '''GraphormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __A : Union[str, Any] = logging.get_logger(__name__) __A : int = { '''google/bit-50''': '''https://huggingface.co/google/bit-50/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase ): lowercase : Optional[int] = 'bit' lowercase : Any = ['preactivation', 'bottleneck'] lowercase : Any = ['SAME', 'VALID'] def __init__( self , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=[256, 512, 1024, 2048] , SCREAMING_SNAKE_CASE_=[3, 4, 6, 3] , SCREAMING_SNAKE_CASE_="preactivation" , SCREAMING_SNAKE_CASE_="relu" , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) if layer_type not in self.layer_types: raise ValueError(f'layer_type={layer_type} is not one of {",".join(self.layer_types )}' ) if global_padding is not None: if global_padding.upper() in self.supported_padding: UpperCamelCase : str = global_padding.upper() else: raise ValueError(f'Padding strategy {global_padding} not supported' ) UpperCamelCase : Optional[int] = num_channels UpperCamelCase : str = embedding_size UpperCamelCase : List[Any] = hidden_sizes UpperCamelCase : Any = depths UpperCamelCase : Optional[int] = layer_type UpperCamelCase : List[str] = hidden_act UpperCamelCase : Any = global_padding UpperCamelCase : Dict = num_groups UpperCamelCase : Optional[int] = drop_path_rate UpperCamelCase : Dict = embedding_dynamic_padding UpperCamelCase : str = output_stride UpperCamelCase : str = width_factor UpperCamelCase : int = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(SCREAMING_SNAKE_CASE_ ) + 1 )] UpperCamelCase , UpperCamelCase : List[str] = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , stage_names=self.stage_names )
27
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( 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_ = None , 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_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : 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_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
1
"""simple docstring""" import argparse import os import re __A : Any = '''src/transformers''' # Pattern that looks at the indentation in a line. __A : Tuple = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : List[Any] = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : str ,snake_case_ : str="" ,snake_case_ : Any=None ,snake_case_ : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Tuple = ["""\n""".join(lines[:index] )] else: UpperCamelCase : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Dict = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = [lines[index + 1]] index += 1 else: UpperCamelCase : str = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : List[Any] ): '''simple docstring''' def _inner(snake_case_ : List[str] ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Optional[int] ): return x if key is None: UpperCamelCase : List[str] = noop # Constants are all uppercase, they go first. UpperCamelCase : List[str] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : Tuple = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : int = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Union[str, Any] = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : Any ): UpperCamelCase : Union[str, Any] = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : str = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : Optional[int] = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : int = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Tuple = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : List[Any] = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : List[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : Optional[int] = keys[:-1] UpperCamelCase : Union[str, Any] = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : Any = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int=True ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : int = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Dict = main_blocks[block_idx] UpperCamelCase : Dict = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : List[str] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : Optional[Any] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Optional[Any] = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : List[Any] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Optional[Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Optional[Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Any = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : Union[str, Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Optional[int] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : List[Any] = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
27
1
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = AudioLDMPipeline lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS lowercase : Tuple = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Tuple = 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, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCamelCase : int = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) UpperCamelCase : Optional[int] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) UpperCamelCase : Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Any = self.get_dummy_components() UpperCamelCase : int = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Tuple = audio[:10] UpperCamelCase : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[str] = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) UpperCamelCase : Tuple = prompt_embeds # forward UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_components() UpperCamelCase : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * ["""this is a negative prompt"""] UpperCamelCase : List[Any] = negative_prompt UpperCamelCase : str = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : str = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[Any] = [] for p in [prompt, negative_prompt]: UpperCamelCase : int = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Union[str, Any] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = text_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Tuple = embeds # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Optional[int] = self.get_dummy_components() UpperCamelCase : List[str] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """egg cracking""" UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Union[str, Any] = audio[:10] UpperCamelCase : Dict = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Union[str, Any] = self.get_dummy_components() UpperCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) UpperCamelCase : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts UpperCamelCase : Dict = 2 UpperCamelCase : List[str] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt UpperCamelCase : List[str] = 2 UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts UpperCamelCase : Any = 2 UpperCamelCase : str = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config.sampling_rate UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 UpperCamelCase : Optional[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = ["""hey"""] UpperCamelCase : Dict = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : str = output.audios.shape assert audio_shape == (1, 256) UpperCamelCase : Optional[Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 UpperCamelCase : str = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : List[str] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) UpperCamelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def a_ ( self ): UpperCamelCase : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 25 UpperCamelCase : Optional[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[7_7230:7_7240] UpperCamelCase : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) UpperCamelCase : Any = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def a_ ( self ): UpperCamelCase : Any = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) UpperCamelCase : str = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[2_7780:2_7790] UpperCamelCase : Tuple = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) UpperCamelCase : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
27
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def a_ ( self ): UpperCamelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : Dict = """xvjiarui/stable-diffusion-2-inpainting""" UpperCamelCase , UpperCamelCase : List[str] = FlaxStableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = jax.random.PRNGKey(0 ) UpperCamelCase : Tuple = 50 UpperCamelCase : Dict = jax.device_count() UpperCamelCase : Optional[int] = num_samples * [prompt] UpperCamelCase : int = num_samples * [init_image] UpperCamelCase : List[Any] = num_samples * [mask_image] UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = pipeline.prepare_inputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # shard inputs and rng UpperCamelCase : Optional[int] = replicate(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = jax.random.split(SCREAMING_SNAKE_CASE_ , jax.device_count() ) UpperCamelCase : str = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipeline( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , jit=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = output.images.reshape(SCREAMING_SNAKE_CASE_ , 512 , 512 , 3 ) UpperCamelCase : List[Any] = images[0, 253:256, 253:256, -1] UpperCamelCase : List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase : Dict = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
27
1
"""simple docstring""" import qiskit def A_ ( snake_case_ : int ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : str = qiskit.Aer.get_backend("""aer_simulator""" ) UpperCamelCase : Any = qiskit.QuantumCircuit(4 ,2 ) # encode inputs in qubits 0 and 1 if bita == 1: qc_ha.x(0 ) if bita == 1: qc_ha.x(1 ) qc_ha.barrier() # use cnots to write XOR of the inputs on qubit2 qc_ha.cx(0 ,2 ) qc_ha.cx(1 ,2 ) # use ccx / toffoli gate to write AND of the inputs on qubit3 qc_ha.ccx(0 ,1 ,3 ) qc_ha.barrier() # extract outputs qc_ha.measure(2 ,0 ) # extract XOR value qc_ha.measure(3 ,1 ) # extract AND value # Execute the circuit on the qasm simulator UpperCamelCase : Optional[Any] = qiskit.execute(snake_case_ ,snake_case_ ,shots=1_0_0_0 ) # Return the histogram data of the results of the experiment return job.result().get_counts(snake_case_ ) if __name__ == "__main__": __A : str = half_adder(1, 1) print(F'''Half Adder Output Qubit Counts: {counts}''')
27
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Optional[Any] = [1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" ,[2, -1] ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[Any] = [1, 2] UpperCamelCase : List[Any] = {"""a""": 1, """b""": 2} UpperCamelCase : List[str] = {"""a""": [1, 2], """b""": [3, 4]} UpperCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} UpperCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCamelCase : Optional[int] = [2, 3] UpperCamelCase : List[str] = {"""a""": 2, """b""": 3} UpperCamelCase : Any = {"""a""": [2, 3], """b""": [4, 5]} UpperCamelCase : Tuple = {"""a""": {"""1""": 2}, """b""": 3} UpperCamelCase : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa
27
1
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : 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_=False , 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_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase : Dict = parent UpperCamelCase : Tuple = batch_size UpperCamelCase : Optional[int] = seq_length UpperCamelCase : Any = is_training UpperCamelCase : List[Any] = use_input_mask UpperCamelCase : Optional[Any] = use_token_type_ids UpperCamelCase : List[str] = use_labels UpperCamelCase : int = vocab_size UpperCamelCase : Tuple = hidden_size UpperCamelCase : int = num_hidden_layers UpperCamelCase : Optional[int] = num_attention_heads UpperCamelCase : str = intermediate_size UpperCamelCase : List[Any] = hidden_act UpperCamelCase : List[Any] = hidden_dropout_prob UpperCamelCase : int = attention_probs_dropout_prob UpperCamelCase : List[str] = max_position_embeddings UpperCamelCase : Dict = type_vocab_size UpperCamelCase : Tuple = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : int = num_labels UpperCamelCase : Any = num_choices UpperCamelCase : Union[str, Any] = scope def a_ ( self ): UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Any = None if self.use_input_mask: UpperCamelCase : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : int = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : Tuple = None UpperCamelCase : int = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Tuple = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( 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_ , ): UpperCamelCase : List[str] = BioGptForCausalLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() # create attention mask UpperCamelCase : str = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.seq_length // 2 UpperCamelCase : int = 0 # first forward pass UpperCamelCase , UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase : Dict = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCamelCase : Tuple = ids_tensor((1,) , SCREAMING_SNAKE_CASE_ ).item() + 1 UpperCamelCase : str = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCamelCase : Any = random_other_next_tokens # append to next input_ids and attn_mask UpperCamelCase : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ )] , dim=1 , ) # get two different outputs UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] # select random slice UpperCamelCase : List[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase : Tuple = output_from_no_past[:, -1, random_slice_idx].detach() UpperCamelCase : Optional[int] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = BioGptModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase : str = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # first forward pass UpperCamelCase : str = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Optional[int] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase : Optional[Any] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCamelCase : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase : int = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ )[ """last_hidden_state""" ] # select random slice UpperCamelCase : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase : Any = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Optional[int] = BioGptForCausalLM(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def a_ ( self , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = BioGptModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = self.num_labels UpperCamelCase : Optional[int] = BioGptForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self ): UpperCamelCase : List[str] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Dict = config_and_inputs UpperCamelCase : List[str] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Optional[int] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase : str = (BioGptForCausalLM,) if is_torch_available() else () lowercase : Optional[int] = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase : Optional[Any] = False def a_ ( self ): UpperCamelCase : int = BioGptModelTester(self ) UpperCamelCase : Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase : Optional[Any] = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*SCREAMING_SNAKE_CASE_ , gradient_checkpointing=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): UpperCamelCase : List[str] = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase : Union[str, Any] = """left""" # Define PAD Token = EOS Token = 50256 UpperCamelCase : List[Any] = tokenizer.eos_token UpperCamelCase : Tuple = model.config.eos_token_id # use different length sentences to test batching UpperCamelCase : Optional[int] = [ """Hello, my dog is a little""", """Today, I""", ] UpperCamelCase : Optional[int] = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = model.generate( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=inputs["""attention_mask"""].to(SCREAMING_SNAKE_CASE_ ) , ) UpperCamelCase : int = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() UpperCamelCase : Any = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_length=model.config.max_length - num_paddings ) UpperCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , [non_padded_sentence, padded_sentence] ) @slow def a_ ( self ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = BioGptModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase , UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase : Tuple = 3 UpperCamelCase : Optional[int] = input_dict["""input_ids"""] UpperCamelCase : Tuple = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCamelCase : Any = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def a_ ( self ): UpperCamelCase , UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase : Dict = 3 UpperCamelCase : str = """multi_label_classification""" UpperCamelCase : Optional[Any] = input_dict["""input_ids"""] UpperCamelCase : Dict = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCamelCase : Any = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[int] = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase : str = torch.tensor([[2, 4805, 9, 656, 21]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : str = 4_2384 UpperCamelCase : str = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) ) @slow def a_ ( self ): UpperCamelCase : int = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase : Tuple = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) UpperCamelCase : List[str] = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model.generate( **SCREAMING_SNAKE_CASE_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : Any = use_input_lengths UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = gelu_activation UpperCamelCase : Dict = sinusoidal_embeddings UpperCamelCase : Optional[int] = causal UpperCamelCase : List[Any] = asm UpperCamelCase : int = n_langs UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = n_special UpperCamelCase : Dict = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : List[str] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[str] = scope UpperCamelCase : Dict = bos_token_id def a_ ( self ): UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Union[str, Any] = None if self.use_input_lengths: UpperCamelCase : str = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[str] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a_ ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def a_ ( 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_ , ): UpperCamelCase : Optional[int] = XLMModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , lengths=SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( 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_ , ): UpperCamelCase : Optional[Any] = XLMWithLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( 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_ , ): UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( 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_ , ): UpperCamelCase : int = XLMForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , p_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , ) ((UpperCamelCase) , ) : Union[str, Any] = result_with_labels.to_tuple() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , ) : Tuple = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def a_ ( 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_ , ): UpperCamelCase : Union[str, Any] = XLMForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( 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_ , ): UpperCamelCase : int = self.num_labels UpperCamelCase : int = XLMForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : 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.num_labels) ) def a_ ( 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_ , ): UpperCamelCase : List[Any] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[Any] = config_and_inputs UpperCamelCase : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase : Optional[Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) return inputs_dict def a_ ( self ): UpperCamelCase : List[Any] = XLMModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , emb_dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_attentions in attentions] , [True] * len(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : Tuple = min_length + idx + 1 UpperCamelCase : Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_hidden_states in hidden_states] , [True] * len(SCREAMING_SNAKE_CASE_ ) , ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : List[str] = min_length + idx + 1 UpperCamelCase : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) , ) pass @slow def a_ ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = XLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Dict = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # the president UpperCamelCase : List[Any] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() __A : Any = logging.get_logger(__name__) __A : Any = [ ('''bert.bert''', '''visual_bert'''), ('''bert.cls''', '''cls'''), ('''bert.classifier''', '''cls'''), ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''), ('''position_embeddings_visual''', '''visual_position_embeddings'''), ('''projection''', '''visual_projection'''), ] __A : Optional[int] = [ '''nlvr2_coco_pre_trained.th''', '''nlvr2_fine_tuned.th''', '''nlvr2_pre_trained.th''', '''vcr_coco_pre_train.th''', '''vcr_fine_tune.th''', '''vcr_pre_train.th''', '''vqa_coco_pre_trained.th''', '''vqa_fine_tuned.th''', '''vqa_pre_trained.th''', ] def A_ ( snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : Optional[int] = torch.load(snake_case_ ,map_location="""cpu""" ) return sd def A_ ( snake_case_ : Optional[int] ,snake_case_ : Union[str, Any] ,snake_case_ : int=rename_keys_prefix ): '''simple docstring''' UpperCamelCase : List[Any] = OrderedDict() UpperCamelCase : Union[str, Any] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue UpperCamelCase : List[str] = key for name_pair in rename_keys_prefix: UpperCamelCase : Dict = new_key.replace(name_pair[0] ,name_pair[1] ) UpperCamelCase : Optional[int] = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately UpperCamelCase : List[Any] = new_d["""cls.predictions.bias"""] return new_d @torch.no_grad() def A_ ( snake_case_ : Dict ,snake_case_ : int ): '''simple docstring''' assert ( checkpoint_path.split("""/""" )[-1] in ACCEPTABLE_CHECKPOINTS ), f'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: UpperCamelCase : str = """pretraining""" if "vcr" in checkpoint_path: UpperCamelCase : Dict = {"""visual_embedding_dim""": 5_1_2} elif "vqa_advanced" in checkpoint_path: UpperCamelCase : Tuple = {"""visual_embedding_dim""": 2_0_4_8} elif "vqa" in checkpoint_path: UpperCamelCase : Dict = {"""visual_embedding_dim""": 2_0_4_8} elif "nlvr" in checkpoint_path: UpperCamelCase : Union[str, Any] = {"""visual_embedding_dim""": 1_0_2_4} else: raise NotImplementedError(f'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: UpperCamelCase : Any = {"""visual_embedding_dim""": 5_1_2} UpperCamelCase : Union[str, Any] = """multichoice""" elif "vqa_advanced" in checkpoint_path: UpperCamelCase : Tuple = {"""visual_embedding_dim""": 2_0_4_8} UpperCamelCase : int = """vqa_advanced""" elif "vqa" in checkpoint_path: UpperCamelCase : str = {"""visual_embedding_dim""": 2_0_4_8, """num_labels""": 3_1_2_9} UpperCamelCase : Optional[Any] = """vqa""" elif "nlvr" in checkpoint_path: UpperCamelCase : Tuple = { """visual_embedding_dim""": 1_0_2_4, """num_labels""": 2, } UpperCamelCase : List[str] = """nlvr""" UpperCamelCase : Any = VisualBertConfig(**snake_case_ ) # Load State Dict UpperCamelCase : Dict = load_state_dict(snake_case_ ) UpperCamelCase : Dict = get_new_dict(snake_case_ ,snake_case_ ) if model_type == "pretraining": UpperCamelCase : str = VisualBertForPreTraining(snake_case_ ) elif model_type == "vqa": UpperCamelCase : int = VisualBertForQuestionAnswering(snake_case_ ) elif model_type == "nlvr": UpperCamelCase : List[str] = VisualBertForVisualReasoning(snake_case_ ) elif model_type == "multichoice": UpperCamelCase : List[str] = VisualBertForMultipleChoice(snake_case_ ) model.load_state_dict(snake_case_ ) # Save Checkpoints Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) model.save_pretrained(snake_case_ ) if __name__ == "__main__": __A : int = argparse.ArgumentParser() # Required parameters parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''') __A : Dict = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
27
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
1
"""simple docstring""" import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py __A : List[Any] = '''.''' if __name__ == "__main__": __A : str = os.path.join(REPO_PATH, '''utils/documentation_tests.txt''') __A : Dict = [] __A : Union[str, Any] = [] with open(doctest_file_path) as fp: for line in fp: __A : int = line.strip() __A : List[str] = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: __A : Tuple = '''\n'''.join(non_existent_paths) raise ValueError(F'''`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}''') if all_paths != sorted(all_paths): raise ValueError('''Files in `utils/documentation_tests.txt` are not in alphabetical order.''')
27
"""simple docstring""" import torch from transformers import AutoModel class lowerCamelCase ( torch.nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_="sayef/fsner-bert-base-uncased" ): super(SCREAMING_SNAKE_CASE_ , self ).__init__() UpperCamelCase : int = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.nn.CosineSimilarity(3 , 1e-08 ) UpperCamelCase : Any = torch.nn.Softmax(dim=1 ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return self.bert(**SCREAMING_SNAKE_CASE_ ).last_hidden_state def a_ ( self , SCREAMING_SNAKE_CASE_ ): return token_embeddings.sum(2 , keepdim=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 ): return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = W_supports["""sizes"""].tolist() UpperCamelCase : List[str] = W_supports["""start_token_id"""].item() UpperCamelCase : List[Any] = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase : List[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = W_supports["""input_ids"""] == start_token_id UpperCamelCase : Optional[Any] = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: UpperCamelCase : int = 0 else: UpperCamelCase : Optional[int] = support_sizes[i - 1] UpperCamelCase : Tuple = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase : int = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase : Tuple = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase : List[str] = torch.vstack((p_starts, p_start) ) UpperCamelCase : Optional[Any] = torch.vstack((p_ends, p_end) ) else: UpperCamelCase : Optional[int] = p_start UpperCamelCase : Tuple = p_end return p_starts, p_ends
27
1
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A : List[Any] = { '''configuration_blenderbot''': [ '''BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BlenderbotConfig''', '''BlenderbotOnnxConfig''', ], '''tokenization_blenderbot''': ['''BlenderbotTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = ['''BlenderbotTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ '''BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BlenderbotForCausalLM''', '''BlenderbotForConditionalGeneration''', '''BlenderbotModel''', '''BlenderbotPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ '''TFBlenderbotForConditionalGeneration''', '''TFBlenderbotModel''', '''TFBlenderbotPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ '''FlaxBlenderbotForConditionalGeneration''', '''FlaxBlenderbotModel''', '''FlaxBlenderbotPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
1
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging __A : int = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase : Union[str, Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , 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_ = None , **SCREAMING_SNAKE_CASE_ , ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = 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 UpperCamelCase : Optional[Any] = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) UpperCamelCase : Optional[Any] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCamelCase : Tuple = 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}' ) UpperCamelCase : str = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: UpperCamelCase : 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 UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = text_embeddings.shape UpperCamelCase : Optional[Any] = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase : Optional[Any] = 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. UpperCamelCase : Dict = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase : List[str] if negative_prompt is None: UpperCamelCase : Any = [""""""] 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_ ): UpperCamelCase : 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: UpperCamelCase : str = negative_prompt UpperCamelCase : Tuple = text_input_ids.shape[-1] UpperCamelCase : Dict = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Tuple = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCamelCase : Optional[Any] = uncond_embeddings.shape[1] UpperCamelCase : str = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase : str = 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 UpperCamelCase : Optional[int] = 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`. UpperCamelCase : Union[str, Any] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase : Optional[Any] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) UpperCamelCase : List[str] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps UpperCamelCase : Any = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) UpperCamelCase : Tuple = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase : Any = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) UpperCamelCase : Tuple = latents_reference.to(self.device ) UpperCamelCase : Union[str, Any] = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images UpperCamelCase : str = (latents_shape[3] - latents_shape_reference[3]) // 2 UpperCamelCase : Union[str, Any] = (latents_shape[2] - latents_shape_reference[2]) // 2 UpperCamelCase : Tuple = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx UpperCamelCase : Optional[int] = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy UpperCamelCase : int = 0 if dx < 0 else dx UpperCamelCase : Union[str, Any] = 0 if dy < 0 else dy UpperCamelCase : List[Any] = max(-dx , 0 ) UpperCamelCase : Union[str, Any] = max(-dy , 0 ) # import pdb # pdb.set_trace() UpperCamelCase : List[str] = latents_reference[:, :, dy : dy + h, dx : dx + w] # 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 UpperCamelCase : List[Any] = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase : 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] UpperCamelCase : Dict = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase : Any = {} if accepts_eta: UpperCamelCase : List[Any] = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase : str = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase : Tuple = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase : int = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: UpperCamelCase , UpperCamelCase : Tuple = noise_pred.chunk(2 ) UpperCamelCase : Tuple = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase : Dict = 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_ ) UpperCamelCase : str = 1 / 0.18215 * latents UpperCamelCase : Dict = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase : Optional[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 UpperCamelCase : int = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: UpperCamelCase : Any = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).to( self.device ) UpperCamelCase , UpperCamelCase : Optional[int] = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: UpperCamelCase : List[str] = None if output_type == "pil": UpperCamelCase : List[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Optional[Any] = logging.get_logger(__name__) __A : Tuple = { '''andreasmadsen/efficient_mlm_m0.40''': ( '''https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json''' ), } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'roberta-prelayernorm' def __init__( self , SCREAMING_SNAKE_CASE_=5_0265 , 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-12 , 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_ , ): super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = vocab_size UpperCamelCase : List[str] = hidden_size UpperCamelCase : List[Any] = num_hidden_layers UpperCamelCase : List[str] = num_attention_heads UpperCamelCase : Tuple = hidden_act UpperCamelCase : List[str] = intermediate_size UpperCamelCase : List[Any] = hidden_dropout_prob UpperCamelCase : Dict = attention_probs_dropout_prob UpperCamelCase : Union[str, Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : Dict = initializer_range UpperCamelCase : List[str] = layer_norm_eps UpperCamelCase : Any = position_embedding_type UpperCamelCase : List[str] = use_cache UpperCamelCase : Union[str, Any] = classifier_dropout class lowerCamelCase ( _UpperCAmelCase ): @property def a_ ( self ): if self.task == "multiple-choice": UpperCamelCase : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCamelCase : Any = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
27
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = AudioLDMPipeline lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS lowercase : Tuple = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Tuple = 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, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCamelCase : int = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) UpperCamelCase : Optional[int] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) UpperCamelCase : Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Any = self.get_dummy_components() UpperCamelCase : int = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Tuple = audio[:10] UpperCamelCase : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[str] = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) UpperCamelCase : Tuple = prompt_embeds # forward UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_components() UpperCamelCase : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * ["""this is a negative prompt"""] UpperCamelCase : List[Any] = negative_prompt UpperCamelCase : str = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : str = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[Any] = [] for p in [prompt, negative_prompt]: UpperCamelCase : int = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Union[str, Any] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = text_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Tuple = embeds # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Optional[int] = self.get_dummy_components() UpperCamelCase : List[str] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """egg cracking""" UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Union[str, Any] = audio[:10] UpperCamelCase : Dict = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Union[str, Any] = self.get_dummy_components() UpperCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) UpperCamelCase : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts UpperCamelCase : Dict = 2 UpperCamelCase : List[str] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt UpperCamelCase : List[str] = 2 UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts UpperCamelCase : Any = 2 UpperCamelCase : str = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config.sampling_rate UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 UpperCamelCase : Optional[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = ["""hey"""] UpperCamelCase : Dict = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : str = output.audios.shape assert audio_shape == (1, 256) UpperCamelCase : Optional[Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 UpperCamelCase : str = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : List[str] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) UpperCamelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def a_ ( self ): UpperCamelCase : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 25 UpperCamelCase : Optional[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[7_7230:7_7240] UpperCamelCase : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) UpperCamelCase : Any = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def a_ ( self ): UpperCamelCase : Any = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) UpperCamelCase : str = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[2_7780:2_7790] UpperCamelCase : Tuple = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) UpperCamelCase : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
27
1
"""simple docstring""" from math import factorial def A_ ( snake_case_ : int ,snake_case_ : int ): '''simple docstring''' # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible 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.''', )
27
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' # load dataset UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
1
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
27
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : str = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
27
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __A : int = logging.get_logger(__name__) __A : Dict = { '''BAAI/AltCLIP''': '''https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json''', # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = 'altclip_text_model' def __init__( self , SCREAMING_SNAKE_CASE_=25_0002 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=24 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=4096 , 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_=0.02 , SCREAMING_SNAKE_CASE_=1e-05 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_="absolute" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=768 , **SCREAMING_SNAKE_CASE_ , ): super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = vocab_size UpperCamelCase : Tuple = hidden_size UpperCamelCase : Optional[Any] = num_hidden_layers UpperCamelCase : Tuple = num_attention_heads UpperCamelCase : Dict = hidden_act UpperCamelCase : Dict = intermediate_size UpperCamelCase : str = hidden_dropout_prob UpperCamelCase : Optional[int] = attention_probs_dropout_prob UpperCamelCase : Optional[int] = max_position_embeddings UpperCamelCase : str = type_vocab_size UpperCamelCase : List[Any] = initializer_range UpperCamelCase : str = initializer_factor UpperCamelCase : Optional[int] = layer_norm_eps UpperCamelCase : Any = position_embedding_type UpperCamelCase : Union[str, Any] = use_cache UpperCamelCase : List[str] = project_dim class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[Any] = 'altclip_vision_model' def __init__( self , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=224 , 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_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = hidden_size UpperCamelCase : str = intermediate_size UpperCamelCase : Union[str, Any] = projection_dim UpperCamelCase : List[Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : str = num_channels UpperCamelCase : List[str] = patch_size UpperCamelCase : List[str] = image_size UpperCamelCase : Optional[int] = initializer_range UpperCamelCase : Optional[int] = initializer_factor UpperCamelCase : List[Any] = attention_dropout UpperCamelCase : Union[str, Any] = layer_norm_eps UpperCamelCase : Dict = hidden_act @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : int = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get("""model_type""" ) == "altclip": UpperCamelCase : 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 lowerCamelCase ( _UpperCAmelCase ): lowercase : int = 'altclip' lowercase : str = True def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=2.6592 , **SCREAMING_SNAKE_CASE_ ): # If `_config_dict` exist, we use them for the backward compatibility. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot # of confusion!). UpperCamelCase : Dict = kwargs.pop("""text_config_dict""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = kwargs.pop("""vision_config_dict""" , SCREAMING_SNAKE_CASE_ ) super().__init__(**SCREAMING_SNAKE_CASE_ ) # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. if text_config_dict is not None: if text_config is None: UpperCamelCase : List[str] = {} # This is the complete result when using `text_config_dict`. UpperCamelCase : int = AltCLIPTextConfig(**SCREAMING_SNAKE_CASE_ ).to_dict() # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. for key, value in _text_config_dict.items(): if key in text_config and value != text_config[key] and key not in ["transformers_version"]: # If specified in `text_config_dict` if key in text_config_dict: UpperCamelCase : List[Any] = ( f'`{key}` is found in both `text_config_dict` and `text_config` but with different values. ' f'The value `text_config_dict["{key}"]` will be used instead.' ) # If inferred from default argument values (just to be super careful) else: UpperCamelCase : Any = ( f'`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The ' f'value `text_config["{key}"]` will be overriden.' ) logger.warning(SCREAMING_SNAKE_CASE_ ) # Update all values in `text_config` with the ones in `_text_config_dict`. text_config.update(_text_config_dict ) if vision_config_dict is not None: if vision_config is None: UpperCamelCase : List[str] = {} # This is the complete result when using `vision_config_dict`. UpperCamelCase : Dict = AltCLIPVisionConfig(**SCREAMING_SNAKE_CASE_ ).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: UpperCamelCase : List[Any] = { str(SCREAMING_SNAKE_CASE_ ): value for key, value in _vision_config_dict["""id2label"""].items() } # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. for key, value in _vision_config_dict.items(): if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]: # If specified in `vision_config_dict` if key in vision_config_dict: UpperCamelCase : int = ( f'`{key}` is found in both `vision_config_dict` and `vision_config` but with different ' f'values. The value `vision_config_dict["{key}"]` will be used instead.' ) # If inferred from default argument values (just to be super careful) else: UpperCamelCase : List[Any] = ( f'`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. ' f'The value `vision_config["{key}"]` will be overriden.' ) logger.warning(SCREAMING_SNAKE_CASE_ ) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict ) if text_config is None: UpperCamelCase : int = {} logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.""" ) if vision_config is None: UpperCamelCase : str = {} logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.""" ) UpperCamelCase : str = AltCLIPTextConfig(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = AltCLIPVisionConfig(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = projection_dim UpperCamelCase : Union[str, Any] = logit_scale_init_value UpperCamelCase : Union[str, Any] = 1.0 @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Union[str, Any] = copy.deepcopy(self.__dict__ ) UpperCamelCase : Dict = self.text_config.to_dict() UpperCamelCase : Union[str, Any] = self.vision_config.to_dict() UpperCamelCase : Any = self.__class__.model_type return output
27
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
27
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = KandinskyImgaImgPipeline lowercase : Tuple = ['prompt', 'image_embeds', 'negative_image_embeds', 'image'] lowercase : str = [ 'prompt', 'negative_prompt', 'image_embeds', 'negative_image_embeds', 'image', ] lowercase : Union[str, Any] = [ 'generator', 'height', 'width', 'strength', 'guidance_scale', 'negative_prompt', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] lowercase : Dict = False @property def a_ ( self ): return 32 @property def a_ ( self ): return 32 @property def a_ ( self ): return self.time_input_dim @property def a_ ( self ): return self.time_input_dim * 4 @property def a_ ( self ): return 100 @property def a_ ( self ): UpperCamelCase : List[str] = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Optional[Any] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) UpperCamelCase : int = MultilingualCLIP(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = text_encoder.eval() return text_encoder @property def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : List[Any] = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } UpperCamelCase : Optional[int] = UNetaDConditionModel(**SCREAMING_SNAKE_CASE_ ) return model @property def a_ ( self ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Any = VQModel(**self.dummy_movq_kwargs ) return model def a_ ( self ): UpperCamelCase : Optional[int] = self.dummy_text_encoder UpperCamelCase : Optional[int] = self.dummy_tokenizer UpperCamelCase : Union[str, Any] = self.dummy_unet UpperCamelCase : Optional[Any] = self.dummy_movq UpperCamelCase : List[str] = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.00085, """beta_end""": 0.012, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } UpperCamelCase : Optional[Any] = DDIMScheduler(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : Any = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(SCREAMING_SNAKE_CASE_ ) # create init_image UpperCamelCase : Dict = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : Optional[int] = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_ ) ).convert("""RGB""" ).resize((256, 256) ) if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : int = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : int = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def a_ ( self ): UpperCamelCase : Tuple = """cpu""" UpperCamelCase : Dict = self.get_dummy_components() UpperCamelCase : Optional[int] = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Optional[Any] = output.images UpperCamelCase : int = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) , return_dict=SCREAMING_SNAKE_CASE_ , )[0] UpperCamelCase : Tuple = image[0, -3:, -3:, -1] UpperCamelCase : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCamelCase : Dict = np.array( [0.61474943, 0.6073539, 0.43308544, 0.5928269, 0.47493595, 0.46755973, 0.4613838, 0.45368797, 0.50119233] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self ): UpperCamelCase : List[str] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) UpperCamelCase : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) UpperCamelCase : List[Any] = """A red cartoon frog, 4k""" UpperCamelCase : List[Any] = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) UpperCamelCase : List[str] = pipeline.to(SCREAMING_SNAKE_CASE_ ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCamelCase , UpperCamelCase : Optional[int] = pipe_prior( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() UpperCamelCase : Optional[int] = pipeline( SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , image_embeds=SCREAMING_SNAKE_CASE_ , negative_image_embeds=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) UpperCamelCase : str = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCamelCase ( _UpperCAmelCase ): 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_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Union[str, Any] = use_token_type_ids UpperCamelCase : Dict = use_labels UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : str = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : int = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Dict = num_labels UpperCamelCase : Tuple = num_choices UpperCamelCase : Optional[int] = scope UpperCamelCase : List[Any] = q_groups UpperCamelCase : Tuple = k_groups UpperCamelCase : Any = v_groups UpperCamelCase : List[str] = post_attention_groups UpperCamelCase : Tuple = intermediate_groups UpperCamelCase : int = output_groups def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = SqueezeBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = SqueezeBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = 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 a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = SqueezeBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : str = SqueezeBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = 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.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = SqueezeBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = config_and_inputs UpperCamelCase : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase : Dict = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : str = True lowercase : str = False def a_ ( self ): UpperCamelCase : Any = SqueezeBertModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = SqueezeBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) UpperCamelCase : Dict = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
1
"""simple docstring""" def A_ ( snake_case_ : list ): '''simple docstring''' def merge(snake_case_ : list ,snake_case_ : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(snake_case_ ) <= 1: return collection UpperCamelCase : Union[str, Any] = len(snake_case_ ) // 2 return merge(merge_sort(collection[:mid] ) ,merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() __A : Dict = input('''Enter numbers separated by a comma:\n''').strip() __A : Tuple = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
27
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : Dict = { '''configuration_swiftformer''': [ '''SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwiftFormerConfig''', '''SwiftFormerOnnxConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Dict = [ '''SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwiftFormerForImageClassification''', '''SwiftFormerModel''', '''SwiftFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys __A : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Optional[int] = { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = 'mvp' lowercase : Optional[Any] = ['past_key_values'] lowercase : Union[str, Any] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , SCREAMING_SNAKE_CASE_=5_0267 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=800 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Dict = max_position_embeddings UpperCamelCase : Optional[int] = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : Any = encoder_layers UpperCamelCase : List[Any] = encoder_attention_heads UpperCamelCase : Optional[Any] = decoder_ffn_dim UpperCamelCase : Optional[int] = decoder_layers UpperCamelCase : Dict = decoder_attention_heads UpperCamelCase : List[str] = dropout UpperCamelCase : List[str] = attention_dropout UpperCamelCase : List[Any] = activation_dropout UpperCamelCase : Dict = activation_function UpperCamelCase : List[str] = init_std UpperCamelCase : int = encoder_layerdrop UpperCamelCase : Dict = decoder_layerdrop UpperCamelCase : Any = classifier_dropout UpperCamelCase : Tuple = use_cache UpperCamelCase : Dict = encoder_layers UpperCamelCase : Tuple = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase : Optional[Any] = use_prompt UpperCamelCase : Any = prompt_length UpperCamelCase : List[Any] = prompt_mid_dim super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , forced_eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' """The config can simply be saved and uploaded again to be fixed.""" )
27
1
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[List[np.ndarray], torch.FloatTensor] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
27
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A : Optional[Any] = 16 __A : str = 32 def A_ ( snake_case_ : Accelerator ,snake_case_ : int = 1_6 ): '''simple docstring''' UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[int] = load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(snake_case_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : Union[str, Any] = tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=snake_case_ ,max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase : Optional[Any] = datasets.map( snake_case_ ,batched=snake_case_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase : str = tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(snake_case_ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase : Optional[Any] = 1_6 elif accelerator.mixed_precision != "no": UpperCamelCase : Any = 8 else: UpperCamelCase : Optional[Any] = None return tokenizer.pad( snake_case_ ,padding="""longest""" ,max_length=snake_case_ ,pad_to_multiple_of=snake_case_ ,return_tensors="""pt""" ,) # Instantiate dataloaders. UpperCamelCase : str = DataLoader( tokenized_datasets["""train"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) UpperCamelCase : Dict = DataLoader( tokenized_datasets["""validation"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A : int = mocked_dataloaders # noqa: F811 def A_ ( snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,snake_case_ ) == "1": UpperCamelCase : Union[str, Any] = 2 # New Code # UpperCamelCase : Dict = int(args.gradient_accumulation_steps ) UpperCamelCase : List[Any] = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=snake_case_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : Union[str, Any] = config["""lr"""] UpperCamelCase : int = int(config["""num_epochs"""] ) UpperCamelCase : int = int(config["""seed"""] ) UpperCamelCase : List[Any] = int(config["""batch_size"""] ) UpperCamelCase : Optional[int] = evaluate.load("""glue""" ,"""mrpc""" ) set_seed(snake_case_ ) UpperCamelCase , UpperCamelCase : Dict = get_dataloaders(snake_case_ ,snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" ,return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase : Tuple = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase : List[Any] = AdamW(params=model.parameters() ,lr=snake_case_ ) # Instantiate scheduler UpperCamelCase : str = get_linear_schedule_with_warmup( optimizer=snake_case_ ,num_warmup_steps=1_0_0 ,num_training_steps=(len(snake_case_ ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() with LocalSGD( accelerator=snake_case_ ,model=snake_case_ ,local_sgd_steps=snake_case_ ,enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case_ ): UpperCamelCase : Optional[Any] = model(**snake_case_ ) UpperCamelCase : Optional[int] = output.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase : Any = model(**snake_case_ ) UpperCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case_ ,references=snake_case_ ,) UpperCamelCase : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' ,snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" ,type=snake_case_ ,default=snake_case_ ,choices=["""no""", """fp16""", """bf16""", """fp8"""] ,help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" ,) # New Code # parser.add_argument( """--gradient_accumulation_steps""" ,type=snake_case_ ,default=1 ,help="""The number of minibatches to be ran before gradients are accumulated.""" ,) parser.add_argument( """--local_sgd_steps""" ,type=snake_case_ ,default=8 ,help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) UpperCamelCase : Dict = parser.parse_args() UpperCamelCase : List[Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
27
1
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __A : Any = logging.get_logger(__name__) __A : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __A : Any = {'''allegro/herbert-base-cased''': 514} __A : Optional[Any] = {} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_INIT_CONFIGURATION lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = HerbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = [self.cls_token_id] UpperCamelCase : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): 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] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def A_ ( snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : int = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """_float_tensor""", """decoder.output_projection.weight""", ] for k in ignore_keys: state_dict.pop(snake_case_ ,snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase , UpperCamelCase : str = emb.weight.shape UpperCamelCase : List[Any] = nn.Linear(snake_case_ ,snake_case_ ,bias=snake_case_ ) UpperCamelCase : List[Any] = emb.weight.data return lin_layer def A_ ( snake_case_ : Dict ,snake_case_ : Optional[Any]="facebook/mbart-large-en-ro" ,snake_case_ : List[Any]=False ,snake_case_ : Optional[Any]=False ): '''simple docstring''' UpperCamelCase : Dict = torch.load(snake_case_ ,map_location="""cpu""" )["""model"""] remove_ignore_keys_(snake_case_ ) UpperCamelCase : int = state_dict["""encoder.embed_tokens.weight"""].shape[0] UpperCamelCase : int = MBartConfig.from_pretrained(snake_case_ ,vocab_size=snake_case_ ) if mbart_aa and finetuned: UpperCamelCase : Union[str, Any] = """relu""" UpperCamelCase : Tuple = state_dict["""decoder.embed_tokens.weight"""] UpperCamelCase : List[Any] = MBartForConditionalGeneration(snake_case_ ) model.model.load_state_dict(snake_case_ ) if finetuned: UpperCamelCase : Tuple = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": __A : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default='''facebook/mbart-large-cc25''', type=str, help='''Which huggingface architecture to use: mbart-large''', ) parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''') parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''') __A : List[Any] = parser.parse_args() __A : Any = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
27
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase , UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A , __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A , __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
27
1
"""simple docstring""" import argparse import json import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( VideoMAEConfig, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEImageProcessor, ) def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Optional[int] = VideoMAEConfig() set_architecture_configs(snake_case_ ,snake_case_ ) if "finetuned" not in model_name: UpperCamelCase : Tuple = False if "finetuned" in model_name: UpperCamelCase : Union[str, Any] = """huggingface/label-files""" if "kinetics" in model_name: UpperCamelCase : Dict = 4_0_0 UpperCamelCase : str = """kinetics400-id2label.json""" elif "ssv2" in model_name: UpperCamelCase : int = 1_7_4 UpperCamelCase : int = """something-something-v2-id2label.json""" else: raise ValueError("""Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned.""" ) UpperCamelCase : List[str] = json.load(open(hf_hub_download(snake_case_ ,snake_case_ ,repo_type="""dataset""" ) ,"""r""" ) ) UpperCamelCase : Union[str, Any] = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCamelCase : List[Any] = idalabel UpperCamelCase : Optional[int] = {v: k for k, v in idalabel.items()} return config def A_ ( snake_case_ : Optional[int] ,snake_case_ : List[Any] ): '''simple docstring''' if "small" in model_name: UpperCamelCase : List[Any] = 3_8_4 UpperCamelCase : Any = 1_5_3_6 UpperCamelCase : Any = 1_2 UpperCamelCase : Union[str, Any] = 1_6 UpperCamelCase : List[str] = 1_2 UpperCamelCase : Union[str, Any] = 3 UpperCamelCase : Any = 1_9_2 UpperCamelCase : Tuple = 7_6_8 elif "large" in model_name: UpperCamelCase : str = 1_0_2_4 UpperCamelCase : Union[str, Any] = 4_0_9_6 UpperCamelCase : Optional[int] = 2_4 UpperCamelCase : Dict = 1_6 UpperCamelCase : Optional[int] = 1_2 UpperCamelCase : Optional[int] = 8 UpperCamelCase : int = 5_1_2 UpperCamelCase : List[Any] = 2_0_4_8 elif "huge" in model_name: UpperCamelCase : Tuple = 1_2_8_0 UpperCamelCase : List[str] = 5_1_2_0 UpperCamelCase : List[str] = 3_2 UpperCamelCase : int = 1_6 UpperCamelCase : Union[str, Any] = 1_2 UpperCamelCase : int = 8 UpperCamelCase : Union[str, Any] = 6_4_0 UpperCamelCase : Optional[Any] = 2_5_6_0 elif "base" not in model_name: raise ValueError("""Model name should include either \"small\", \"base\", \"large\", or \"huge\"""" ) def A_ ( snake_case_ : Dict ): '''simple docstring''' if "encoder." in name: UpperCamelCase : List[str] = name.replace("""encoder.""" ,"""""" ) if "cls_token" in name: UpperCamelCase : Tuple = name.replace("""cls_token""" ,"""videomae.embeddings.cls_token""" ) if "decoder_pos_embed" in name: UpperCamelCase : Optional[Any] = name.replace("""decoder_pos_embed""" ,"""decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: UpperCamelCase : Optional[int] = name.replace("""pos_embed""" ,"""videomae.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: UpperCamelCase : List[Any] = name.replace("""patch_embed.proj""" ,"""videomae.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: UpperCamelCase : Optional[int] = name.replace("""patch_embed.norm""" ,"""videomae.embeddings.norm""" ) if "decoder.blocks" in name: UpperCamelCase : List[str] = name.replace("""decoder.blocks""" ,"""decoder.decoder_layers""" ) if "blocks" in name: UpperCamelCase : str = name.replace("""blocks""" ,"""videomae.encoder.layer""" ) if "attn.proj" in name: UpperCamelCase : Any = name.replace("""attn.proj""" ,"""attention.output.dense""" ) if "attn" in name and "bias" not in name: UpperCamelCase : Union[str, Any] = name.replace("""attn""" ,"""attention.self""" ) if "attn" in name: UpperCamelCase : Tuple = name.replace("""attn""" ,"""attention.attention""" ) if "norm1" in name: UpperCamelCase : str = name.replace("""norm1""" ,"""layernorm_before""" ) if "norm2" in name: UpperCamelCase : Any = name.replace("""norm2""" ,"""layernorm_after""" ) if "mlp.fc1" in name: UpperCamelCase : int = name.replace("""mlp.fc1""" ,"""intermediate.dense""" ) if "mlp.fc2" in name: UpperCamelCase : Union[str, Any] = name.replace("""mlp.fc2""" ,"""output.dense""" ) if "decoder_embed" in name: UpperCamelCase : Dict = name.replace("""decoder_embed""" ,"""decoder.decoder_embed""" ) if "decoder_norm" in name: UpperCamelCase : int = name.replace("""decoder_norm""" ,"""decoder.decoder_norm""" ) if "decoder_pred" in name: UpperCamelCase : Optional[int] = name.replace("""decoder_pred""" ,"""decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name and "fc" not in name: UpperCamelCase : Tuple = name.replace("""norm.weight""" ,"""videomae.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name and "fc" not in name: UpperCamelCase : int = name.replace("""norm.bias""" ,"""videomae.layernorm.bias""" ) if "head" in name and "decoder" not in name: UpperCamelCase : Dict = name.replace("""head""" ,"""classifier""" ) return name def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int ): '''simple docstring''' for key in orig_state_dict.copy().keys(): UpperCamelCase : Tuple = orig_state_dict.pop(snake_case_ ) if key.startswith("""encoder.""" ): UpperCamelCase : Union[str, Any] = key.replace("""encoder.""" ,"""""" ) if "qkv" in key: UpperCamelCase : Optional[Any] = key.split(""".""" ) if key.startswith("""decoder.blocks""" ): UpperCamelCase : Optional[int] = config.decoder_hidden_size UpperCamelCase : List[str] = int(key_split[2] ) UpperCamelCase : Optional[Any] = """decoder.decoder_layers.""" if "weight" in key: UpperCamelCase : Union[str, Any] = val[:dim, :] UpperCamelCase : Optional[int] = val[dim : dim * 2, :] UpperCamelCase : Optional[int] = val[-dim:, :] else: UpperCamelCase : List[str] = config.hidden_size UpperCamelCase : Optional[int] = int(key_split[1] ) UpperCamelCase : List[Any] = """videomae.encoder.layer.""" if "weight" in key: UpperCamelCase : str = val[:dim, :] UpperCamelCase : Optional[int] = val[dim : dim * 2, :] UpperCamelCase : List[str] = val[-dim:, :] else: UpperCamelCase : Tuple = val return orig_state_dict def A_ ( ): '''simple docstring''' UpperCamelCase : List[str] = hf_hub_download( repo_id="""hf-internal-testing/spaghetti-video""" ,filename="""eating_spaghetti.npy""" ,repo_type="""dataset""" ) UpperCamelCase : List[Any] = np.load(snake_case_ ) return list(snake_case_ ) def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Optional[Any] ,snake_case_ : Optional[Any] ,snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : int = get_videomae_config(snake_case_ ) if "finetuned" in model_name: UpperCamelCase : Any = VideoMAEForVideoClassification(snake_case_ ) else: UpperCamelCase : Dict = VideoMAEForPreTraining(snake_case_ ) # download original checkpoint, hosted on Google Drive UpperCamelCase : str = """pytorch_model.bin""" gdown.cached_download(snake_case_ ,snake_case_ ,quiet=snake_case_ ) UpperCamelCase : Optional[Any] = torch.load(snake_case_ ,map_location="""cpu""" ) if "model" in files: UpperCamelCase : Optional[Any] = files["""model"""] else: UpperCamelCase : Optional[Any] = files["""module"""] UpperCamelCase : Optional[int] = convert_state_dict(snake_case_ ,snake_case_ ) model.load_state_dict(snake_case_ ) model.eval() # verify model on basic input UpperCamelCase : Dict = VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] ,image_std=[0.5, 0.5, 0.5] ) UpperCamelCase : Optional[int] = prepare_video() UpperCamelCase : Any = image_processor(snake_case_ ,return_tensors="""pt""" ) if "finetuned" not in model_name: UpperCamelCase : Tuple = hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos""" ,filename="""bool_masked_pos.pt""" ) UpperCamelCase : Optional[Any] = torch.load(snake_case_ ) UpperCamelCase : Any = model(**snake_case_ ) UpperCamelCase : List[Any] = outputs.logits UpperCamelCase : Tuple = [ """videomae-small-finetuned-kinetics""", """videomae-small-finetuned-ssv2""", # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600) """videomae-base-short""", """videomae-base-short-finetuned-kinetics""", """videomae-base""", """videomae-base-finetuned-kinetics""", """videomae-large""", """videomae-large-finetuned-kinetics""", """videomae-huge-finetuned-kinetics""", # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400) """videomae-base-short-ssv2""", """videomae-base-short-finetuned-ssv2""", """videomae-base-ssv2""", """videomae-base-finetuned-ssv2""", ] # NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5] if model_name == "videomae-small-finetuned-kinetics": UpperCamelCase : Tuple = torch.Size([1, 4_0_0] ) UpperCamelCase : Optional[Any] = torch.tensor([-0.9291, -0.4061, -0.9307] ) elif model_name == "videomae-small-finetuned-ssv2": UpperCamelCase : Optional[Any] = torch.Size([1, 1_7_4] ) UpperCamelCase : Dict = torch.tensor([0.2671, -0.4689, -0.8235] ) elif model_name == "videomae-base": UpperCamelCase : List[Any] = torch.Size([1, 1_4_0_8, 1_5_3_6] ) UpperCamelCase : Dict = torch.tensor([[0.7739, 0.7968, 0.7089], [0.6701, 0.7487, 0.6209], [0.4287, 0.5158, 0.4773]] ) elif model_name == "videomae-base-short": UpperCamelCase : Optional[int] = torch.Size([1, 1_4_0_8, 1_5_3_6] ) UpperCamelCase : Optional[int] = torch.tensor([[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]] ) # we verified the loss both for normalized and unnormalized targets for this one UpperCamelCase : str = torch.tensor([0.5142] ) if config.norm_pix_loss else torch.tensor([0.6469] ) elif model_name == "videomae-large": UpperCamelCase : Any = torch.Size([1, 1_4_0_8, 1_5_3_6] ) UpperCamelCase : str = torch.tensor([[0.7149, 0.7997, 0.6966], [0.6768, 0.7869, 0.6948], [0.5139, 0.6221, 0.5605]] ) elif model_name == "videomae-large-finetuned-kinetics": UpperCamelCase : Optional[int] = torch.Size([1, 4_0_0] ) UpperCamelCase : Union[str, Any] = torch.tensor([0.0771, 0.0011, -0.3625] ) elif model_name == "videomae-huge-finetuned-kinetics": UpperCamelCase : int = torch.Size([1, 4_0_0] ) UpperCamelCase : Tuple = torch.tensor([0.2433, 0.1632, -0.4894] ) elif model_name == "videomae-base-short-finetuned-kinetics": UpperCamelCase : Union[str, Any] = torch.Size([1, 4_0_0] ) UpperCamelCase : Any = torch.tensor([0.6588, 0.0990, -0.2493] ) elif model_name == "videomae-base-finetuned-kinetics": UpperCamelCase : Optional[int] = torch.Size([1, 4_0_0] ) UpperCamelCase : Optional[int] = torch.tensor([0.3669, -0.0688, -0.2421] ) elif model_name == "videomae-base-short-ssv2": UpperCamelCase : Dict = torch.Size([1, 1_4_0_8, 1_5_3_6] ) UpperCamelCase : List[Any] = torch.tensor([[0.4712, 0.5296, 0.5786], [0.2278, 0.2729, 0.4026], [0.0352, 0.0730, 0.2506]] ) elif model_name == "videomae-base-short-finetuned-ssv2": UpperCamelCase : int = torch.Size([1, 1_7_4] ) UpperCamelCase : Union[str, Any] = torch.tensor([-0.0537, -0.1539, -0.3266] ) elif model_name == "videomae-base-ssv2": UpperCamelCase : int = torch.Size([1, 1_4_0_8, 1_5_3_6] ) UpperCamelCase : Union[str, Any] = torch.tensor([[0.8131, 0.8727, 0.8546], [0.7366, 0.9377, 0.8870], [0.5935, 0.8874, 0.8564]] ) elif model_name == "videomae-base-finetuned-ssv2": UpperCamelCase : int = torch.Size([1, 1_7_4] ) UpperCamelCase : Any = torch.tensor([0.1961, -0.8337, -0.6389] ) else: raise ValueError(f'Model name not supported. Should be one of {model_names}' ) # verify logits assert logits.shape == expected_shape if "finetuned" in model_name: assert torch.allclose(logits[0, :3] ,snake_case_ ,atol=1e-4 ) else: print("""Logits:""" ,logits[0, :3, :3] ) assert torch.allclose(logits[0, :3, :3] ,snake_case_ ,atol=1e-4 ) print("""Logits ok!""" ) # verify loss, if applicable if model_name == "videomae-base-short": UpperCamelCase : Tuple = outputs.loss assert torch.allclose(snake_case_ ,snake_case_ ,atol=1e-4 ) print("""Loss ok!""" ) if pytorch_dump_folder_path is not None: print(f'Saving model and image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case_ ) model.save_pretrained(snake_case_ ) if push_to_hub: print("""Pushing to the hub...""" ) model.push_to_hub(snake_case_ ,organization="""nielsr""" ) if __name__ == "__main__": __A : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&amp;export=download&amp;confirm=t&amp;uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4''', type=str, help=( '''URL of the original PyTorch checkpoint (on Google Drive) you\'d like to convert. Should be a direct''' ''' download link.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''/Users/nielsrogge/Documents/VideoMAE/Test''', type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--model_name''', default='''videomae-base''', type=str, help='''Name of the model.''') parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) __A : Optional[Any] = parser.parse_args() convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
27
"""simple docstring""" import argparse import os import re __A : Any = '''src/transformers''' # Pattern that looks at the indentation in a line. __A : Tuple = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : List[Any] = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : str ,snake_case_ : str="" ,snake_case_ : Any=None ,snake_case_ : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Tuple = ["""\n""".join(lines[:index] )] else: UpperCamelCase : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Dict = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = [lines[index + 1]] index += 1 else: UpperCamelCase : str = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : List[Any] ): '''simple docstring''' def _inner(snake_case_ : List[str] ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Optional[int] ): return x if key is None: UpperCamelCase : List[str] = noop # Constants are all uppercase, they go first. UpperCamelCase : List[str] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : Tuple = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : int = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Union[str, Any] = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : Any ): UpperCamelCase : Union[str, Any] = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : str = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : Optional[int] = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : int = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Tuple = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : List[Any] = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : List[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : Optional[int] = keys[:-1] UpperCamelCase : Union[str, Any] = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : Any = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int=True ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : int = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Dict = main_blocks[block_idx] UpperCamelCase : Dict = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : List[str] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : Optional[Any] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Optional[Any] = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : List[Any] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Optional[Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Optional[Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Any = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : Union[str, Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Optional[int] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : List[Any] = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
1
"""simple docstring""" def A_ ( snake_case_ : int ,snake_case_ : int ): '''simple docstring''' if b == 0: return 1 if (b % 2) == 0: return actual_power(snake_case_ ,int(b / 2 ) ) * actual_power(snake_case_ ,int(b / 2 ) ) else: return a * actual_power(snake_case_ ,int(b / 2 ) ) * actual_power(snake_case_ ,int(b / 2 ) ) def A_ ( snake_case_ : int ,snake_case_ : int ): '''simple docstring''' if b < 0: return 1 / actual_power(snake_case_ ,snake_case_ ) return actual_power(snake_case_ ,snake_case_ ) if __name__ == "__main__": print(power(-2, -3))
27
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
1
"""simple docstring""" import math def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : int = 0 UpperCamelCase : Dict = 0 while num > 0: UpperCamelCase : List[Any] = num % 8 UpperCamelCase : Tuple = octal + (remainder * math.floor(math.pow(1_0 ,snake_case_ ) )) counter += 1 UpperCamelCase : Optional[Any] = math.floor(num / 8 ) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f'0o{int(snake_case_ )}' def A_ ( ): '''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(6_5 ) ) # = 101 print("""\n216 in octal is:""" ) print(decimal_to_octal(2_1_6 ) ) # = 330 print("""\n512 in octal is:""" ) print(decimal_to_octal(5_1_2 ) ) # = 1000 print("""\n""" ) if __name__ == "__main__": main()
27
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( 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_ = None , 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_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : 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_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
1
"""simple docstring""" import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants __A : Optional[int] = Mapping[str, np.ndarray] __A : Optional[Any] = Mapping[str, Any] # Is a nested dict. __A : List[Any] = 0.01 @dataclasses.dataclass(frozen=_UpperCAmelCase ) class lowerCamelCase : lowercase : np.ndarray # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. lowercase : np.ndarray # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. lowercase : np.ndarray # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. lowercase : np.ndarray # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. lowercase : np.ndarray # [num_res, num_atom_type] # Chain indices for multi-chain predictions lowercase : Optional[np.ndarray] = None # Optional remark about the protein. Included as a comment in output PDB # files lowercase : Optional[str] = None # Templates used to generate this protein (prediction-only) lowercase : Optional[Sequence[str]] = None # Chain corresponding to each parent lowercase : Optional[Sequence[int]] = None def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Optional[Any] = R"""(\[[A-Z]+\]\n)""" UpperCamelCase : List[str] = [tag.strip() for tag in re.split(snake_case_ ,snake_case_ ) if len(snake_case_ ) > 0] UpperCamelCase : Iterator[Tuple[str, List[str]]] = zip(tags[0::2] ,[l.split("""\n""" ) for l in tags[1::2]] ) UpperCamelCase : List[str] = ["N", "CA", "C"] UpperCamelCase : List[str] = None UpperCamelCase : Optional[int] = None UpperCamelCase : Any = None for g in groups: if "[PRIMARY]" == g[0]: UpperCamelCase : str = g[1][0].strip() for i in range(len(snake_case_ ) ): if seq[i] not in residue_constants.restypes: UpperCamelCase : Dict = """X""" # FIXME: strings are immutable UpperCamelCase : str = np.array( [residue_constants.restype_order.get(snake_case_ ,residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: UpperCamelCase : List[List[float]] = [] for axis in range(3 ): tertiary.append(list(map(snake_case_ ,g[1][axis].split() ) ) ) UpperCamelCase : Dict = np.array(snake_case_ ) UpperCamelCase : Tuple = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(snake_case_ ): UpperCamelCase : str = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: UpperCamelCase : Any = np.array(list(map({"""-""": 0, """+""": 1}.get ,g[1][0].strip() ) ) ) UpperCamelCase : Tuple = np.zeros( ( len(snake_case_ ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(snake_case_ ): UpperCamelCase : List[Any] = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=snake_case_ ,atom_mask=snake_case_ ,aatype=snake_case_ ,residue_index=np.arange(len(snake_case_ ) ) ,b_factors=snake_case_ ,) def A_ ( snake_case_ : Protein ,snake_case_ : int = 0 ): '''simple docstring''' UpperCamelCase : List[str] = [] UpperCamelCase : Dict = prot.remark if remark is not None: pdb_headers.append(f'REMARK {remark}' ) UpperCamelCase : Optional[int] = prot.parents UpperCamelCase : List[Any] = prot.parents_chain_index if parents is not None and parents_chain_index is not None: UpperCamelCase : List[Any] = [p for i, p in zip(snake_case_ ,snake_case_ ) if i == chain_id] if parents is None or len(snake_case_ ) == 0: UpperCamelCase : Any = ["""N/A"""] pdb_headers.append(f'PARENT {" ".join(snake_case_ )}' ) return pdb_headers def A_ ( snake_case_ : Protein ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[str] = [] UpperCamelCase : Dict = pdb_str.split("""\n""" ) UpperCamelCase : Optional[int] = prot.remark if remark is not None: out_pdb_lines.append(f'REMARK {remark}' ) UpperCamelCase : List[List[str]] if prot.parents is not None and len(prot.parents ) > 0: UpperCamelCase : Optional[int] = [] if prot.parents_chain_index is not None: UpperCamelCase : Dict[str, List[str]] = {} for p, i in zip(prot.parents ,prot.parents_chain_index ): parent_dict.setdefault(str(snake_case_ ) ,[] ) parent_dict[str(snake_case_ )].append(snake_case_ ) UpperCamelCase : str = max([int(snake_case_ ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): UpperCamelCase : Optional[int] = parent_dict.get(str(snake_case_ ) ,["""N/A"""] ) parents_per_chain.append(snake_case_ ) else: parents_per_chain.append(list(prot.parents ) ) else: UpperCamelCase : List[str] = [["""N/A"""]] def make_parent_line(snake_case_ : Sequence[str] ) -> str: return f'PARENT {" ".join(snake_case_ )}' out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) UpperCamelCase : Any = 0 for i, l in enumerate(snake_case_ ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(snake_case_ ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(snake_case_ ): UpperCamelCase : str = parents_per_chain[chain_counter] else: UpperCamelCase : Tuple = ["""N/A"""] out_pdb_lines.append(make_parent_line(snake_case_ ) ) return "\n".join(snake_case_ ) def A_ ( snake_case_ : Protein ): '''simple docstring''' UpperCamelCase : Dict = residue_constants.restypes + ["""X"""] def res_atoa(snake_case_ : int ) -> str: return residue_constants.restype_atoa.get(restypes[r] ,"""UNK""" ) UpperCamelCase : Dict = residue_constants.atom_types UpperCamelCase : List[str] = [] UpperCamelCase : int = prot.atom_mask UpperCamelCase : str = prot.aatype UpperCamelCase : Tuple = prot.atom_positions UpperCamelCase : List[str] = prot.residue_index.astype(np.intaa ) UpperCamelCase : int = prot.b_factors UpperCamelCase : Union[str, Any] = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError("""Invalid aatypes.""" ) UpperCamelCase : int = get_pdb_headers(snake_case_ ) if len(snake_case_ ) > 0: pdb_lines.extend(snake_case_ ) UpperCamelCase : Dict = aatype.shape[0] UpperCamelCase : int = 1 UpperCamelCase : Optional[int] = 0 UpperCamelCase : Union[str, Any] = string.ascii_uppercase UpperCamelCase : List[Any] = None # Add all atom sites. for i in range(snake_case_ ): UpperCamelCase : Any = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(snake_case_ ,atom_positions[i] ,atom_mask[i] ,b_factors[i] ): if mask < 0.5: continue UpperCamelCase : Any = """ATOM""" UpperCamelCase : Union[str, Any] = atom_name if len(snake_case_ ) == 4 else f' {atom_name}' UpperCamelCase : int = """""" UpperCamelCase : Optional[int] = """""" UpperCamelCase : int = 1.00 UpperCamelCase : List[str] = atom_name[0] # Protein supports only C, N, O, S, this works. UpperCamelCase : Optional[int] = """""" UpperCamelCase : List[Any] = """A""" if chain_index is not None: UpperCamelCase : str = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! UpperCamelCase : List[str] = ( f'{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}' f'{res_name_a:>3} {chain_tag:>1}' f'{residue_index[i]:>4}{insertion_code:>1} ' f'{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}' f'{occupancy:>6.2f}{b_factor:>6.2f} ' f'{element:>2}{charge:>2}' ) pdb_lines.append(snake_case_ ) atom_index += 1 UpperCamelCase : List[str] = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: UpperCamelCase : int = True UpperCamelCase : Dict = chain_index[i + 1] if should_terminate: # Close the chain. UpperCamelCase : Optional[Any] = """TER""" UpperCamelCase : Union[str, Any] = ( f'{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}' ) pdb_lines.append(snake_case_ ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(snake_case_ ,snake_case_ ) ) pdb_lines.append("""END""" ) pdb_lines.append("""""" ) return "\n".join(snake_case_ ) def A_ ( snake_case_ : Protein ): '''simple docstring''' return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def A_ ( snake_case_ : FeatureDict ,snake_case_ : ModelOutput ,snake_case_ : Optional[np.ndarray] = None ,snake_case_ : Optional[np.ndarray] = None ,snake_case_ : Optional[str] = None ,snake_case_ : Optional[Sequence[str]] = None ,snake_case_ : Optional[Sequence[int]] = None ,): '''simple docstring''' return Protein( aatype=features["""aatype"""] ,atom_positions=result["""final_atom_positions"""] ,atom_mask=result["""final_atom_mask"""] ,residue_index=features["""residue_index"""] + 1 ,b_factors=b_factors if b_factors is not None else np.zeros_like(result["""final_atom_mask"""] ) ,chain_index=snake_case_ ,remark=snake_case_ ,parents=snake_case_ ,parents_chain_index=snake_case_ ,)
27
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
27
1
"""simple docstring""" import unittest from transformers import DonutProcessor __A : List[str] = '''naver-clova-ix/donut-base''' class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : str = DonutProcessor.from_pretrained(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = { """name""": """John Doe""", """age""": """99""", """city""": """Atlanta""", """state""": """GA""", """zip""": """30301""", """phone""": """123-4567""", """nicknames""": [{"""nickname""": """Johnny"""}, {"""nickname""": """JD"""}], } UpperCamelCase : Any = ( """<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>""" """<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>""" """<s_nicknames><s_nickname>Johnny</s_nickname>""" """<sep/><s_nickname>JD</s_nickname></s_nicknames>""" ) UpperCamelCase : Tuple = self.processor.tokenajson(SCREAMING_SNAKE_CASE_ ) self.assertDictEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def a_ ( self ): UpperCamelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : Dict = """xvjiarui/stable-diffusion-2-inpainting""" UpperCamelCase , UpperCamelCase : List[str] = FlaxStableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = jax.random.PRNGKey(0 ) UpperCamelCase : Tuple = 50 UpperCamelCase : Dict = jax.device_count() UpperCamelCase : Optional[int] = num_samples * [prompt] UpperCamelCase : int = num_samples * [init_image] UpperCamelCase : List[Any] = num_samples * [mask_image] UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = pipeline.prepare_inputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # shard inputs and rng UpperCamelCase : Optional[int] = replicate(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = jax.random.split(SCREAMING_SNAKE_CASE_ , jax.device_count() ) UpperCamelCase : str = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipeline( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , jit=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = output.images.reshape(SCREAMING_SNAKE_CASE_ , 512 , 512 , 3 ) UpperCamelCase : List[Any] = images[0, 253:256, 253:256, -1] UpperCamelCase : List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase : Dict = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
27
1
"""simple docstring""" from __future__ import annotations import math def A_ ( snake_case_ : list ,snake_case_ : list ): '''simple docstring''' if len(snake_case_ ) != 2 or len(a[0] ) != 2 or len(snake_case_ ) != 2 or len(b[0] ) != 2: raise Exception("""Matrices are not 2x2""" ) UpperCamelCase : Tuple = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def A_ ( snake_case_ : list ,snake_case_ : list ): '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(snake_case_ ) ) ] def A_ ( snake_case_ : list ,snake_case_ : list ): '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(snake_case_ ) ) ] def A_ ( snake_case_ : list ): '''simple docstring''' if len(snake_case_ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("""Odd matrices are not supported!""" ) UpperCamelCase : Optional[int] = len(snake_case_ ) UpperCamelCase : Any = matrix_length // 2 UpperCamelCase : Union[str, Any] = [[a[i][j] for j in range(snake_case_ ,snake_case_ )] for i in range(snake_case_ )] UpperCamelCase : Optional[int] = [ [a[i][j] for j in range(snake_case_ ,snake_case_ )] for i in range(snake_case_ ,snake_case_ ) ] UpperCamelCase : Tuple = [[a[i][j] for j in range(snake_case_ )] for i in range(snake_case_ )] UpperCamelCase : int = [[a[i][j] for j in range(snake_case_ )] for i in range(snake_case_ ,snake_case_ )] return top_left, top_right, bot_left, bot_right def A_ ( snake_case_ : list ): '''simple docstring''' return len(snake_case_ ), len(matrix[0] ) def A_ ( snake_case_ : list ): '''simple docstring''' print("""\n""".join(str(snake_case_ ) for line in matrix ) ) def A_ ( snake_case_ : list ,snake_case_ : list ): '''simple docstring''' if matrix_dimensions(snake_case_ ) == (2, 2): return default_matrix_multiplication(snake_case_ ,snake_case_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : str = split_matrix(snake_case_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : List[Any] = split_matrix(snake_case_ ) UpperCamelCase : Tuple = actual_strassen(snake_case_ ,matrix_subtraction(snake_case_ ,snake_case_ ) ) UpperCamelCase : List[Any] = actual_strassen(matrix_addition(snake_case_ ,snake_case_ ) ,snake_case_ ) UpperCamelCase : str = actual_strassen(matrix_addition(snake_case_ ,snake_case_ ) ,snake_case_ ) UpperCamelCase : Optional[Any] = actual_strassen(snake_case_ ,matrix_subtraction(snake_case_ ,snake_case_ ) ) UpperCamelCase : int = actual_strassen(matrix_addition(snake_case_ ,snake_case_ ) ,matrix_addition(snake_case_ ,snake_case_ ) ) UpperCamelCase : str = actual_strassen(matrix_subtraction(snake_case_ ,snake_case_ ) ,matrix_addition(snake_case_ ,snake_case_ ) ) UpperCamelCase : Dict = actual_strassen(matrix_subtraction(snake_case_ ,snake_case_ ) ,matrix_addition(snake_case_ ,snake_case_ ) ) UpperCamelCase : List[str] = matrix_addition(matrix_subtraction(matrix_addition(snake_case_ ,snake_case_ ) ,snake_case_ ) ,snake_case_ ) UpperCamelCase : Union[str, Any] = matrix_addition(snake_case_ ,snake_case_ ) UpperCamelCase : int = matrix_addition(snake_case_ ,snake_case_ ) UpperCamelCase : int = matrix_subtraction(matrix_subtraction(matrix_addition(snake_case_ ,snake_case_ ) ,snake_case_ ) ,snake_case_ ) # construct the new matrix from our 4 quadrants UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(snake_case_ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def A_ ( snake_case_ : list ,snake_case_ : list ): '''simple docstring''' if matrix_dimensions(snake_case_ )[1] != matrix_dimensions(snake_case_ )[0]: UpperCamelCase : str = ( """Unable to multiply these matrices, please check the dimensions.\n""" f'Matrix A: {matrixa}\n' f'Matrix B: {matrixa}' ) raise Exception(snake_case_ ) UpperCamelCase : str = matrix_dimensions(snake_case_ ) UpperCamelCase : Optional[Any] = matrix_dimensions(snake_case_ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] UpperCamelCase : Optional[Any] = max(*snake_case_ ,*snake_case_ ) UpperCamelCase : str = int(math.pow(2 ,math.ceil(math.loga(snake_case_ ) ) ) ) UpperCamelCase : Any = matrixa UpperCamelCase : Any = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 ,snake_case_ ): if i < dimensiona[0]: for _ in range(dimensiona[1] ,snake_case_ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] ,snake_case_ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) UpperCamelCase : int = actual_strassen(snake_case_ ,snake_case_ ) # Removing the additional zeros for i in range(0 ,snake_case_ ): if i < dimensiona[0]: for _ in range(dimensiona[1] ,snake_case_ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": __A : Optional[int] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] __A : List[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
27
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Optional[Any] = [1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" ,[2, -1] ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[Any] = [1, 2] UpperCamelCase : List[Any] = {"""a""": 1, """b""": 2} UpperCamelCase : List[str] = {"""a""": [1, 2], """b""": [3, 4]} UpperCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} UpperCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCamelCase : Optional[int] = [2, 3] UpperCamelCase : List[str] = {"""a""": 2, """b""": 3} UpperCamelCase : Any = {"""a""": [2, 3], """b""": [4, 5]} UpperCamelCase : Tuple = {"""a""": {"""1""": 2}, """b""": 3} UpperCamelCase : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa
27
1
"""simple docstring""" def A_ ( snake_case_ : int = 2_0_0 ): '''simple docstring''' UpperCamelCase : Any = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 2_0_0] UpperCamelCase : int = [0] * (pence + 1) UpperCamelCase : 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) == 73682
27
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : Any = use_input_lengths UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = gelu_activation UpperCamelCase : Dict = sinusoidal_embeddings UpperCamelCase : Optional[int] = causal UpperCamelCase : List[Any] = asm UpperCamelCase : int = n_langs UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = n_special UpperCamelCase : Dict = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : List[str] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[str] = scope UpperCamelCase : Dict = bos_token_id def a_ ( self ): UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Union[str, Any] = None if self.use_input_lengths: UpperCamelCase : str = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[str] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a_ ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def a_ ( 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_ , ): UpperCamelCase : Optional[int] = XLMModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , lengths=SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( 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_ , ): UpperCamelCase : Optional[Any] = XLMWithLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( 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_ , ): UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( 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_ , ): UpperCamelCase : int = XLMForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , p_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , ) ((UpperCamelCase) , ) : Union[str, Any] = result_with_labels.to_tuple() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , ) : Tuple = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def a_ ( 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_ , ): UpperCamelCase : Union[str, Any] = XLMForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( 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_ , ): UpperCamelCase : int = self.num_labels UpperCamelCase : int = XLMForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : 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.num_labels) ) def a_ ( 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_ , ): UpperCamelCase : List[Any] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[Any] = config_and_inputs UpperCamelCase : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase : Optional[Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) return inputs_dict def a_ ( self ): UpperCamelCase : List[Any] = XLMModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , emb_dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_attentions in attentions] , [True] * len(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : Tuple = min_length + idx + 1 UpperCamelCase : Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_hidden_states in hidden_states] , [True] * len(SCREAMING_SNAKE_CASE_ ) , ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : List[str] = min_length + idx + 1 UpperCamelCase : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) , ) pass @slow def a_ ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = XLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Dict = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # the president UpperCamelCase : List[Any] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" import warnings from functools import wraps from typing import Callable def A_ ( snake_case_ : Callable ): '''simple docstring''' @wraps(snake_case_ ) def _inner_fn(*snake_case_ : Dict ,**snake_case_ : int ): warnings.warn( (f'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') ,snake_case_ ,) return fn(*snake_case_ ,**snake_case_ ) return _inner_fn
27
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
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, BatchEncoding, PreTrainedTokenizer from ...utils import logging __A : Any = logging.get_logger(__name__) __A : int = '''▁''' __A : str = {'''vocab_file''': '''sentencepiece.bpe.model'''} __A : Dict = { '''vocab_file''': { '''facebook/mbart-large-en-ro''': ( '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model''' ), '''facebook/mbart-large-cc25''': ( '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model''' ), } } __A : Dict = { '''facebook/mbart-large-en-ro''': 1024, '''facebook/mbart-large-cc25''': 1024, } # fmt: off __A : Optional[int] = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN'''] class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[Any] = VOCAB_FILES_NAMES lowercase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : List[str] = PRETRAINED_VOCAB_FILES_MAP lowercase : Any = ['input_ids', 'attention_mask'] lowercase : List[int] = [] lowercase : List[int] = [] 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 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): # Mask token behave like a normal word, i.e. include the space before it UpperCamelCase : int = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token UpperCamelCase : Optional[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_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : str = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token UpperCamelCase : int = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab UpperCamelCase : str = 1 UpperCamelCase : List[str] = len(self.sp_model ) UpperCamelCase : List[str] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(SCREAMING_SNAKE_CASE_ ) } UpperCamelCase : Dict = {v: k for k, v in self.lang_code_to_id.items()} UpperCamelCase : Union[str, Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) UpperCamelCase : int = {v: k for k, v in self.fairseq_tokens_to_ids.items()} UpperCamelCase : Tuple = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) UpperCamelCase : List[Any] = src_lang if src_lang is not None else """en_XX""" UpperCamelCase : str = self.lang_code_to_id[self._src_lang] UpperCamelCase : Union[str, Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): UpperCamelCase : str = self.__dict__.copy() UpperCamelCase : List[Any] = None UpperCamelCase : int = self.sp_model.serialized_model_proto() return state def __setstate__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): UpperCamelCase : Any = {} UpperCamelCase : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def a_ ( self ): return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def a_ ( self ): return self._src_lang @src_lang.setter def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): 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_ ) UpperCamelCase : Union[str, Any] = [1] * len(self.prefix_tokens ) UpperCamelCase : Union[str, Any] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(SCREAMING_SNAKE_CASE_ )) + suffix_ones return prefix_ones + ([0] * len(SCREAMING_SNAKE_CASE_ )) + ([0] * len(SCREAMING_SNAKE_CASE_ )) + suffix_ones def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = [self.sep_token_id] UpperCamelCase : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) UpperCamelCase : Any = src_lang UpperCamelCase : Union[str, Any] = self(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tgt_lang_id return inputs def a_ ( self ): UpperCamelCase : Union[str, Any] = {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 a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.sp_model.encode(SCREAMING_SNAKE_CASE_ , out_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] UpperCamelCase : List[str] = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def a_ ( self , SCREAMING_SNAKE_CASE_ ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = """""".join(SCREAMING_SNAKE_CASE_ ).replace(SCREAMING_SNAKE_CASE_ , """ """ ).strip() return out_string def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase : List[str] = 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: UpperCamelCase : Dict = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE_ ) return (out_vocab_file,) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = "en_XX" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "ro_RO" , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : str = src_lang UpperCamelCase : Optional[int] = tgt_lang return super().prepare_seqaseq_batch(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self ): return self.set_src_lang_special_tokens(self.src_lang ) def a_ ( self ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.lang_code_to_id[src_lang] UpperCamelCase : Dict = [] UpperCamelCase : List[Any] = [self.eos_token_id, self.cur_lang_code] def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.lang_code_to_id[lang] UpperCamelCase : Union[str, Any] = [] UpperCamelCase : List[str] = [self.eos_token_id, self.cur_lang_code]
27
"""simple docstring""" import torch from transformers import AutoModel class lowerCamelCase ( torch.nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_="sayef/fsner-bert-base-uncased" ): super(SCREAMING_SNAKE_CASE_ , self ).__init__() UpperCamelCase : int = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.nn.CosineSimilarity(3 , 1e-08 ) UpperCamelCase : Any = torch.nn.Softmax(dim=1 ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return self.bert(**SCREAMING_SNAKE_CASE_ ).last_hidden_state def a_ ( self , SCREAMING_SNAKE_CASE_ ): return token_embeddings.sum(2 , keepdim=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 ): return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = W_supports["""sizes"""].tolist() UpperCamelCase : List[str] = W_supports["""start_token_id"""].item() UpperCamelCase : List[Any] = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase : List[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = W_supports["""input_ids"""] == start_token_id UpperCamelCase : Optional[Any] = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: UpperCamelCase : int = 0 else: UpperCamelCase : Optional[int] = support_sizes[i - 1] UpperCamelCase : Tuple = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase : int = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase : Tuple = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase : List[str] = torch.vstack((p_starts, p_start) ) UpperCamelCase : Optional[Any] = torch.vstack((p_ends, p_end) ) else: UpperCamelCase : Optional[int] = p_start UpperCamelCase : Tuple = p_end return p_starts, p_ends
27
1
"""simple docstring""" import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) __A : int = logging.getLogger() def A_ ( snake_case_ : Path ,snake_case_ : list ): '''simple docstring''' UpperCamelCase : int = """\n""".join(snake_case_ ) Path(snake_case_ ).open("""w""" ).writelines(snake_case_ ) __A : Tuple = '''patrickvonplaten/t5-tiny-random''' __A : List[str] = '''sshleifer/bart-tiny-random''' __A : Union[str, Any] = '''sshleifer/tiny-mbart''' __A : Any = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class lowerCamelCase ( _UpperCAmelCase ): def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = Path(self.get_auto_remove_tmp_dir() ) / """utest_input.source""" UpperCamelCase : List[Any] = input_file_name.parent / """utest_output.txt""" assert not output_file_name.exists() UpperCamelCase : Optional[int] = [""" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."""] _dump_articles(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = str(Path(self.get_auto_remove_tmp_dir() ) / """scores.json""" ) UpperCamelCase : Optional[int] = """translation_en_to_de""" if model == T5_TINY else """summarization""" UpperCamelCase : str = f'\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n '.split() with patch.object(SCREAMING_SNAKE_CASE_ , """argv""" , SCREAMING_SNAKE_CASE_ ): run_generate() assert Path(SCREAMING_SNAKE_CASE_ ).exists() # os.remove(Path(output_file_name)) def a_ ( self ): self.run_eval_tester(SCREAMING_SNAKE_CASE_ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.run_eval_tester(SCREAMING_SNAKE_CASE_ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = Path(self.get_auto_remove_tmp_dir() ) / """utest_input.source""" UpperCamelCase : str = input_file_name.parent / """utest_output.txt""" assert not output_file_name.exists() UpperCamelCase : Dict = { """en""": ["""Machine learning is great, isn't it?""", """I like to eat bananas""", """Tomorrow is another great day!"""], """de""": [ """Maschinelles Lernen ist großartig, oder?""", """Ich esse gerne Bananen""", """Morgen ist wieder ein toller Tag!""", ], } UpperCamelCase : List[Any] = Path(self.get_auto_remove_tmp_dir() ) UpperCamelCase : Tuple = str(tmp_dir / """scores.json""" ) UpperCamelCase : Optional[int] = str(tmp_dir / """val.target""" ) _dump_articles(SCREAMING_SNAKE_CASE_ , text["""en"""] ) _dump_articles(SCREAMING_SNAKE_CASE_ , text["""de"""] ) UpperCamelCase : Dict = """translation_en_to_de""" if model == T5_TINY else """summarization""" UpperCamelCase : str = f'\n run_eval_search.py\n {model}\n {str(SCREAMING_SNAKE_CASE_ )}\n {str(SCREAMING_SNAKE_CASE_ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n '.split() testargs.extend(["""--search""", """num_beams=1:2 length_penalty=0.9:1.0"""] ) with patch.object(SCREAMING_SNAKE_CASE_ , """argv""" , SCREAMING_SNAKE_CASE_ ): with CaptureStdout() as cs: run_search() UpperCamelCase : Tuple = [""" num_beams | length_penalty""", model, """Best score args"""] UpperCamelCase : int = ["""Info"""] if "translation" in task: expected_strings.append("""bleu""" ) else: expected_strings.extend(SCREAMING_SNAKE_CASE_ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(SCREAMING_SNAKE_CASE_ ).exists() os.remove(Path(SCREAMING_SNAKE_CASE_ ) )
27
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
1
"""simple docstring""" import os import sys __A : List[Any] = os.path.join(os.path.dirname(__file__), '''src''') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) __A : List[str] = [ '''torch''', '''numpy''', '''tokenizers''', '''filelock''', '''requests''', '''tqdm''', '''regex''', '''sentencepiece''', '''sacremoses''', '''importlib_metadata''', '''huggingface_hub''', ] @add_start_docstrings(AutoConfig.__doc__ ) def A_ ( *snake_case_ : List[Any] ,**snake_case_ : Optional[Any] ): '''simple docstring''' return AutoConfig.from_pretrained(*snake_case_ ,**snake_case_ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def A_ ( *snake_case_ : Optional[Any] ,**snake_case_ : Any ): '''simple docstring''' return AutoTokenizer.from_pretrained(*snake_case_ ,**snake_case_ ) @add_start_docstrings(AutoModel.__doc__ ) def A_ ( *snake_case_ : Any ,**snake_case_ : List[str] ): '''simple docstring''' return AutoModel.from_pretrained(*snake_case_ ,**snake_case_ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def A_ ( *snake_case_ : Any ,**snake_case_ : Optional[Any] ): '''simple docstring''' return AutoModelForCausalLM.from_pretrained(*snake_case_ ,**snake_case_ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def A_ ( *snake_case_ : Dict ,**snake_case_ : str ): '''simple docstring''' return AutoModelForMaskedLM.from_pretrained(*snake_case_ ,**snake_case_ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def A_ ( *snake_case_ : Any ,**snake_case_ : List[Any] ): '''simple docstring''' return AutoModelForSequenceClassification.from_pretrained(*snake_case_ ,**snake_case_ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def A_ ( *snake_case_ : Union[str, Any] ,**snake_case_ : Any ): '''simple docstring''' return AutoModelForQuestionAnswering.from_pretrained(*snake_case_ ,**snake_case_ )
27
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
1
"""simple docstring""" import math class lowerCamelCase : def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = 0.0 UpperCamelCase : Dict = 0.0 for i in range(len(SCREAMING_SNAKE_CASE_ ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): for i in range(len(SCREAMING_SNAKE_CASE_ ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def A_ ( ): '''simple docstring''' # Training Examples ( m, n ) UpperCamelCase : Tuple = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) UpperCamelCase : List[Any] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training UpperCamelCase : Optional[Any] = SelfOrganizingMap() UpperCamelCase : Tuple = 3 UpperCamelCase : int = 0.5 for _ in range(snake_case_ ): for j in range(len(snake_case_ ) ): # training sample UpperCamelCase : int = training_samples[j] # Compute the winning vector UpperCamelCase : List[Any] = self_organizing_map.get_winner(snake_case_ ,snake_case_ ) # Update the winning vector UpperCamelCase : str = self_organizing_map.update(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # classify test sample UpperCamelCase : List[Any] = [0, 0, 0, 1] UpperCamelCase : Optional[Any] = self_organizing_map.get_winner(snake_case_ ,snake_case_ ) # results print(f'Clusters that the test sample belongs to : {winner}' ) print(f'Weights that have been trained : {weights}' ) # running the main() function if __name__ == "__main__": main()
27
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
1
"""simple docstring""" from __future__ import annotations def A_ ( snake_case_ : list[list[int]] ): '''simple docstring''' UpperCamelCase : str = len(snake_case_ ) # We need to create solution object to save path. UpperCamelCase : List[Any] = [[0 for _ in range(snake_case_ )] for _ in range(snake_case_ )] UpperCamelCase : Any = run_maze(snake_case_ ,0 ,0 ,snake_case_ ) if solved: print("""\n""".join(str(snake_case_ ) for row in solutions ) ) else: print("""No solution exists!""" ) return solved def A_ ( snake_case_ : list[list[int]] ,snake_case_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ): '''simple docstring''' UpperCamelCase : str = len(snake_case_ ) # Final check point. if i == j == (size - 1): UpperCamelCase : Optional[Any] = 1 return True UpperCamelCase : Optional[int] = (not i < 0) and (not j < 0) # Check lower bounds UpperCamelCase : List[Any] = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. UpperCamelCase : List[str] = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited UpperCamelCase : Dict = 1 # check for directions if ( run_maze(snake_case_ ,i + 1 ,snake_case_ ,snake_case_ ) or run_maze(snake_case_ ,snake_case_ ,j + 1 ,snake_case_ ) or run_maze(snake_case_ ,i - 1 ,snake_case_ ,snake_case_ ) or run_maze(snake_case_ ,snake_case_ ,j - 1 ,snake_case_ ) ): return True UpperCamelCase : Optional[Any] = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
27
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = AudioLDMPipeline lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS lowercase : Tuple = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Tuple = 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, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCamelCase : int = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) UpperCamelCase : Optional[int] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) UpperCamelCase : Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Any = self.get_dummy_components() UpperCamelCase : int = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Tuple = audio[:10] UpperCamelCase : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[str] = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) UpperCamelCase : Tuple = prompt_embeds # forward UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_components() UpperCamelCase : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * ["""this is a negative prompt"""] UpperCamelCase : List[Any] = negative_prompt UpperCamelCase : str = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : str = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[Any] = [] for p in [prompt, negative_prompt]: UpperCamelCase : int = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Union[str, Any] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = text_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Tuple = embeds # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Optional[int] = self.get_dummy_components() UpperCamelCase : List[str] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """egg cracking""" UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Union[str, Any] = audio[:10] UpperCamelCase : Dict = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Union[str, Any] = self.get_dummy_components() UpperCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) UpperCamelCase : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts UpperCamelCase : Dict = 2 UpperCamelCase : List[str] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt UpperCamelCase : List[str] = 2 UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts UpperCamelCase : Any = 2 UpperCamelCase : str = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config.sampling_rate UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 UpperCamelCase : Optional[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = ["""hey"""] UpperCamelCase : Dict = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : str = output.audios.shape assert audio_shape == (1, 256) UpperCamelCase : Optional[Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 UpperCamelCase : str = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : List[str] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) UpperCamelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def a_ ( self ): UpperCamelCase : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 25 UpperCamelCase : Optional[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[7_7230:7_7240] UpperCamelCase : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) UpperCamelCase : Any = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def a_ ( self ): UpperCamelCase : Any = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) UpperCamelCase : str = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[2_7780:2_7790] UpperCamelCase : Tuple = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) UpperCamelCase : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
27
1
"""simple docstring""" from __future__ import annotations from collections.abc import Sequence from typing import Literal def A_ ( snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : int = list(snake_case_ ) UpperCamelCase : Optional[int] = list(snake_case_ ) UpperCamelCase : Optional[Any] = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count += 1 UpperCamelCase : Tuple = """_""" if count > 1: return False else: return "".join(snake_case_ ) def A_ ( snake_case_ : list[str] ): '''simple docstring''' UpperCamelCase : int = [] while True: UpperCamelCase : Union[str, Any] = ["""$"""] * len(snake_case_ ) UpperCamelCase : Optional[int] = [] for i in range(len(snake_case_ ) ): for j in range(i + 1 ,len(snake_case_ ) ): UpperCamelCase : str = compare_string(binary[i] ,binary[j] ) if k is False: UpperCamelCase : Any = """*""" UpperCamelCase : Union[str, Any] = """*""" temp.append("""X""" ) for i in range(len(snake_case_ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case_ ) == 0: return pi UpperCamelCase : Optional[Any] = list(set(snake_case_ ) ) def A_ ( snake_case_ : int ,snake_case_ : Sequence[float] ): '''simple docstring''' UpperCamelCase : Optional[int] = [] for minterm in minterms: UpperCamelCase : List[str] = """""" for _ in range(snake_case_ ): UpperCamelCase : Dict = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case_ ) return temp def A_ ( snake_case_ : str ,snake_case_ : str ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : Union[str, Any] = list(snake_case_ ) UpperCamelCase : Optional[int] = list(snake_case_ ) UpperCamelCase : List[Any] = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def A_ ( snake_case_ : list[list[int]] ,snake_case_ : list[str] ): '''simple docstring''' UpperCamelCase : int = [] UpperCamelCase : Optional[Any] = [0] * len(snake_case_ ) for i in range(len(chart[0] ) ): UpperCamelCase : Tuple = 0 UpperCamelCase : Optional[Any] = -1 for j in range(len(snake_case_ ) ): if chart[j][i] == 1: count += 1 UpperCamelCase : Union[str, Any] = j if count == 1: UpperCamelCase : Optional[int] = 1 for i in range(len(snake_case_ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case_ ) ): UpperCamelCase : Union[str, Any] = 0 temp.append(prime_implicants[i] ) while True: UpperCamelCase : Optional[int] = 0 UpperCamelCase : Optional[int] = -1 UpperCamelCase : List[Any] = 0 for i in range(len(snake_case_ ) ): UpperCamelCase : Tuple = chart[i].count(1 ) if count_n > max_n: UpperCamelCase : Tuple = count_n UpperCamelCase : Any = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case_ ) ): UpperCamelCase : Optional[Any] = 0 def A_ ( snake_case_ : list[str] ,snake_case_ : list[str] ): '''simple docstring''' UpperCamelCase : List[str] = [[0 for x in range(len(snake_case_ ) )] for x in range(len(snake_case_ ) )] for i in range(len(snake_case_ ) ): UpperCamelCase : Tuple = prime_implicants[i].count("""_""" ) for j in range(len(snake_case_ ) ): if is_for_table(prime_implicants[i] ,binary[j] ,snake_case_ ): UpperCamelCase : Optional[Any] = 1 return chart def A_ ( ): '''simple docstring''' UpperCamelCase : Any = int(input("""Enter the no. of variables\n""" ) ) UpperCamelCase : Tuple = [ float(snake_case_ ) for x in input( """Enter the decimal representation of Minterms 'Spaces Separated'\n""" ).split() ] UpperCamelCase : int = decimal_to_binary(snake_case_ ,snake_case_ ) UpperCamelCase : List[str] = check(snake_case_ ) print("""Prime Implicants are:""" ) print(snake_case_ ) UpperCamelCase : Dict = prime_implicant_chart(snake_case_ ,snake_case_ ) UpperCamelCase : List[Any] = selection(snake_case_ ,snake_case_ ) print("""Essential Prime Implicants are:""" ) print(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
27
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' # load dataset UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
1
"""simple docstring""" import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration __A : List[str] = pytest.mark.integration __A : List[Any] = {'''comet'''} __A : List[str] = importlib.util.find_spec('''fairseq''') is not None __A : Dict = {'''code_eval'''} __A : List[Any] = os.name == '''nt''' __A : Tuple = {'''bertscore''', '''frugalscore''', '''perplexity'''} __A : Union[str, Any] = importlib.util.find_spec('''transformers''') is not None def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' @wraps(snake_case_ ) def wrapper(self : Union[str, Any] ,snake_case_ : List[Any] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("""\"test requires Fairseq\"""" ) else: test_case(self ,snake_case_ ) return wrapper def A_ ( snake_case_ : Dict ): '''simple docstring''' @wraps(snake_case_ ) def wrapper(self : Optional[int] ,snake_case_ : Optional[Any] ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("""\"test requires transformers\"""" ) else: test_case(self ,snake_case_ ) return wrapper def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' @wraps(snake_case_ ) def wrapper(self : Optional[Any] ,snake_case_ : Dict ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("""\"test not supported on Windows\"""" ) else: test_case(self ,snake_case_ ) return wrapper def A_ ( ): '''simple docstring''' UpperCamelCase : Optional[Any] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("""./metrics/*/""" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) @local class lowerCamelCase ( parameterized.TestCase ): lowercase : List[str] = {} lowercase : Optional[Any] = None @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""" ) @pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning""" ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = """[...]""" UpperCamelCase : List[str] = importlib.import_module( datasets.load.metric_module_factory(os.path.join("""metrics""" , SCREAMING_SNAKE_CASE_ ) ).module_path ) UpperCamelCase : int = datasets.load.import_main_class(metric_module.__name__ , dataset=SCREAMING_SNAKE_CASE_ ) # check parameters UpperCamelCase : int = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(SCREAMING_SNAKE_CASE_ , metric_module.__name__ ): with self.use_local_metrics(): try: UpperCamelCase : int = doctest.testmod(SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , raise_on_error=SCREAMING_SNAKE_CASE_ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = """[...]""" UpperCamelCase : int = importlib.import_module( datasets.load.metric_module_factory(os.path.join("""metrics""" , SCREAMING_SNAKE_CASE_ ) ).module_path ) # run doctest with self.use_local_metrics(): UpperCamelCase : str = doctest.testmod(SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , raise_on_error=SCREAMING_SNAKE_CASE_ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](SCREAMING_SNAKE_CASE_ ): yield else: yield @contextmanager def a_ ( self ): def load_local_metric(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return load_metric(os.path.join("""metrics""" , SCREAMING_SNAKE_CASE_ ) , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) with patch("""datasets.load_metric""" ) as mock_load_metric: UpperCamelCase : Any = load_local_metric yield @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ ): def wrapper(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = contextmanager(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("""bleurt""" ) def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("""sv""" ,"""""" ,"""""" ) # handle pytest cli flags class lowerCamelCase ( _UpperCAmelCase ): def a_ ( self , SCREAMING_SNAKE_CASE_ ): assert len(input_dict["""input_ids"""] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("""bleurt.score._create_predictor""" ) as mock_create_predictor: UpperCamelCase : Tuple = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("""bertscore""" ) def A_ ( snake_case_ : Any ): '''simple docstring''' import torch def bert_cos_score_idf(snake_case_ : List[Any] ,snake_case_ : int ,*snake_case_ : List[Any] ,**snake_case_ : Tuple ): return torch.tensor([[1.0, 1.0, 1.0]] * len(snake_case_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("""bert_score.scorer.get_model""" ), patch( """bert_score.scorer.bert_cos_score_idf""" ) as mock_bert_cos_score_idf: UpperCamelCase : Optional[int] = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("""comet""" ) def A_ ( snake_case_ : Dict ): '''simple docstring''' def load_from_checkpoint(snake_case_ : List[str] ): class lowerCamelCase : def a_ ( self , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): assert len(SCREAMING_SNAKE_CASE_ ) == 2 UpperCamelCase : Dict = [0.19, 0.92] return scores, sum(SCREAMING_SNAKE_CASE_ ) / len(SCREAMING_SNAKE_CASE_ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("""comet.download_model""" ) as mock_download_model: UpperCamelCase : Dict = None with patch("""comet.load_from_checkpoint""" ) as mock_load_from_checkpoint: UpperCamelCase : Tuple = load_from_checkpoint yield def A_ ( ): '''simple docstring''' UpperCamelCase : List[str] = load_metric(os.path.join("""metrics""" ,"""seqeval""" ) ) UpperCamelCase : List[Any] = """ERROR""" UpperCamelCase : Union[str, Any] = f'Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}' with pytest.raises(snake_case_ ,match=re.escape(snake_case_ ) ): metric.compute(predictions=[] ,references=[] ,scheme=snake_case_ )
27
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : str = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
27
1
"""simple docstring""" from dataclasses import dataclass, field from typing import Optional @dataclass class lowerCamelCase : lowercase : Optional[str] = field( default='codeparrot/codeparrot' , metadata={'help': 'Model name or path of model to be trained.'} ) lowercase : Optional[str] = field( default='./' , metadata={'help': 'Save dir where model repo is cloned and models updates are saved to.'} ) lowercase : Optional[str] = field( default='codeparrot/codeparrot-clean-train' , metadata={'help': 'Name or path of training dataset.'} ) lowercase : Optional[str] = field( default='codeparrot/codeparrot-clean-valid' , metadata={'help': 'Name or path of validation dataset.'} ) lowercase : Optional[int] = field(default=2 , metadata={'help': 'Batch size for training.'} ) lowercase : Optional[int] = field(default=2 , metadata={'help': 'Batch size for evaluation.'} ) lowercase : Optional[float] = field(default=0.1 , metadata={'help': 'Value of weight decay.'} ) lowercase : Optional[int] = field( default=1_0_0_0_0 , metadata={'help': 'Size of buffer used to shuffle streaming dataset.'} ) lowercase : Optional[float] = field(default=2E-4 , metadata={'help': 'Learning rate fo training.'} ) lowercase : Optional[str] = field(default='cosine' , metadata={'help': 'Learning rate.'} ) lowercase : Optional[int] = field( default=7_5_0 , metadata={'help': 'Number of warmup steps in the learning rate schedule.'} ) lowercase : Optional[int] = field( default=1_6 , metadata={'help': 'Number of gradient accumulation steps.'} ) lowercase : Optional[bool] = field( default=_UpperCAmelCase , metadata={'help': 'Use gradient checkpointing to reduce memory footprint.'} ) lowercase : Optional[int] = field(default=5_0_0_0_0 , metadata={'help': 'Maximum number of training steps.'} ) lowercase : Optional[int] = field( default=-1 , metadata={'help': 'Maximum number of evaluation steps. If -1 the full dataset is evaluated.'} ) lowercase : Optional[int] = field(default=1_0_2_4 , metadata={'help': 'Sequence lengths used for training.'} ) lowercase : Optional[int] = field(default=1 , metadata={'help': 'Training seed.'} ) lowercase : Optional[int] = field( default=1_0_2_4 , metadata={'help': 'Interval to save checkpoints. Measured as number of forward passes not training steps.'} , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'States path if the training should continue from a checkpoint folder.'} ) lowercase : Optional[bool] = field(default=_UpperCAmelCase , metadata={'help': 'If True the data is pretokenized.'} ) @dataclass class lowerCamelCase : lowercase : Optional[str] = field( default='codeparrot/codeparrot' , metadata={'help': 'Model name or path of model to be evaluated.'} ) lowercase : Optional[str] = field( default='codeparrot/codeparrot-clean-valid' , metadata={'help': 'Name or path of validation dataset.'} ) lowercase : Optional[int] = field(default=2 , metadata={'help': 'Batch size used for evaluation.'} ) lowercase : Optional[int] = field( default=-1 , metadata={'help': 'Maximum number of evaluation steps. If -1 the full dataset is evaluated.'} ) lowercase : Optional[int] = field(default=1_0_2_4 , metadata={'help': 'Length of sequences to be evaluated.'} ) lowercase : Optional[int] = field(default=1 , metadata={'help': 'Random seed used for evaluation.'} ) @dataclass class lowerCamelCase : lowercase : Optional[str] = field( default='codeparrot/codeparrot' , metadata={'help': 'Model name or path of model to be evaluated.'} ) lowercase : Optional[int] = field(default=_UpperCAmelCase , metadata={'help': 'Number of workers used for code evaluation.'} ) lowercase : Optional[int] = field( default=_UpperCAmelCase , metadata={'help': 'The number of human-eval tasks to run. If not included all tasks are evaluated.'} , ) lowercase : Optional[bool] = field( default=_UpperCAmelCase , metadata={'help': 'Sample from the language model\'s output distribution.'} ) lowercase : Optional[float] = field(default=0.2 , metadata={'help': 'Sampling temperature used for generation.'} ) lowercase : Optional[int] = field(default=2_5_6 , metadata={'help': 'Maximum number of newly generated tokens.'} ) lowercase : Optional[int] = field(default=0 , metadata={'help': 'Top-k parameter used for generation.'} ) lowercase : Optional[float] = field(default=0.95 , metadata={'help': 'Top-p parameter used for nucleus sampling.'} ) lowercase : Optional[int] = field(default=1_0 , metadata={'help': 'Number of generations to run in parallel.'} ) lowercase : Optional[int] = field( default=2_0_0 , metadata={'help': 'Number of completions to generate for each sample.'} ) lowercase : Optional[int] = field(default=1 , metadata={'help': 'Random seed used for evaluation.'} ) lowercase : Optional[str] = field( default='eval_results.json' , metadata={'help': 'Random seed used for evaluation.'} ) lowercase : Optional[str] = field( default='0' , metadata={'help': 'Allow `code_eval` to execute Python code on machine'} ) lowercase : Optional[int] = field( default=-1 , metadata={ 'help': ( 'Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive' ' number corresponds to which GPU device id to run on.' ) } , ) @dataclass class lowerCamelCase : lowercase : Optional[int] = field( default=_UpperCAmelCase , metadata={ 'help': 'The number of CPU cores to use for parallel preprocessing. Default uses the maximum available.' } , ) lowercase : Optional[str] = field( default='transformersbook/codeparrot' , metadata={'help': 'Folder or name of dataset to process.'} ) lowercase : Optional[str] = field( default='codeparrot-clean' , metadata={'help': 'Folder to save processed processed dataset.'} ) lowercase : Optional[int] = field( default=1_0_0_0_0_0 , metadata={'help': 'Number of files to save per JSON output file.'} ) lowercase : Optional[str] = field(default='content' , metadata={'help': 'Column containing text data to process.'} ) lowercase : Optional[float] = field( default=1_0_0_0 , metadata={'help': 'Maximum line length in file, otherwise file is filtered.'} ) lowercase : Optional[float] = field( default=1_0_0 , metadata={'help': 'Maximum mean line length in file, otherwise file is filtered.'} ) lowercase : Optional[float] = field( default=0.25 , metadata={'help': 'Maximum fraction of non-alphanumeric characters, otherwise file is filtered.'} ) lowercase : Optional[float] = field( default=1.5 , metadata={'help': 'Minimum character token ratio for the file, otherwise file is filtered.'} ) lowercase : Optional[float] = field( default=0.7 , metadata={'help': 'Probability for filtering config, test and uncommon files.'} ) lowercase : Optional[str] = field( default='codeparrot/codeparrot' , metadata={'help': 'Name or path to the tokenizer.'} , ) lowercase : Optional[bool] = field( default=_UpperCAmelCase , metadata={'help': 'If True, near-duplicate samples are removed.'} ) lowercase : Optional[float] = field( default=0.85 , metadata={'help': 'Jaccard threshold for near-duplicate samples.'} ) @dataclass class lowerCamelCase : lowercase : Optional[str] = field( default='gpt2' , metadata={'help': 'Base tokenizer to build new tokenizer from.'} ) lowercase : Optional[str] = field( default='transformersbook/codeparrot-train' , metadata={'help': 'Dataset to train tokenizer on.'} ) lowercase : Optional[str] = field(default='content' , metadata={'help': 'Column containing text data to process.'} ) lowercase : Optional[int] = field(default=2_0_0_0_0_0 , metadata={'help': 'Number of examples to train tokenizer on.'} ) lowercase : Optional[int] = field( default=3_2_7_6_8 , metadata={'help': 'Number of examples to train the tokenizer on.'} ) lowercase : Optional[str] = field(default='codeparrot' , metadata={'help': 'Name of new tokenizer.'} ) lowercase : Optional[bool] = field(default=_UpperCAmelCase , metadata={'help': 'Push saved tokenizer to the hub.'} ) @dataclass class lowerCamelCase : lowercase : Optional[str] = field( default='codeparrot/codeparrot' , metadata={'help': 'Name or path to the tokenizer.'} ) lowercase : Optional[str] = field( default='codeparrot/codeparrot-clean-train' , metadata={'help': 'Name or path to the dataset to pretokenize.'} ) lowercase : Optional[str] = field( default='tokenized-codeparrot-train' , metadata={'help': 'Repo name of the pretokenized data.'} ) lowercase : Optional[int] = field(default=_UpperCAmelCase , metadata={'help': 'Number of workers used for code evaluation.'} ) @dataclass class lowerCamelCase : lowercase : Optional[str] = field( default='gpt2-large' , metadata={'help': 'Configuration to use for model initialization.'} ) lowercase : Optional[str] = field( default='codeparrot/codeparrot' , metadata={'help': 'Tokenizer attached to model.'} ) lowercase : Optional[str] = field(default='codeparrot' , metadata={'help': 'Name of the created model.'} ) lowercase : Optional[bool] = field(default=_UpperCAmelCase , metadata={'help': 'Push saved tokenizer to the hub.'} )
27
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
27
1
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase , UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A , __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A , __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
27
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCamelCase ( _UpperCAmelCase ): 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_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Union[str, Any] = use_token_type_ids UpperCamelCase : Dict = use_labels UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : str = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : int = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Dict = num_labels UpperCamelCase : Tuple = num_choices UpperCamelCase : Optional[int] = scope UpperCamelCase : List[Any] = q_groups UpperCamelCase : Tuple = k_groups UpperCamelCase : Any = v_groups UpperCamelCase : List[str] = post_attention_groups UpperCamelCase : Tuple = intermediate_groups UpperCamelCase : int = output_groups def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = SqueezeBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = SqueezeBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = 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 a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = SqueezeBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : str = SqueezeBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = 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.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = SqueezeBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = config_and_inputs UpperCamelCase : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase : Dict = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : str = True lowercase : str = False def a_ ( self ): UpperCamelCase : Any = SqueezeBertModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = SqueezeBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) UpperCamelCase : Dict = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
1
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Tuple = LayoutLMTokenizer lowercase : List[str] = LayoutLMTokenizerFast lowercase : List[str] = True lowercase : str = True def a_ ( self ): super().setUp() UpperCamelCase : Union[str, Any] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] UpperCamelCase : 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 a_ ( self , **SCREAMING_SNAKE_CASE_ ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = """UNwant\u00E9d,running""" UpperCamelCase : Dict = """unwanted, running""" return input_text, output_text def a_ ( self ): UpperCamelCase : int = self.tokenizer_class(self.vocab_file ) UpperCamelCase : Any = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [7, 4, 5, 10, 8, 9] ) def a_ ( self ): pass
27
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A : Dict = logging.get_logger(__name__) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Tuple ,snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : int = original_name.split(""".""" )[0] UpperCamelCase : Union[str, Any] = key.split(""".""" ) UpperCamelCase : Dict = int(key_list[key_list.index(snake_case_ ) - 2] ) UpperCamelCase : Optional[Any] = int(key_list[key_list.index(snake_case_ ) - 1] ) UpperCamelCase : List[str] = orig_block_num - offset UpperCamelCase : Tuple = key.replace(f'{orig_block_num}.{layer_num}.{original_name}' ,f'block.{new_block_num}.{layer_num}.{new_name}' ) return key def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : List[Any] = OrderedDict() UpperCamelCase , UpperCamelCase : Optional[Any] = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): UpperCamelCase : Tuple = key.replace("""network""" ,"""poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 UpperCamelCase : List[str] = key[: key.find("""proj""" )] UpperCamelCase : List[str] = key.replace(snake_case_ ,f'patch_embeddings.{total_embed_found}.' ) UpperCamelCase : Tuple = key.replace("""proj""" ,"""projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: UpperCamelCase : str = """poolformer.encoder.""" + key if "mlp.fc1" in key: UpperCamelCase : Union[str, Any] = replace_key_with_offset(snake_case_ ,snake_case_ ,"""mlp.fc1""" ,"""output.conv1""" ) if "mlp.fc2" in key: UpperCamelCase : Union[str, Any] = replace_key_with_offset(snake_case_ ,snake_case_ ,"""mlp.fc2""" ,"""output.conv2""" ) if "norm1" in key: UpperCamelCase : Tuple = replace_key_with_offset(snake_case_ ,snake_case_ ,"""norm1""" ,"""before_norm""" ) if "norm2" in key: UpperCamelCase : Any = replace_key_with_offset(snake_case_ ,snake_case_ ,"""norm2""" ,"""after_norm""" ) if "layer_scale_1" in key: UpperCamelCase : int = replace_key_with_offset(snake_case_ ,snake_case_ ,"""layer_scale_1""" ,"""layer_scale_1""" ) if "layer_scale_2" in key: UpperCamelCase : Any = replace_key_with_offset(snake_case_ ,snake_case_ ,"""layer_scale_2""" ,"""layer_scale_2""" ) if "head" in key: UpperCamelCase : Dict = key.replace("""head""" ,"""classifier""" ) UpperCamelCase : Any = value return new_state_dict def A_ ( ): '''simple docstring''' UpperCamelCase : List[str] = """http://images.cocodataset.org/val2017/000000039769.jpg""" UpperCamelCase : Optional[Any] = Image.open(requests.get(snake_case_ ,stream=snake_case_ ).raw ) return image @torch.no_grad() def A_ ( snake_case_ : Optional[Any] ,snake_case_ : List[Any] ,snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : str = PoolFormerConfig() # set attributes based on model_name UpperCamelCase : str = """huggingface/label-files""" UpperCamelCase : Optional[Any] = model_name[-3:] UpperCamelCase : Optional[int] = 1_0_0_0 UpperCamelCase : List[str] = """imagenet-1k-id2label.json""" UpperCamelCase : Any = (1, 1_0_0_0) # set config attributes UpperCamelCase : int = json.load(open(hf_hub_download(snake_case_ ,snake_case_ ,repo_type="""dataset""" ) ,"""r""" ) ) UpperCamelCase : Union[str, Any] = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCamelCase : Optional[Any] = idalabel UpperCamelCase : List[str] = {v: k for k, v in idalabel.items()} if size == "s12": UpperCamelCase : Dict = [2, 2, 6, 2] UpperCamelCase : List[Any] = [6_4, 1_2_8, 3_2_0, 5_1_2] UpperCamelCase : Optional[Any] = 4.0 UpperCamelCase : int = 0.9 elif size == "s24": UpperCamelCase : Optional[int] = [4, 4, 1_2, 4] UpperCamelCase : Any = [6_4, 1_2_8, 3_2_0, 5_1_2] UpperCamelCase : Optional[Any] = 4.0 UpperCamelCase : Tuple = 0.9 elif size == "s36": UpperCamelCase : Union[str, Any] = [6, 6, 1_8, 6] UpperCamelCase : Any = [6_4, 1_2_8, 3_2_0, 5_1_2] UpperCamelCase : List[str] = 4.0 UpperCamelCase : Optional[int] = 1e-6 UpperCamelCase : List[str] = 0.9 elif size == "m36": UpperCamelCase : Tuple = [6, 6, 1_8, 6] UpperCamelCase : List[str] = [9_6, 1_9_2, 3_8_4, 7_6_8] UpperCamelCase : int = 4.0 UpperCamelCase : Dict = 1e-6 UpperCamelCase : Optional[int] = 0.95 elif size == "m48": UpperCamelCase : Any = [8, 8, 2_4, 8] UpperCamelCase : str = [9_6, 1_9_2, 3_8_4, 7_6_8] UpperCamelCase : List[Any] = 4.0 UpperCamelCase : int = 1e-6 UpperCamelCase : List[str] = 0.95 else: raise ValueError(f'Size {size} not supported' ) # load image processor UpperCamelCase : Union[str, Any] = PoolFormerImageProcessor(crop_pct=snake_case_ ) # Prepare image UpperCamelCase : int = prepare_img() UpperCamelCase : Tuple = image_processor(images=snake_case_ ,return_tensors="""pt""" ).pixel_values logger.info(f'Converting model {model_name}...' ) # load original state dict UpperCamelCase : List[str] = torch.load(snake_case_ ,map_location=torch.device("""cpu""" ) ) # rename keys UpperCamelCase : str = rename_keys(snake_case_ ) # create HuggingFace model and load state dict UpperCamelCase : List[Any] = PoolFormerForImageClassification(snake_case_ ) model.load_state_dict(snake_case_ ) model.eval() # Define image processor UpperCamelCase : Union[str, Any] = PoolFormerImageProcessor(crop_pct=snake_case_ ) UpperCamelCase : List[Any] = image_processor(images=prepare_img() ,return_tensors="""pt""" ).pixel_values # forward pass UpperCamelCase : Optional[int] = model(snake_case_ ) UpperCamelCase : Union[str, Any] = outputs.logits # define expected logit slices for different models if size == "s12": UpperCamelCase : List[Any] = torch.tensor([-0.3045, -0.6758, -0.4869] ) elif size == "s24": UpperCamelCase : Any = torch.tensor([0.4402, -0.1374, -0.8045] ) elif size == "s36": UpperCamelCase : Dict = torch.tensor([-0.6080, -0.5133, -0.5898] ) elif size == "m36": UpperCamelCase : Tuple = torch.tensor([0.3952, 0.2263, -1.2668] ) elif size == "m48": UpperCamelCase : Dict = torch.tensor([0.1167, -0.0656, -0.3423] ) else: raise ValueError(f'Size {size} not supported' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] ,snake_case_ ,atol=1e-2 ) # finally, save model and image processor logger.info(f'Saving PyTorch model and image processor to {pytorch_dump_folder_path}...' ) Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) model.save_pretrained(snake_case_ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case_ ) if __name__ == "__main__": __A : Tuple = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''poolformer_s12''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) __A : Optional[int] = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
27
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Optional[int] = { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = 'mvp' lowercase : Optional[Any] = ['past_key_values'] lowercase : Union[str, Any] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , SCREAMING_SNAKE_CASE_=5_0267 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=800 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Dict = max_position_embeddings UpperCamelCase : Optional[int] = d_model UpperCamelCase : Optional[Any] = encoder_ffn_dim UpperCamelCase : Any = encoder_layers UpperCamelCase : List[Any] = encoder_attention_heads UpperCamelCase : Optional[Any] = decoder_ffn_dim UpperCamelCase : Optional[int] = decoder_layers UpperCamelCase : Dict = decoder_attention_heads UpperCamelCase : List[str] = dropout UpperCamelCase : List[str] = attention_dropout UpperCamelCase : List[Any] = activation_dropout UpperCamelCase : Dict = activation_function UpperCamelCase : List[str] = init_std UpperCamelCase : int = encoder_layerdrop UpperCamelCase : Dict = decoder_layerdrop UpperCamelCase : Any = classifier_dropout UpperCamelCase : Tuple = use_cache UpperCamelCase : Dict = encoder_layers UpperCamelCase : Tuple = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase : Optional[Any] = use_prompt UpperCamelCase : Any = prompt_length UpperCamelCase : List[Any] = prompt_mid_dim super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , forced_eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' """The config can simply be saved and uploaded again to be fixed.""" )
27
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A : Union[str, Any] = {'''configuration_yolos''': ['''YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''YolosConfig''', '''YolosOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Dict = ['''YolosFeatureExtractor'''] __A : str = ['''YolosImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[Any] = [ '''YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''YolosForObjectDetection''', '''YolosModel''', '''YolosPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A : Optional[Any] = 16 __A : str = 32 def A_ ( snake_case_ : Accelerator ,snake_case_ : int = 1_6 ): '''simple docstring''' UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase : Optional[int] = load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(snake_case_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : Union[str, Any] = tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=snake_case_ ,max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase : Optional[Any] = datasets.map( snake_case_ ,batched=snake_case_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase : str = tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(snake_case_ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase : Union[str, Any] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase : Optional[Any] = 1_6 elif accelerator.mixed_precision != "no": UpperCamelCase : Any = 8 else: UpperCamelCase : Optional[Any] = None return tokenizer.pad( snake_case_ ,padding="""longest""" ,max_length=snake_case_ ,pad_to_multiple_of=snake_case_ ,return_tensors="""pt""" ,) # Instantiate dataloaders. UpperCamelCase : str = DataLoader( tokenized_datasets["""train"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) UpperCamelCase : Dict = DataLoader( tokenized_datasets["""validation"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A : int = mocked_dataloaders # noqa: F811 def A_ ( snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,snake_case_ ) == "1": UpperCamelCase : Union[str, Any] = 2 # New Code # UpperCamelCase : Dict = int(args.gradient_accumulation_steps ) UpperCamelCase : List[Any] = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=snake_case_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : Union[str, Any] = config["""lr"""] UpperCamelCase : int = int(config["""num_epochs"""] ) UpperCamelCase : int = int(config["""seed"""] ) UpperCamelCase : List[Any] = int(config["""batch_size"""] ) UpperCamelCase : Optional[int] = evaluate.load("""glue""" ,"""mrpc""" ) set_seed(snake_case_ ) UpperCamelCase , UpperCamelCase : Dict = get_dataloaders(snake_case_ ,snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" ,return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase : Tuple = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase : List[Any] = AdamW(params=model.parameters() ,lr=snake_case_ ) # Instantiate scheduler UpperCamelCase : str = get_linear_schedule_with_warmup( optimizer=snake_case_ ,num_warmup_steps=1_0_0 ,num_training_steps=(len(snake_case_ ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() with LocalSGD( accelerator=snake_case_ ,model=snake_case_ ,local_sgd_steps=snake_case_ ,enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case_ ): UpperCamelCase : Optional[Any] = model(**snake_case_ ) UpperCamelCase : Optional[int] = output.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase : Any = model(**snake_case_ ) UpperCamelCase : Tuple = outputs.logits.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase : int = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case_ ,references=snake_case_ ,) UpperCamelCase : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}:' ,snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" ,type=snake_case_ ,default=snake_case_ ,choices=["""no""", """fp16""", """bf16""", """fp8"""] ,help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" ,) # New Code # parser.add_argument( """--gradient_accumulation_steps""" ,type=snake_case_ ,default=1 ,help="""The number of minibatches to be ran before gradients are accumulated.""" ,) parser.add_argument( """--local_sgd_steps""" ,type=snake_case_ ,default=8 ,help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) UpperCamelCase : Dict = parser.parse_args() UpperCamelCase : List[Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6} training_function(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
27
1
"""simple docstring""" from __future__ import annotations from math import gcd def A_ ( snake_case_ : int ,snake_case_ : int = 2 ,snake_case_ : int = 1 ,snake_case_ : int = 3 ,): '''simple docstring''' # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("""The input value cannot be less than 2""" ) # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(snake_case_ : int ,snake_case_ : int ,snake_case_ : int ) -> int: return (pow(snake_case_ ,2 ) + step) % modulus for _ in range(snake_case_ ): # These track the position within the cycle detection logic. UpperCamelCase : int = seed UpperCamelCase : Optional[int] = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. UpperCamelCase : List[Any] = rand_fn(snake_case_ ,snake_case_ ,snake_case_ ) UpperCamelCase : Union[str, Any] = rand_fn(snake_case_ ,snake_case_ ,snake_case_ ) UpperCamelCase : List[Any] = rand_fn(snake_case_ ,snake_case_ ,snake_case_ ) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. UpperCamelCase : Tuple = gcd(hare - tortoise ,snake_case_ ) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. UpperCamelCase : Dict = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse __A : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '''num''', type=int, help='''The value to find a divisor of''', ) parser.add_argument( '''--attempts''', type=int, default=3, help='''The number of attempts before giving up''', ) __A : Optional[int] = parser.parse_args() __A : str = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(F'''{args.num} is probably prime''') else: __A : List[str] = args.num // divisor print(F'''{args.num} = {divisor} * {quotient}''')
27
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer __A : Any = logging.get_logger(__name__) __A : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A : Optional[Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } __A : Any = {'''allegro/herbert-base-cased''': 514} __A : Optional[Any] = {} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_INIT_CONFIGURATION lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = HerbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = [self.cls_token_id] UpperCamelCase : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): 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] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Tuple = [self.sep_token_id] UpperCamelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() __A : str = 2 class lowerCamelCase : def __init__( self , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : List[Any] = bos, unk, pad, eos UpperCamelCase : Dict = [] UpperCamelCase : List[str] = [] UpperCamelCase : Dict = {} UpperCamelCase : List[Any] = self.add_symbol(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.add_symbol(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.add_symbol(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.add_symbol(SCREAMING_SNAKE_CASE_ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = len(self.symbols ) def __eq__( self , SCREAMING_SNAKE_CASE_ ): return self.indices == other.indices def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self ): return len(self.symbols ) def __contains__( self , SCREAMING_SNAKE_CASE_ ): return sym in self.indices @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = cls() d.add_from_file(SCREAMING_SNAKE_CASE_ ) return d def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=False ): if word in self.indices and not overwrite: UpperCamelCase : str = self.indices[word] UpperCamelCase : List[Any] = self.count[idx] + n return idx else: UpperCamelCase : Optional[int] = len(self.symbols ) UpperCamelCase : List[Any] = idx self.symbols.append(SCREAMING_SNAKE_CASE_ ) self.count.append(SCREAMING_SNAKE_CASE_ ) return idx def a_ ( self , SCREAMING_SNAKE_CASE_ ): return 0 def a_ ( self , SCREAMING_SNAKE_CASE_ ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): try: with open(SCREAMING_SNAKE_CASE_ , """r""" , encoding="""utf-8""" ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE_ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception("""Incorrect encoding detected in {}, please rebuild the dataset""".format(SCREAMING_SNAKE_CASE_ ) ) return UpperCamelCase : Union[str, Any] = f.readlines() UpperCamelCase : str = self._load_meta(SCREAMING_SNAKE_CASE_ ) for line in lines[indices_start_line:]: try: UpperCamelCase , UpperCamelCase : Tuple = line.rstrip().rsplit(""" """ , 1 ) if field == "#fairseq:overwrite": UpperCamelCase : Any = True UpperCamelCase , UpperCamelCase : Union[str, Any] = line.rsplit(""" """ , 1 ) else: UpperCamelCase : Optional[int] = False UpperCamelCase : Any = int(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = line if word in self and not overwrite: raise RuntimeError( """Duplicate word found when loading Dictionary: '{}'. """ """Duplicate words can overwrite earlier ones by adding the """ """#fairseq:overwrite flag at the end of the corresponding row """ """in the dictionary file. If using the Camembert model, please """ """download an updated copy of the model file.""".format(SCREAMING_SNAKE_CASE_ ) ) self.add_symbol(SCREAMING_SNAKE_CASE_ , n=SCREAMING_SNAKE_CASE_ , overwrite=SCREAMING_SNAKE_CASE_ ) except ValueError: raise ValueError("""Incorrect dictionary format, expected '<token> <cnt> [flags]'""" ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} UpperCamelCase : Dict = dict((re.sub(R"""@@$""" ,"""""" ,snake_case_ ), v) if k.endswith("""@@""" ) else (re.sub(R"""$""" ,"""</w>""" ,snake_case_ ), v) for k, v in d.items() ) UpperCamelCase : str = """<s> <pad> </s> <unk>""".split() # restore the special tokens for k in keep_keys: del da[f'{k}</w>'] UpperCamelCase : Optional[int] = d[k] # restore return da def A_ ( snake_case_ : Any ,snake_case_ : int ): '''simple docstring''' # prep if not os.path.exists(snake_case_ ): raise ValueError(f'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(snake_case_ ,exist_ok=snake_case_ ) print(f'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models UpperCamelCase : Any = os.path.join(snake_case_ ,"""checkpoint.pt""" ) if not os.path.isfile(snake_case_ ): raise ValueError(f'path to the file {checkpoint_file} does not exist!' ) UpperCamelCase : List[str] = torch.load(snake_case_ ,map_location="""cpu""" ) UpperCamelCase : List[str] = chkpt["""cfg"""]["""model"""] # dicts UpperCamelCase : Optional[Any] = os.path.join(snake_case_ ,"""dict.txt""" ) if not os.path.isfile(snake_case_ ): raise ValueError(f'path to the file {dict_file} does not exist!' ) UpperCamelCase : Optional[Any] = Dictionary.load(snake_case_ ) UpperCamelCase : Union[str, Any] = rewrite_dict_keys(src_dict.indices ) UpperCamelCase : Tuple = len(snake_case_ ) UpperCamelCase : str = os.path.join(snake_case_ ,VOCAB_FILES_NAMES["""vocab_file"""] ) print(f'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_ ,ensure_ascii=snake_case_ ,indent=snake_case_ ) ) # merges_file (bpecodes) UpperCamelCase : int = os.path.join(snake_case_ ,"""bpecodes""" ) if not os.path.isfile(snake_case_ ): raise ValueError(f'path to the file {bpecodes_file} does not exist!' ) UpperCamelCase : Any = os.path.join(snake_case_ ,VOCAB_FILES_NAMES["""merges_file"""] ) shutil.copyfile(snake_case_ ,snake_case_ ) # model config UpperCamelCase : Union[str, Any] = os.path.join(snake_case_ ,"""config.json""" ) UpperCamelCase : str = { """activation_dropout""": args["""activation_dropout"""], """architectures""": ["""BioGptForCausalLM"""], """attention_probs_dropout_prob""": args["""attention_dropout"""], """bos_token_id""": 0, """eos_token_id""": 2, """hidden_act""": args["""activation_fn"""], """hidden_dropout_prob""": args["""dropout"""], """hidden_size""": args["""decoder_embed_dim"""], """initializer_range""": 0.02, """intermediate_size""": args["""decoder_ffn_embed_dim"""], """layer_norm_eps""": 1e-12, """layerdrop""": args["""decoder_layerdrop"""], """max_position_embeddings""": args["""max_target_positions"""], """model_type""": """biogpt""", """num_attention_heads""": args["""decoder_attention_heads"""], """num_hidden_layers""": args["""decoder_layers"""], """pad_token_id""": 1, """scale_embedding""": not args["""no_scale_embedding"""], """tie_word_embeddings""": args["""share_decoder_input_output_embed"""], """vocab_size""": src_vocab_size, } # good hparam defaults to start with print(f'Generating {biogpt_model_config_file}' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_ ,ensure_ascii=snake_case_ ,indent=snake_case_ ) ) # tokenizer config UpperCamelCase : Union[str, Any] = os.path.join(snake_case_ ,snake_case_ ) UpperCamelCase : Tuple = { """bos_token""": """<s>""", """eos_token""": """</s>""", """model_max_length""": 1_0_2_4, """pad_token""": """<pad>""", """special_tokens_map_file""": None, """tokenizer_class""": """BioGptTokenizer""", """unk_token""": """<unk>""", } print(f'Generating {biogpt_tokenizer_config_file}' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write(json.dumps(snake_case_ ,ensure_ascii=snake_case_ ,indent=snake_case_ ) ) # model UpperCamelCase : int = chkpt["""model"""] # remove unneeded keys UpperCamelCase : Any = [ """decoder.version""", ] for k in ignore_keys: model_state_dict.pop(snake_case_ ,snake_case_ ) UpperCamelCase : Tuple = list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith("""output_projection.weight""" ): UpperCamelCase : List[Any] = model_state_dict.pop(snake_case_ ) else: UpperCamelCase : Dict = model_state_dict.pop(snake_case_ ) UpperCamelCase : Dict = BioGptConfig.from_pretrained(snake_case_ ) UpperCamelCase : List[str] = BioGptForCausalLM(snake_case_ ) # check that it loads ok model_new.load_state_dict(snake_case_ ) # save UpperCamelCase : str = os.path.join(snake_case_ ,snake_case_ ) print(f'Generating {pytorch_weights_dump_path}' ) torch.save(snake_case_ ,snake_case_ ) print("""Conversion is done!""" ) if __name__ == "__main__": __A : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_checkpoint_path''', default=None, type=str, required=True, help=( '''Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,''' ''' bpecodes, etc.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) __A : List[str] = parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
27
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=3.6 ): UpperCamelCase : Dict = tokenizer UpperCamelCase : Optional[Any] = tokenizer.bos_token_id UpperCamelCase : Any = dataset UpperCamelCase : List[str] = seq_length UpperCamelCase : Optional[Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self ): UpperCamelCase : Dict = iter(self.dataset ) UpperCamelCase : Union[str, Any] = True while more_examples: UpperCamelCase , UpperCamelCase : Tuple = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(SCREAMING_SNAKE_CASE_ )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: UpperCamelCase : Dict = False break UpperCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )["""input_ids"""] UpperCamelCase : str = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , self.seq_length ): UpperCamelCase : List[str] = all_token_ids[i : i + self.seq_length] if len(SCREAMING_SNAKE_CASE_ ) == self.seq_length: yield torch.tensor(SCREAMING_SNAKE_CASE_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Dict = {"""streaming""": True} UpperCamelCase : Optional[int] = load_dataset(args.dataset_name ,split="""train""" ,**snake_case_ ) UpperCamelCase : Optional[int] = ConstantLengthDataset(snake_case_ ,snake_case_ ,seq_length=args.seq_length ) UpperCamelCase : List[Any] = DataLoader(snake_case_ ,batch_size=args.batch_size ) return eval_dataloader def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' model.eval() UpperCamelCase : Dict = [] for step, batch in enumerate(snake_case_ ): with torch.no_grad(): UpperCamelCase : List[Any] = model(snake_case_ ,labels=snake_case_ ) UpperCamelCase : Any = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(snake_case_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break UpperCamelCase : Dict = torch.mean(torch.cat(snake_case_ ) ) try: UpperCamelCase : Dict = torch.exp(snake_case_ ) except OverflowError: UpperCamelCase : Optional[int] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator __A : List[Any] = Accelerator() # Parse configuration __A : str = HfArgumentParser(EvaluationArguments) __A : List[Any] = parser.parse_args() set_seed(args.seed) # Logging __A : Any = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer __A : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) __A : List[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader __A : int = create_dataloader(args) # Prepare everything with our `accelerator`. __A , __A : Optional[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') __A , __A : Tuple = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
27
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 __A : str = subprocess.check_output('''git merge-base main HEAD'''.split()).decode('''utf-8''') __A : Union[str, Any] = subprocess.check_output(F'''git diff --name-only {fork_point_sha}'''.split()).decode('''utf-8''').split() __A : Dict = '''|'''.join(sys.argv[1:]) __A : int = re.compile(RF'''^({joined_dirs}).*?\.py$''') __A : List[Any] = [x for x in modified_files if regex.match(x)] print(''' '''.join(relevant_modified_files), end='''''')
27
"""simple docstring""" import argparse import os import re __A : Any = '''src/transformers''' # Pattern that looks at the indentation in a line. __A : Tuple = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : List[Any] = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Any = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : str ,snake_case_ : str="" ,snake_case_ : Any=None ,snake_case_ : Union[str, Any]=None ): '''simple docstring''' UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Tuple = ["""\n""".join(lines[:index] )] else: UpperCamelCase : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Dict = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = [lines[index + 1]] index += 1 else: UpperCamelCase : str = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : List[Any] ): '''simple docstring''' def _inner(snake_case_ : List[str] ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Optional[int] ): return x if key is None: UpperCamelCase : List[str] = noop # Constants are all uppercase, they go first. UpperCamelCase : List[str] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : Tuple = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : int = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Union[str, Any] = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : Any ): UpperCamelCase : Union[str, Any] = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : str = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : Optional[int] = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : int = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Tuple = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : List[Any] = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : List[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : Optional[int] = keys[:-1] UpperCamelCase : Union[str, Any] = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : Any = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : int=True ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : int = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Dict = main_blocks[block_idx] UpperCamelCase : Dict = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : List[str] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : Optional[Any] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Optional[Any] = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : List[Any] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Optional[Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Optional[Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Any = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : Union[str, Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[str] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: UpperCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Optional[int] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : List[Any] = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
1
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : Any = use_input_lengths UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = gelu_activation UpperCamelCase : Dict = sinusoidal_embeddings UpperCamelCase : Optional[int] = causal UpperCamelCase : List[Any] = asm UpperCamelCase : int = n_langs UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = n_special UpperCamelCase : Dict = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : List[str] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[str] = scope UpperCamelCase : Dict = bos_token_id def a_ ( self ): UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Union[str, Any] = None if self.use_input_lengths: UpperCamelCase : str = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[str] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a_ ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def a_ ( 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_ , ): UpperCamelCase : Optional[int] = XLMModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , lengths=SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( 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_ , ): UpperCamelCase : Optional[Any] = XLMWithLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( 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_ , ): UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( 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_ , ): UpperCamelCase : int = XLMForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , p_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , ) ((UpperCamelCase) , ) : Union[str, Any] = result_with_labels.to_tuple() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , ) : Tuple = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def a_ ( 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_ , ): UpperCamelCase : Union[str, Any] = XLMForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( 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_ , ): UpperCamelCase : int = self.num_labels UpperCamelCase : int = XLMForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : 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.num_labels) ) def a_ ( 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_ , ): UpperCamelCase : List[Any] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[Any] = config_and_inputs UpperCamelCase : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase : Optional[Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) return inputs_dict def a_ ( self ): UpperCamelCase : List[Any] = XLMModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , emb_dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_attentions in attentions] , [True] * len(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : Tuple = min_length + idx + 1 UpperCamelCase : Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_hidden_states in hidden_states] , [True] * len(SCREAMING_SNAKE_CASE_ ) , ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : List[str] = min_length + idx + 1 UpperCamelCase : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) , ) pass @slow def a_ ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = XLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Dict = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # the president UpperCamelCase : List[Any] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
1
"""simple docstring""" import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class lowerCamelCase ( pl.LightningModule ): def __init__( self , SCREAMING_SNAKE_CASE_ ): super().__init__() UpperCamelCase : int = model UpperCamelCase : Any = 2 UpperCamelCase : Dict = nn.Linear(self.model.config.hidden_size , self.num_labels ) def a_ ( self ): pass def A_ ( snake_case_ : str ,snake_case_ : str ,snake_case_ : str ): '''simple docstring''' # load longformer model from model identifier UpperCamelCase : Tuple = LongformerModel.from_pretrained(snake_case_ ) UpperCamelCase : Union[str, Any] = LightningModel(snake_case_ ) UpperCamelCase : Optional[int] = torch.load(snake_case_ ,map_location=torch.device("""cpu""" ) ) lightning_model.load_state_dict(ckpt["""state_dict"""] ) # init longformer question answering model UpperCamelCase : Optional[Any] = LongformerForQuestionAnswering.from_pretrained(snake_case_ ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(snake_case_ ) print(f'Conversion successful. Model saved under {pytorch_dump_folder_path}' ) if __name__ == "__main__": __A : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--longformer_model''', default=None, type=str, required=True, help='''model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.''', ) parser.add_argument( '''--longformer_question_answering_ckpt_path''', default=None, type=str, required=True, help='''Path the official PyTorch Lightning Checkpoint.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) __A : List[str] = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
27
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __A : Optional[Any] = logging.get_logger(__name__) def A_ ( snake_case_ : np.ndarray ,snake_case_ : Union[int, Iterable[int]] ,snake_case_ : bool ,snake_case_ : int ): '''simple docstring''' def constraint_to_multiple_of(snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : List[str]=0 ,snake_case_ : Optional[Any]=None ): UpperCamelCase : List[str] = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCamelCase : Optional[Any] = math.floor(val / multiple ) * multiple if x < min_val: UpperCamelCase : Dict = math.ceil(val / multiple ) * multiple return x UpperCamelCase : Any = (output_size, output_size) if isinstance(snake_case_ ,snake_case_ ) else output_size UpperCamelCase , UpperCamelCase : int = get_image_size(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = output_size # determine new height and width UpperCamelCase : List[str] = output_height / input_height UpperCamelCase : List[str] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCamelCase : int = scale_width else: # fit height UpperCamelCase : Optional[Any] = scale_height UpperCamelCase : int = constraint_to_multiple_of(scale_height * input_height ,multiple=snake_case_ ) UpperCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_width * input_width ,multiple=snake_case_ ) return (new_height, new_width) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = ['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = size if size is not None else {"""height""": 384, """width""": 384} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = do_resize UpperCamelCase : Union[str, Any] = size UpperCamelCase : Union[str, Any] = keep_aspect_ratio UpperCamelCase : Any = ensure_multiple_of UpperCamelCase : List[Any] = resample UpperCamelCase : str = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase : Dict = get_resize_output_image_size( SCREAMING_SNAKE_CASE_ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE_ , multiple=SCREAMING_SNAKE_CASE_ , ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( 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_ = None , 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_ , ): UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[Any] = size if size is not None else self.size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCamelCase : Optional[int] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCamelCase : Tuple = resample if resample is not None else self.resample UpperCamelCase : str = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Any = image_mean if image_mean is not None else self.image_mean UpperCamelCase : List[Any] = image_std if image_std is not None else self.image_std UpperCamelCase : 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_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase : int = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase : List[str] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase : Union[str, Any] = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : str = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = target_sizes.numpy() UpperCamelCase : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase : List[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : List[Any] = logits.argmax(dim=1 ) UpperCamelCase : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
27
1
"""simple docstring""" import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder __A : List[Any] = '''base_with_context''' def A_ ( snake_case_ : int ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Optional[int] = nn.Parameter(torch.FloatTensor(weights["""token_embedder"""]["""embedding"""] ) ) UpperCamelCase : Optional[int] = nn.Parameter( torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) ,requires_grad=snake_case_ ) for lyr_num, lyr in enumerate(model.encoders ): UpperCamelCase : Any = weights[f'layers_{lyr_num}'] UpperCamelCase : Optional[Any] = nn.Parameter( torch.FloatTensor(ly_weight["""pre_attention_layer_norm"""]["""scale"""] ) ) UpperCamelCase : str = ly_weight["""attention"""] UpperCamelCase : Dict = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) UpperCamelCase : str = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) UpperCamelCase : Any = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) UpperCamelCase : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) UpperCamelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) ) UpperCamelCase : Any = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) ) UpperCamelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) ) UpperCamelCase : Dict = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) ) UpperCamelCase : Optional[int] = nn.Parameter(torch.FloatTensor(weights["""encoder_norm"""]["""scale"""] ) ) return model def A_ ( snake_case_ : Tuple ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = nn.Parameter(torch.FloatTensor(weights["""input_proj"""]["""kernel"""].T ) ) UpperCamelCase : int = nn.Parameter( torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) ,requires_grad=snake_case_ ) for lyr_num, lyr in enumerate(model.encoders ): UpperCamelCase : Any = weights[f'layers_{lyr_num}'] UpperCamelCase : Optional[Any] = ly_weight["""attention"""] UpperCamelCase : Any = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) UpperCamelCase : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) UpperCamelCase : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) UpperCamelCase : str = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) UpperCamelCase : Tuple = nn.Parameter( torch.FloatTensor(ly_weight["""pre_attention_layer_norm"""]["""scale"""] ) ) UpperCamelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) ) UpperCamelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) ) UpperCamelCase : str = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) ) UpperCamelCase : str = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) ) UpperCamelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(weights["""encoder_norm"""]["""scale"""] ) ) return model def A_ ( snake_case_ : int ,snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(weights["""time_emb_dense0"""]["""kernel"""].T ) ) UpperCamelCase : List[str] = nn.Parameter(torch.FloatTensor(weights["""time_emb_dense1"""]["""kernel"""].T ) ) UpperCamelCase : List[str] = nn.Parameter( torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) ,requires_grad=snake_case_ ) UpperCamelCase : List[Any] = nn.Parameter( torch.FloatTensor(weights["""continuous_inputs_projection"""]["""kernel"""].T ) ) for lyr_num, lyr in enumerate(model.decoders ): UpperCamelCase : Union[str, Any] = weights[f'layers_{lyr_num}'] UpperCamelCase : int = nn.Parameter( torch.FloatTensor(ly_weight["""pre_self_attention_layer_norm"""]["""scale"""] ) ) UpperCamelCase : int = nn.Parameter( torch.FloatTensor(ly_weight["""FiLMLayer_0"""]["""DenseGeneral_0"""]["""kernel"""].T ) ) UpperCamelCase : Union[str, Any] = ly_weight["""self_attention"""] UpperCamelCase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) UpperCamelCase : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) UpperCamelCase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) UpperCamelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) UpperCamelCase : List[str] = ly_weight["""MultiHeadDotProductAttention_0"""] UpperCamelCase : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) UpperCamelCase : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) UpperCamelCase : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) UpperCamelCase : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) UpperCamelCase : Union[str, Any] = nn.Parameter( torch.FloatTensor(ly_weight["""pre_cross_attention_layer_norm"""]["""scale"""] ) ) UpperCamelCase : Any = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) ) UpperCamelCase : List[Any] = nn.Parameter( torch.FloatTensor(ly_weight["""FiLMLayer_1"""]["""DenseGeneral_0"""]["""kernel"""].T ) ) UpperCamelCase : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) ) UpperCamelCase : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) ) UpperCamelCase : str = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) ) UpperCamelCase : Optional[int] = nn.Parameter(torch.FloatTensor(weights["""decoder_norm"""]["""scale"""] ) ) UpperCamelCase : Any = nn.Parameter(torch.FloatTensor(weights["""spec_out_dense"""]["""kernel"""].T ) ) return model def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : str = checkpoints.load_tax_checkpoint(args.checkpoint_path ) UpperCamelCase : Optional[Any] = jnp.tree_util.tree_map(onp.array ,snake_case_ ) UpperCamelCase : Optional[Any] = [ """from __gin__ import dynamic_registration""", """from music_spectrogram_diffusion.models.diffusion import diffusion_utils""", """diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0""", """diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()""", ] UpperCamelCase : Optional[Any] = os.path.join(args.checkpoint_path ,"""..""" ,"""config.gin""" ) UpperCamelCase : Dict = inference.parse_training_gin_file(snake_case_ ,snake_case_ ) UpperCamelCase : Optional[Any] = inference.InferenceModel(args.checkpoint_path ,snake_case_ ) UpperCamelCase : List[Any] = DDPMScheduler(beta_schedule="""squaredcos_cap_v2""" ,variance_type="""fixed_large""" ) UpperCamelCase : int = SpectrogramNotesEncoder( max_length=synth_model.sequence_length["""inputs"""] ,vocab_size=synth_model.model.module.config.vocab_size ,d_model=synth_model.model.module.config.emb_dim ,dropout_rate=synth_model.model.module.config.dropout_rate ,num_layers=synth_model.model.module.config.num_encoder_layers ,num_heads=synth_model.model.module.config.num_heads ,d_kv=synth_model.model.module.config.head_dim ,d_ff=synth_model.model.module.config.mlp_dim ,feed_forward_proj="""gated-gelu""" ,) UpperCamelCase : str = SpectrogramContEncoder( input_dims=synth_model.audio_codec.n_dims ,targets_context_length=synth_model.sequence_length["""targets_context"""] ,d_model=synth_model.model.module.config.emb_dim ,dropout_rate=synth_model.model.module.config.dropout_rate ,num_layers=synth_model.model.module.config.num_encoder_layers ,num_heads=synth_model.model.module.config.num_heads ,d_kv=synth_model.model.module.config.head_dim ,d_ff=synth_model.model.module.config.mlp_dim ,feed_forward_proj="""gated-gelu""" ,) UpperCamelCase : Dict = TaFilmDecoder( input_dims=synth_model.audio_codec.n_dims ,targets_length=synth_model.sequence_length["""targets_context"""] ,max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time ,d_model=synth_model.model.module.config.emb_dim ,num_layers=synth_model.model.module.config.num_decoder_layers ,num_heads=synth_model.model.module.config.num_heads ,d_kv=synth_model.model.module.config.head_dim ,d_ff=synth_model.model.module.config.mlp_dim ,dropout_rate=synth_model.model.module.config.dropout_rate ,) UpperCamelCase : str = load_notes_encoder(ta_checkpoint["""target"""]["""token_encoder"""] ,snake_case_ ) UpperCamelCase : Optional[Any] = load_continuous_encoder(ta_checkpoint["""target"""]["""continuous_encoder"""] ,snake_case_ ) UpperCamelCase : Union[str, Any] = load_decoder(ta_checkpoint["""target"""]["""decoder"""] ,snake_case_ ) UpperCamelCase : List[str] = OnnxRuntimeModel.from_pretrained("""kashif/soundstream_mel_decoder""" ) UpperCamelCase : List[Any] = SpectrogramDiffusionPipeline( notes_encoder=snake_case_ ,continuous_encoder=snake_case_ ,decoder=snake_case_ ,scheduler=snake_case_ ,melgan=snake_case_ ,) if args.save: pipe.save_pretrained(args.output_path ) if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--output_path''', default=None, type=str, required=True, help='''Path to the converted model.''') parser.add_argument( '''--save''', default=True, type=bool, required=False, help='''Whether to save the converted model or not.''' ) parser.add_argument( '''--checkpoint_path''', default=F'''{MODEL}/checkpoint_500000''', type=str, required=False, help='''Path to the original jax model checkpoint.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
"""simple docstring""" from collections.abc import Callable def A_ ( snake_case_ : Callable[[float], float] ,snake_case_ : float ,snake_case_ : float ): '''simple docstring''' UpperCamelCase : float = a UpperCamelCase : float = b if function(snake_case_ ) == 0: # one of the a or b is a root for the function return a elif function(snake_case_ ) == 0: return b elif ( function(snake_case_ ) * function(snake_case_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: UpperCamelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(snake_case_ ) == 0: return mid elif function(snake_case_ ) * function(snake_case_ ) < 0: UpperCamelCase : Dict = mid else: UpperCamelCase : List[str] = mid UpperCamelCase : Tuple = start + (end - start) / 2.0 return mid def A_ ( snake_case_ : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
27
1
"""simple docstring""" from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig 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 TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCamelCase ( _UpperCAmelCase ): def a_ ( self ): UpperCamelCase : Optional[int] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """embed_dim""" ) ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """num_heads""" ) ) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[16, 48, 96] , SCREAMING_SNAKE_CASE_=[1, 3, 6] , SCREAMING_SNAKE_CASE_=[1, 2, 10] , SCREAMING_SNAKE_CASE_=[7, 3, 3] , SCREAMING_SNAKE_CASE_=[4, 2, 2] , SCREAMING_SNAKE_CASE_=[2, 1, 1] , SCREAMING_SNAKE_CASE_=[2, 2, 2] , SCREAMING_SNAKE_CASE_=[False, False, True] , SCREAMING_SNAKE_CASE_=[0.0, 0.0, 0.0] , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , ): UpperCamelCase : Optional[Any] = parent UpperCamelCase : List[str] = batch_size UpperCamelCase : Any = image_size UpperCamelCase : str = patch_sizes UpperCamelCase : int = patch_stride UpperCamelCase : int = patch_padding UpperCamelCase : Union[str, Any] = is_training UpperCamelCase : Any = use_labels UpperCamelCase : Optional[int] = num_labels UpperCamelCase : Optional[int] = num_channels UpperCamelCase : str = embed_dim UpperCamelCase : Union[str, Any] = num_heads UpperCamelCase : Dict = stride_kv UpperCamelCase : Optional[Any] = depth UpperCamelCase : List[str] = cls_token UpperCamelCase : List[str] = attention_drop_rate UpperCamelCase : List[Any] = initializer_range UpperCamelCase : Tuple = layer_norm_eps def a_ ( self ): UpperCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase : Optional[int] = None if self.use_labels: # create a random int32 tensor of given shape UpperCamelCase : str = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase : int = self.get_config() return config, pixel_values, labels def a_ ( self ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = TFCvtModel(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = (self.image_size, self.image_size) UpperCamelCase , UpperCamelCase : Optional[Any] = image_size[0], image_size[1] for i in range(len(self.depth ) ): UpperCamelCase : Optional[Any] = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) UpperCamelCase : Union[str, Any] = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_labels UpperCamelCase : str = TFCvtForImageClassification(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = 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 a_ ( self ): UpperCamelCase : List[str] = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = config_and_inputs UpperCamelCase : Optional[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : str = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () lowercase : Dict = ( {'feature-extraction': TFCvtModel, 'image-classification': TFCvtForImageClassification} if is_tf_available() else {} ) lowercase : Union[str, Any] = False lowercase : Any = False lowercase : str = False lowercase : str = False lowercase : Any = False def a_ ( self ): UpperCamelCase : Dict = TFCvtModelTester(self ) UpperCamelCase : List[str] = TFCvtConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def a_ ( self ): self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason="""Cvt does not output attentions""" ) def a_ ( self ): pass @unittest.skip(reason="""Cvt does not use inputs_embeds""" ) def a_ ( self ): pass @unittest.skip(reason="""Cvt does not support input and output embeddings""" ) def a_ ( self ): 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.""" , ) def a_ ( self ): super().test_dataset_conversion() @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 a_ ( self ): super().test_keras_fit() @unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8""" ) def a_ ( self ): UpperCamelCase : str = tf.keras.mixed_precision.Policy("""mixed_float16""" ) tf.keras.mixed_precision.set_global_policy(SCREAMING_SNAKE_CASE_ ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy("""float32""" ) def a_ ( self ): UpperCamelCase , UpperCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase : Any = [*signature.parameters.keys()] UpperCamelCase : Union[str, Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): def check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : List[Any] = outputs.hidden_states UpperCamelCase : int = len(self.model_tester.depth ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) UpperCamelCase , UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : Union[str, 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"] UpperCamelCase : List[Any] = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[int] = TFCvtModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : Optional[int] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class lowerCamelCase ( unittest.TestCase ): @cached_property def a_ ( self ): return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def a_ ( self ): UpperCamelCase : Union[str, Any] = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) UpperCamelCase : str = self.default_image_processor UpperCamelCase : List[Any] = prepare_img() UpperCamelCase : List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors="""tf""" ) # forward pass UpperCamelCase : str = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def a_ ( self ): UpperCamelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) UpperCamelCase : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) UpperCamelCase : Dict = """xvjiarui/stable-diffusion-2-inpainting""" UpperCamelCase , UpperCamelCase : List[str] = FlaxStableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = """Face of a yellow cat, high resolution, sitting on a park bench""" UpperCamelCase : List[str] = jax.random.PRNGKey(0 ) UpperCamelCase : Tuple = 50 UpperCamelCase : Dict = jax.device_count() UpperCamelCase : Optional[int] = num_samples * [prompt] UpperCamelCase : int = num_samples * [init_image] UpperCamelCase : List[Any] = num_samples * [mask_image] UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = pipeline.prepare_inputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # shard inputs and rng UpperCamelCase : Optional[int] = replicate(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = jax.random.split(SCREAMING_SNAKE_CASE_ , jax.device_count() ) UpperCamelCase : str = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = shard(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = pipeline( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , jit=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = output.images.reshape(SCREAMING_SNAKE_CASE_ , 512 , 512 , 3 ) UpperCamelCase : List[Any] = images[0, 253:256, 253:256, -1] UpperCamelCase : List[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase : Dict = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
27
1
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for multiprocessing '''simple docstring''' return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def A_ ( ): '''simple docstring''' with parallel_backend("""spark""" ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Optional[Any] = [1, 2, 3] with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=2 ) with pytest.raises(snake_case_ ): with parallel_backend("""unsupported backend""" ): map_nested(snake_case_ ,snake_case_ ,num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("""num_proc""" ,[2, -1] ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : List[Any] = [1, 2] UpperCamelCase : List[Any] = {"""a""": 1, """b""": 2} UpperCamelCase : List[str] = {"""a""": [1, 2], """b""": [3, 4]} UpperCamelCase : Tuple = {"""a""": {"""1""": 1}, """b""": 2} UpperCamelCase : Any = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} UpperCamelCase : Optional[int] = [2, 3] UpperCamelCase : List[str] = {"""a""": 2, """b""": 3} UpperCamelCase : Any = {"""a""": [2, 3], """b""": [4, 5]} UpperCamelCase : Tuple = {"""a""": {"""1""": 2}, """b""": 3} UpperCamelCase : List[str] = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} with parallel_backend("""spark""" ): assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa assert map_nested(snake_case_ ,snake_case_ ,num_proc=snake_case_ ) == expected_map_nested_sa
27
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : Optional[Any] = { '''configuration_informer''': [ '''INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''InformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ '''INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''InformerForPrediction''', '''InformerModel''', '''InformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Optional[Any] = is_training UpperCamelCase : Any = use_input_lengths UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Union[str, Any] = gelu_activation UpperCamelCase : Dict = sinusoidal_embeddings UpperCamelCase : Optional[int] = causal UpperCamelCase : List[Any] = asm UpperCamelCase : int = n_langs UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = n_special UpperCamelCase : Dict = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : List[str] = summary_type UpperCamelCase : int = use_proj UpperCamelCase : List[str] = scope UpperCamelCase : Dict = bos_token_id def a_ ( self ): UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Union[str, Any] = None if self.use_input_lengths: UpperCamelCase : str = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCamelCase : Tuple = None if self.use_token_type_ids: UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) UpperCamelCase : int = None UpperCamelCase : Dict = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Dict = ids_tensor([self.batch_size] , 2 ).float() UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[str] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def a_ ( self ): return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def a_ ( 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_ , ): UpperCamelCase : Optional[int] = XLMModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , lengths=SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ , langs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( 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_ , ): UpperCamelCase : Optional[Any] = XLMWithLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( 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_ , ): UpperCamelCase : List[str] = XLMForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( 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_ , ): UpperCamelCase : int = XLMForQuestionAnswering(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , p_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , cls_index=SCREAMING_SNAKE_CASE_ , is_impossible=SCREAMING_SNAKE_CASE_ , ) ((UpperCamelCase) , ) : Union[str, Any] = result_with_labels.to_tuple() UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , ) : Tuple = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def a_ ( 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_ , ): UpperCamelCase : Union[str, Any] = XLMForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a_ ( 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_ , ): UpperCamelCase : int = self.num_labels UpperCamelCase : int = XLMForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : 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.num_labels) ) def a_ ( 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_ , ): UpperCamelCase : List[Any] = self.num_choices UpperCamelCase : Tuple = XLMForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[Any] = config_and_inputs UpperCamelCase : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) lowercase : List[Any] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase : Optional[Any] = ( { 'feature-extraction': XLMModel, 'fill-mask': XLMWithLMHeadModel, 'question-answering': XLMForQuestionAnsweringSimple, 'text-classification': XLMForSequenceClassification, 'text-generation': XLMWithLMHeadModel, 'token-classification': XLMForTokenClassification, 'zero-shot': XLMForSequenceClassification, } if is_torch_available() else {} ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Union[str, Any] = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": UpperCamelCase : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) return inputs_dict def a_ ( self ): UpperCamelCase : List[Any] = XLMModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , emb_dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_attentions in attentions] , [True] * len(SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : int = min_length + idx + 1 UpperCamelCase : Tuple = min_length + idx + 1 UpperCamelCase : Any = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 ): self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( [isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for iter_hidden_states in hidden_states] , [True] * len(SCREAMING_SNAKE_CASE_ ) , ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(SCREAMING_SNAKE_CASE_ ): # adds PAD dummy token UpperCamelCase : List[str] = min_length + idx + 1 UpperCamelCase : Optional[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(SCREAMING_SNAKE_CASE_ ) , ) pass @slow def a_ ( self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : str = XLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Dict = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # the president UpperCamelCase : List[Any] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference UpperCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , SCREAMING_SNAKE_CASE_ )
27
1
"""simple docstring""" from math import ceil def A_ ( snake_case_ : int = 1_0_0_1 ): '''simple docstring''' UpperCamelCase : str = 1 for i in range(1 ,int(ceil(n / 2.0 ) ) ): UpperCamelCase : Optional[Any] = 2 * i + 1 UpperCamelCase : List[str] = 2 * i UpperCamelCase : Optional[int] = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: __A : Dict = int(sys.argv[1]) print(solution(n)) except ValueError: print('''Invalid entry - please enter a number''')
27
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __A : int = { '''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ '''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTBigCodeForSequenceClassification''', '''GPTBigCodeForTokenClassification''', '''GPTBigCodeForCausalLM''', '''GPTBigCodeModel''', '''GPTBigCodePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys __A : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
1
"""simple docstring""" import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Tuple = tmp_path / """file.csv""" UpperCamelCase : Union[str, Any] = textwrap.dedent( """\ header1,header2 1,2 10,20 """ ) with open(snake_case_ ,"""w""" ) as f: f.write(snake_case_ ) return str(snake_case_ ) @pytest.fixture def A_ ( snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : Optional[Any] = tmp_path / """malformed_file.csv""" UpperCamelCase : int = textwrap.dedent( """\ header1,header2 1,2 10,20, """ ) with open(snake_case_ ,"""w""" ) as f: f.write(snake_case_ ) return str(snake_case_ ) @pytest.fixture def A_ ( snake_case_ : List[str] ,snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : Tuple = tmp_path / """csv_with_image.csv""" UpperCamelCase : List[str] = textwrap.dedent( f'\\n image\n {image_file}\n ' ) with open(snake_case_ ,"""w""" ) as f: f.write(snake_case_ ) return str(snake_case_ ) @pytest.fixture def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : List[Any] = tmp_path / """csv_with_label.csv""" UpperCamelCase : Optional[Any] = textwrap.dedent( """\ label good bad good """ ) with open(snake_case_ ,"""w""" ) as f: f.write(snake_case_ ) return str(snake_case_ ) @pytest.fixture def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[Any] = tmp_path / """csv_with_int_list.csv""" UpperCamelCase : int = textwrap.dedent( """\ int_list 1 2 3 4 5 6 7 8 9 """ ) with open(snake_case_ ,"""w""" ) as f: f.write(snake_case_ ) return str(snake_case_ ) def A_ ( snake_case_ : Dict ,snake_case_ : Optional[Any] ,snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Tuple = Csv() UpperCamelCase : Optional[Any] = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(snake_case_ ,match="""Error tokenizing data""" ): for _ in generator: pass assert any( record.levelname == """ERROR""" and """Failed to read file""" in record.message and os.path.basename(snake_case_ ) in record.message for record in caplog.records ) @require_pil def A_ ( snake_case_ : Tuple ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : Tuple = f.read().splitlines()[1] UpperCamelCase : List[str] = Csv(encoding="""utf-8""" ,features=Features({"""image""": Image()} ) ) UpperCamelCase : Any = csv._generate_tables([[csv_file_with_image]] ) UpperCamelCase : List[str] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("""image""" ).type == Image()() UpperCamelCase : List[str] = pa_table.to_pydict()["""image"""] assert generated_content == [{"path": image_file, "bytes": None}] def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : List[str] = f.read().splitlines()[1:] UpperCamelCase : Optional[int] = Csv(encoding="""utf-8""" ,features=Features({"""label""": ClassLabel(names=["""good""", """bad"""] )} ) ) UpperCamelCase : Any = csv._generate_tables([[csv_file_with_label]] ) UpperCamelCase : Union[str, Any] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("""label""" ).type == ClassLabel(names=["""good""", """bad"""] )() UpperCamelCase : Tuple = pa_table.to_pydict()["""label"""] assert generated_content == [ClassLabel(names=["""good""", """bad"""] ).straint(snake_case_ ) for label in labels] def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Any = Csv(encoding="""utf-8""" ,sep=""",""" ,converters={"""int_list""": lambda snake_case_ : [int(snake_case_ ) for i in x.split()]} ) UpperCamelCase : Dict = csv._generate_tables([[csv_file_with_int_list]] ) UpperCamelCase : Union[str, Any] = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field("""int_list""" ).type ) UpperCamelCase : Union[str, Any] = pa_table.to_pydict()["""int_list"""] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
27
"""simple docstring""" import torch from transformers import AutoModel class lowerCamelCase ( torch.nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_="sayef/fsner-bert-base-uncased" ): super(SCREAMING_SNAKE_CASE_ , self ).__init__() UpperCamelCase : int = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.nn.CosineSimilarity(3 , 1e-08 ) UpperCamelCase : Any = torch.nn.Softmax(dim=1 ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return self.bert(**SCREAMING_SNAKE_CASE_ ).last_hidden_state def a_ ( self , SCREAMING_SNAKE_CASE_ ): return token_embeddings.sum(2 , keepdim=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=1 ): return self.softmax(T * self.cos(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = W_supports["""sizes"""].tolist() UpperCamelCase : List[str] = W_supports["""start_token_id"""].item() UpperCamelCase : List[Any] = W_supports["""end_token_id"""].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] UpperCamelCase : List[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.BERT(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = None UpperCamelCase : Optional[Any] = None UpperCamelCase : Tuple = W_supports["""input_ids"""] == start_token_id UpperCamelCase : Optional[Any] = W_supports["""input_ids"""] == end_token_id for i, size in enumerate(SCREAMING_SNAKE_CASE_ ): if i == 0: UpperCamelCase : int = 0 else: UpperCamelCase : Optional[int] = support_sizes[i - 1] UpperCamelCase : Tuple = S[s : s + size][start_token_masks[s : s + size]] UpperCamelCase : int = S[s : s + size][end_token_masks[s : s + size]] UpperCamelCase : Dict = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) UpperCamelCase : Tuple = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: UpperCamelCase : List[str] = torch.vstack((p_starts, p_start) ) UpperCamelCase : Optional[Any] = torch.vstack((p_ends, p_end) ) else: UpperCamelCase : Optional[int] = p_start UpperCamelCase : Tuple = p_end return p_starts, p_ends
27
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A : Union[str, Any] = { '''configuration_data2vec_audio''': ['''DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecAudioConfig'''], '''configuration_data2vec_text''': [ '''DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecTextConfig''', '''Data2VecTextOnnxConfig''', ], '''configuration_data2vec_vision''': [ '''DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecVisionConfig''', '''Data2VecVisionOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[Any] = [ '''DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecAudioForAudioFrameClassification''', '''Data2VecAudioForCTC''', '''Data2VecAudioForSequenceClassification''', '''Data2VecAudioForXVector''', '''Data2VecAudioModel''', '''Data2VecAudioPreTrainedModel''', ] __A : Tuple = [ '''DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecTextForCausalLM''', '''Data2VecTextForMaskedLM''', '''Data2VecTextForMultipleChoice''', '''Data2VecTextForQuestionAnswering''', '''Data2VecTextForSequenceClassification''', '''Data2VecTextForTokenClassification''', '''Data2VecTextModel''', '''Data2VecTextPreTrainedModel''', ] __A : Any = [ '''DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecVisionForImageClassification''', '''Data2VecVisionForMaskedImageModeling''', '''Data2VecVisionForSemanticSegmentation''', '''Data2VecVisionModel''', '''Data2VecVisionPreTrainedModel''', ] if is_tf_available(): __A : Union[str, Any] = [ '''TFData2VecVisionForImageClassification''', '''TFData2VecVisionForSemanticSegmentation''', '''TFData2VecVisionModel''', '''TFData2VecVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
27
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = data UpperCamelCase : Optional[Any] = None def __repr__( self ): return f'Node({self.data})' class lowerCamelCase : def __init__( self ): UpperCamelCase : Dict = None def __iter__( self ): UpperCamelCase : int = self.head while node: yield node.data UpperCamelCase : Union[str, Any] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCamelCase : List[Any] = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = current.next UpperCamelCase : Optional[Any] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCamelCase : Optional[Any] = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: UpperCamelCase : Dict = new_node elif index == 0: UpperCamelCase : Any = self.head # link new_node to head UpperCamelCase : Any = new_node else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : str = temp.next UpperCamelCase : Any = temp.next UpperCamelCase : Optional[Any] = new_node def a_ ( self ): # print every node data print(self ) def a_ ( self ): return self.delete_nth(0 ) def a_ ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCamelCase : Union[str, Any] = self.head # default first node if index == 0: UpperCamelCase : Optional[Any] = self.head.next else: UpperCamelCase : Dict = self.head for _ in range(index - 1 ): UpperCamelCase : int = temp.next UpperCamelCase : Optional[Any] = temp.next UpperCamelCase : Dict = temp.next.next return delete_node.data def a_ ( self ): return self.head is None def a_ ( self ): UpperCamelCase : Optional[Any] = None UpperCamelCase : Union[str, Any] = self.head while current: # Store the current node's next node. UpperCamelCase : Optional[int] = current.next # Make the current node's next point backwards UpperCamelCase : Optional[Any] = prev # Make the previous node be the current node UpperCamelCase : int = current # Make the current node the next node (to progress iteration) UpperCamelCase : Optional[int] = next_node # Return prev in order to put the head at the end UpperCamelCase : Optional[int] = prev def A_ ( ): '''simple docstring''' UpperCamelCase : int = LinkedList() assert linked_list.is_empty() is True assert str(snake_case_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(1_0 ): assert len(snake_case_ ) == i linked_list.insert_nth(snake_case_ ,i + 1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(0 ,1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(snake_case_ ) == 9 assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(1 ,1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): UpperCamelCase : Optional[Any] = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(snake_case_ ) == "->".join(str(snake_case_ ) for i in range(-8 ,1 ) ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), """dlrow olleH""", 7, 5_5_5_5, 0, -192.55555, """Hello, world!""", 77.9, Node(1_0 ), None, None, 12.20, ] UpperCamelCase : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(snake_case_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(snake_case_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCamelCase : Dict = linked_list.delete_head() assert result == -9 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCamelCase : int = linked_list.delete_tail() assert result == 12.2 assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCamelCase : Optional[Any] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(snake_case_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(snake_case_ ) assert ( str(snake_case_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(snake_case_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def A_ ( ): '''simple docstring''' from doctest import testmod testmod() UpperCamelCase : List[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(snake_case_ ) print("""\nReading/changing Node data using indexing:""" ) print(f'Element at Position 1: {linked_list[1]}' ) UpperCamelCase : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(snake_case_ ) print(f'length of linked_list is : {len(snake_case_ )}' ) if __name__ == "__main__": main()
27
1
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCamelCase ( _UpperCAmelCase ): lowercase : int = 'WhisperFeatureExtractor' lowercase : Dict = 'WhisperTokenizer' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.feature_extractor UpperCamelCase : Optional[Any] = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[Any] = args[0] UpperCamelCase : Dict = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: UpperCamelCase : Tuple = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if text is not None: UpperCamelCase : Dict = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if text is None: return inputs elif audio is None: return encodings else: UpperCamelCase : Optional[Any] = encodings["""input_ids"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="np" ): return self.tokenizer.get_prompt_ids(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ )
27
"""simple docstring""" import argparse import os import re __A : Dict = '''src/diffusers''' # Pattern that looks at the indentation in a line. __A : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __A : Dict = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __A : List[str] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __A : Tuple = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __A : Tuple = re.compile(R'''\[([^\]]+)\]''') def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Union[str, Any] = _re_indent.search(snake_case_ ) return "" if search is None else search.groups()[0] def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict="" ,snake_case_ : Dict=None ,snake_case_ : Any=None ): '''simple docstring''' UpperCamelCase : Optional[int] = 0 UpperCamelCase : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(snake_case_ ): index += 1 UpperCamelCase : Optional[Any] = ["""\n""".join(lines[:index] )] else: UpperCamelCase : int = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). UpperCamelCase : Any = [lines[index]] index += 1 while index < len(snake_case_ ) and (end_prompt is None or not lines[index].startswith(snake_case_ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(snake_case_ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(snake_case_ ) ) if index < len(snake_case_ ) - 1: UpperCamelCase : Any = [lines[index + 1]] index += 1 else: UpperCamelCase : List[str] = [] else: blocks.append("""\n""".join(snake_case_ ) ) UpperCamelCase : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(snake_case_ ) > 0: blocks.append("""\n""".join(snake_case_ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case_ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def _inner(snake_case_ : Tuple ): return key(snake_case_ ).lower().replace("""_""" ,"""""" ) return _inner def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int]=None ): '''simple docstring''' # If no key is provided, we use a noop. def noop(snake_case_ : Dict ): return x if key is None: UpperCamelCase : int = noop # Constants are all uppercase, they go first. UpperCamelCase : List[Any] = [obj for obj in objects if key(snake_case_ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. UpperCamelCase : str = [obj for obj in objects if key(snake_case_ )[0].isupper() and not key(snake_case_ ).isupper()] # Functions begin with a lowercase, they go last. UpperCamelCase : List[str] = [obj for obj in objects if not key(snake_case_ )[0].isupper()] UpperCamelCase : Tuple = ignore_underscore(snake_case_ ) return sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) + sorted(snake_case_ ,key=snake_case_ ) def A_ ( snake_case_ : int ): '''simple docstring''' # This inner function sort imports between [ ]. def _replace(snake_case_ : List[Any] ): UpperCamelCase : Any = match.groups()[0] if "," not in imports: return f'[{imports}]' UpperCamelCase : Union[str, Any] = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[str] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(snake_case_ )] ) + "]" UpperCamelCase : str = import_statement.split("""\n""" ) if len(snake_case_ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. UpperCamelCase : str = 2 if lines[1].strip() == """[""" else 1 UpperCamelCase : Dict = [(i, _re_strip_line.search(snake_case_ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] UpperCamelCase : int = sort_objects(snake_case_ ,key=lambda snake_case_ : x[1] ) UpperCamelCase : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(snake_case_ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: UpperCamelCase : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: UpperCamelCase : Optional[Any] = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: UpperCamelCase : List[Any] = keys[:-1] UpperCamelCase : int = get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(snake_case_ )] ) return "\n".join(snake_case_ ) else: # Finally we have to deal with imports fitting on one line UpperCamelCase : List[str] = _re_bracket_content.sub(_replace ,snake_case_ ) return import_statement def A_ ( snake_case_ : Tuple ,snake_case_ : str=True ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as f: UpperCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 UpperCamelCase : Dict = split_code_in_indented_blocks( snake_case_ ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(snake_case_ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. UpperCamelCase : Optional[Any] = main_blocks[block_idx] UpperCamelCase : Optional[int] = block.split("""\n""" ) # Get to the start of the imports. UpperCamelCase : Union[str, Any] = 0 while line_idx < len(snake_case_ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: UpperCamelCase : List[str] = len(snake_case_ ) else: line_idx += 1 if line_idx >= len(snake_case_ ): continue # Ignore beginning and last line: they don't contain anything. UpperCamelCase : Dict = """\n""".join(block_lines[line_idx:-1] ) UpperCamelCase : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. UpperCamelCase : Optional[int] = split_code_in_indented_blocks(snake_case_ ,indent_level=snake_case_ ) # We have two categories of import key: list or _import_structure[key].append/extend UpperCamelCase : Union[str, Any] = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. UpperCamelCase : Union[str, Any] = [(pattern.search(snake_case_ ).groups()[0] if pattern.search(snake_case_ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. UpperCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(snake_case_ ) if key is not None] UpperCamelCase : List[Any] = [x[0] for x in sorted(snake_case_ ,key=lambda snake_case_ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. UpperCamelCase : str = 0 UpperCamelCase : List[Any] = [] for i in range(len(snake_case_ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: UpperCamelCase : str = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(snake_case_ ) count += 1 # And we put our main block back together with its first and last line. UpperCamelCase : Tuple = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(snake_case_ ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(snake_case_ ,"""w""" ) as f: f.write("""\n""".join(snake_case_ ) ) def A_ ( snake_case_ : int=True ): '''simple docstring''' UpperCamelCase : Any = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCamelCase : Union[str, Any] = sort_imports(os.path.join(snake_case_ ,"""__init__.py""" ) ,check_only=snake_case_ ) if result: UpperCamelCase : Any = [os.path.join(snake_case_ ,"""__init__.py""" )] if len(snake_case_ ) > 0: raise ValueError(f'Would overwrite {len(snake_case_ )} files, run `make style`.' ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __A : str = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
27
1
"""simple docstring""" import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() __A : List[str] = logging.get_logger(__name__) def A_ ( snake_case_ : Any ,snake_case_ : int ,snake_case_ : Any ): '''simple docstring''' UpperCamelCase : str = UniSpeechSatForSequenceClassification.from_pretrained(snake_case_ ,config=snake_case_ ) UpperCamelCase : List[Any] = downstream_dict["""projector.weight"""] UpperCamelCase : Tuple = downstream_dict["""projector.bias"""] UpperCamelCase : List[str] = downstream_dict["""model.post_net.linear.weight"""] UpperCamelCase : int = downstream_dict["""model.post_net.linear.bias"""] return model def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Tuple ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : Union[str, Any] = UniSpeechSatForAudioFrameClassification.from_pretrained(snake_case_ ,config=snake_case_ ) UpperCamelCase : str = downstream_dict["""model.linear.weight"""] UpperCamelCase : int = downstream_dict["""model.linear.bias"""] return model def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Dict ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : Union[str, Any] = UniSpeechSatForXVector.from_pretrained(snake_case_ ,config=snake_case_ ) UpperCamelCase : Union[str, Any] = downstream_dict["""connector.weight"""] UpperCamelCase : Optional[Any] = downstream_dict["""connector.bias"""] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): UpperCamelCase : Optional[int] = downstream_dict[ f'model.framelevel_feature_extractor.module.{i}.kernel.weight' ] UpperCamelCase : int = downstream_dict[f'model.framelevel_feature_extractor.module.{i}.kernel.bias'] UpperCamelCase : Optional[Any] = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""] UpperCamelCase : List[Any] = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""] UpperCamelCase : Union[str, Any] = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""] UpperCamelCase : str = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""] UpperCamelCase : Optional[int] = downstream_dict["""objective.W"""] return model @torch.no_grad() def A_ ( snake_case_ : Optional[int] ,snake_case_ : Dict ,snake_case_ : Optional[int] ,snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : Optional[Any] = torch.load(snake_case_ ,map_location="""cpu""" ) UpperCamelCase : List[str] = checkpoint["""Downstream"""] UpperCamelCase : List[Any] = UniSpeechSatConfig.from_pretrained(snake_case_ ) UpperCamelCase : List[Any] = WavaVecaFeatureExtractor.from_pretrained( snake_case_ ,return_attention_mask=snake_case_ ,do_normalize=snake_case_ ) UpperCamelCase : str = hf_config.architectures[0] if arch.endswith("""ForSequenceClassification""" ): UpperCamelCase : List[Any] = convert_classification(snake_case_ ,snake_case_ ,snake_case_ ) elif arch.endswith("""ForAudioFrameClassification""" ): UpperCamelCase : int = convert_diarization(snake_case_ ,snake_case_ ,snake_case_ ) elif arch.endswith("""ForXVector""" ): UpperCamelCase : List[str] = convert_xvector(snake_case_ ,snake_case_ ,snake_case_ ) else: raise NotImplementedError(f'S3PRL weights conversion is not supported for {arch}' ) if hf_config.use_weighted_layer_sum: UpperCamelCase : str = checkpoint["""Featurizer"""]["""weights"""] hf_feature_extractor.save_pretrained(snake_case_ ) hf_model.save_pretrained(snake_case_ ) if __name__ == "__main__": __A : str = argparse.ArgumentParser() parser.add_argument( '''--base_model_name''', default=None, type=str, help='''Name of the huggingface pretrained base model.''' ) parser.add_argument('''--config_path''', default=None, type=str, help='''Path to the huggingface classifier config.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to the s3prl checkpoint.''') parser.add_argument('''--model_dump_path''', default=None, type=str, help='''Path to the final converted model.''') __A : Tuple = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
27
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
1
"""simple docstring""" import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A : Union[str, Any] = logging.get_logger(__name__) __A : Tuple = {'''vocab_file''': '''vocab.json'''} __A : List[Any] = { '''vocab_file''': { '''mgp-str''': '''https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json''', } } __A : Union[str, Any] = {'''mgp-str''': 27} class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[int] = VOCAB_FILES_NAMES lowercase : str = PRETRAINED_VOCAB_FILES_MAP lowercase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="[GO]" , SCREAMING_SNAKE_CASE_="[GO]" , SCREAMING_SNAKE_CASE_="[s]" , SCREAMING_SNAKE_CASE_="[GO]" , **SCREAMING_SNAKE_CASE_ ): 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: UpperCamelCase : Dict = json.load(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = {v: k for k, v in self.vocab.items()} @property def a_ ( self ): return len(self.vocab ) def a_ ( self ): return dict(self.vocab , **self.added_tokens_encoder ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = [] for s in text: char_tokens.extend(SCREAMING_SNAKE_CASE_ ) return char_tokens def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.vocab.get(SCREAMING_SNAKE_CASE_ , self.vocab.get(self.unk_token ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.decoder.get(SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error("""Vocabulary path ({}) should be a directory""".format(SCREAMING_SNAKE_CASE_ ) ) return UpperCamelCase : str = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) with open(SCREAMING_SNAKE_CASE_ , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) + """\n""" ) return (vocab_file,)
27
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = AudioLDMPipeline lowercase : Union[str, Any] = TEXT_TO_AUDIO_PARAMS lowercase : List[str] = TEXT_TO_AUDIO_BATCH_PARAMS lowercase : Tuple = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Tuple = 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, 64) , class_embed_type="""simple_projection""" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[Any] = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCamelCase : int = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) UpperCamelCase : Optional[int] = ClapTextModelWithProjection(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta""" , model_max_length=77 ) UpperCamelCase : Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Any = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def a_ ( self ): UpperCamelCase : str = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Any = self.get_dummy_components() UpperCamelCase : int = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Tuple = audio[:10] UpperCamelCase : Dict = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[str] = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) UpperCamelCase : Tuple = prompt_embeds # forward UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : List[str] = self.get_dummy_components() UpperCamelCase : List[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = 3 * ["""this is a negative prompt"""] UpperCamelCase : List[Any] = negative_prompt UpperCamelCase : str = 3 * [inputs["""prompt"""]] # forward UpperCamelCase : str = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = 3 * [inputs.pop("""prompt""" )] UpperCamelCase : List[Any] = [] for p in [prompt, negative_prompt]: UpperCamelCase : int = audioldm_pipe.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase : Union[str, Any] = text_inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audioldm_pipe.text_encoder( SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = text_embeds.text_embeds # additional L_2 normalization over each hidden-state UpperCamelCase : Optional[int] = F.normalize(SCREAMING_SNAKE_CASE_ , dim=-1 ) embeds.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Tuple = embeds # forward UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Optional[int] = self.get_dummy_components() UpperCamelCase : List[str] = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = """egg cracking""" UpperCamelCase : List[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 256 UpperCamelCase : Union[str, Any] = audio[:10] UpperCamelCase : Dict = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Union[str, Any] = self.get_dummy_components() UpperCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) UpperCamelCase : List[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts UpperCamelCase : Dict = 2 UpperCamelCase : List[str] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt UpperCamelCase : List[str] = 2 UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts UpperCamelCase : Any = 2 UpperCamelCase : str = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=SCREAMING_SNAKE_CASE_ ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def a_ ( self ): UpperCamelCase : Optional[int] = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Tuple = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config.sampling_rate UpperCamelCase : List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = audioldm_pipe(audio_length_in_s=0.016 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.016 UpperCamelCase : Optional[Any] = audioldm_pipe(audio_length_in_s=0.032 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) / vocoder_sampling_rate == 0.032 def a_ ( self ): UpperCamelCase : str = self.get_dummy_components() UpperCamelCase : Optional[Any] = AudioLDMPipeline(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = ["""hey"""] UpperCamelCase : Dict = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : str = output.audios.shape assert audio_shape == (1, 256) UpperCamelCase : Optional[Any] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 UpperCamelCase : str = SpeechTaHifiGan(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = audioldm_pipe(SCREAMING_SNAKE_CASE_ , num_inference_steps=1 ) UpperCamelCase : List[str] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def a_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self._test_inference_batch_single_identical(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def a_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE_ ) @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="cpu" , SCREAMING_SNAKE_CASE_=torch.floataa , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 8, 128, 16) ) UpperCamelCase : int = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def a_ ( self ): UpperCamelCase : Optional[int] = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : List[Any] = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 25 UpperCamelCase : Optional[Any] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[7_7230:7_7240] UpperCamelCase : Optional[Any] = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) UpperCamelCase : Any = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def a_ ( self ): UpperCamelCase : Any = AudioLDMPipeline.from_pretrained("""cvssp/audioldm""" ) UpperCamelCase : Any = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) UpperCamelCase : str = audioldm_pipe.to(SCREAMING_SNAKE_CASE_ ) audioldm_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.get_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = audioldm_pipe(**SCREAMING_SNAKE_CASE_ ).audios[0] assert audio.ndim == 1 assert len(SCREAMING_SNAKE_CASE_ ) == 8_1920 UpperCamelCase : Union[str, Any] = audio[2_7780:2_7790] UpperCamelCase : Tuple = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) UpperCamelCase : Tuple = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
27
1
"""simple docstring""" import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[Any]=1 ): '''simple docstring''' if n_shave_prefix_segments >= 0: return ".".join(path.split(""".""" )[n_shave_prefix_segments:] ) else: return ".".join(path.split(""".""" )[:n_shave_prefix_segments] ) def A_ ( snake_case_ : int ,snake_case_ : Union[str, Any]=0 ): '''simple docstring''' UpperCamelCase : int = [] for old_item in old_list: UpperCamelCase : str = old_item.replace("""in_layers.0""" ,"""norm1""" ) UpperCamelCase : str = new_item.replace("""in_layers.2""" ,"""conv1""" ) UpperCamelCase : Optional[int] = new_item.replace("""out_layers.0""" ,"""norm2""" ) UpperCamelCase : Any = new_item.replace("""out_layers.3""" ,"""conv2""" ) UpperCamelCase : Tuple = new_item.replace("""emb_layers.1""" ,"""time_emb_proj""" ) UpperCamelCase : List[Any] = new_item.replace("""skip_connection""" ,"""conv_shortcut""" ) UpperCamelCase : Optional[int] = shave_segments(snake_case_ ,n_shave_prefix_segments=snake_case_ ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def A_ ( snake_case_ : Tuple ,snake_case_ : Dict=0 ): '''simple docstring''' UpperCamelCase : int = [] for old_item in old_list: UpperCamelCase : Tuple = old_item UpperCamelCase : Optional[int] = new_item.replace("""norm.weight""" ,"""group_norm.weight""" ) UpperCamelCase : Dict = new_item.replace("""norm.bias""" ,"""group_norm.bias""" ) UpperCamelCase : Optional[int] = new_item.replace("""proj_out.weight""" ,"""proj_attn.weight""" ) UpperCamelCase : List[str] = new_item.replace("""proj_out.bias""" ,"""proj_attn.bias""" ) UpperCamelCase : Any = shave_segments(snake_case_ ,n_shave_prefix_segments=snake_case_ ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def A_ ( snake_case_ : Any ,snake_case_ : Union[str, Any] ,snake_case_ : Tuple ,snake_case_ : Optional[Any]=None ,snake_case_ : Any=None ,snake_case_ : Any=None ): '''simple docstring''' assert isinstance(snake_case_ ,snake_case_ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): UpperCamelCase : str = old_checkpoint[path] UpperCamelCase : Dict = old_tensor.shape[0] // 3 UpperCamelCase : Any = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) UpperCamelCase : List[str] = old_tensor.shape[0] // config["""num_head_channels"""] // 3 UpperCamelCase : Optional[Any] = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) UpperCamelCase , UpperCamelCase , UpperCamelCase : Dict = old_tensor.split(channels // num_heads ,dim=1 ) UpperCamelCase : List[Any] = query.reshape(snake_case_ ) UpperCamelCase : Optional[Any] = key.reshape(snake_case_ ) UpperCamelCase : Any = value.reshape(snake_case_ ) for path in paths: UpperCamelCase : Any = path["""new"""] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here UpperCamelCase : str = new_path.replace("""middle_block.0""" ,"""mid_block.resnets.0""" ) UpperCamelCase : Tuple = new_path.replace("""middle_block.1""" ,"""mid_block.attentions.0""" ) UpperCamelCase : Union[str, Any] = new_path.replace("""middle_block.2""" ,"""mid_block.resnets.1""" ) if additional_replacements is not None: for replacement in additional_replacements: UpperCamelCase : Optional[int] = new_path.replace(replacement["""old"""] ,replacement["""new"""] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: UpperCamelCase : Optional[Any] = old_checkpoint[path["""old"""]][:, :, 0] else: UpperCamelCase : str = old_checkpoint[path["""old"""]] def A_ ( snake_case_ : List[Any] ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Tuple = {} UpperCamelCase : str = checkpoint["""time_embed.0.weight"""] UpperCamelCase : str = checkpoint["""time_embed.0.bias"""] UpperCamelCase : Optional[Any] = checkpoint["""time_embed.2.weight"""] UpperCamelCase : Union[str, Any] = checkpoint["""time_embed.2.bias"""] UpperCamelCase : int = checkpoint["""input_blocks.0.0.weight"""] UpperCamelCase : Union[str, Any] = checkpoint["""input_blocks.0.0.bias"""] UpperCamelCase : Optional[int] = checkpoint["""out.0.weight"""] UpperCamelCase : Tuple = checkpoint["""out.0.bias"""] UpperCamelCase : str = checkpoint["""out.2.weight"""] UpperCamelCase : Optional[int] = checkpoint["""out.2.bias"""] # Retrieves the keys for the input blocks only UpperCamelCase : int = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """input_blocks""" in layer} ) UpperCamelCase : Dict = { layer_id: [key for key in checkpoint if f'input_blocks.{layer_id}' in key] for layer_id in range(snake_case_ ) } # Retrieves the keys for the middle blocks only UpperCamelCase : Tuple = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """middle_block""" in layer} ) UpperCamelCase : Tuple = { layer_id: [key for key in checkpoint if f'middle_block.{layer_id}' in key] for layer_id in range(snake_case_ ) } # Retrieves the keys for the output blocks only UpperCamelCase : Optional[Any] = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """output_blocks""" in layer} ) UpperCamelCase : Optional[Any] = { layer_id: [key for key in checkpoint if f'output_blocks.{layer_id}' in key] for layer_id in range(snake_case_ ) } for i in range(1 ,snake_case_ ): UpperCamelCase : List[Any] = (i - 1) // (config["""num_res_blocks"""] + 1) UpperCamelCase : str = (i - 1) % (config["""num_res_blocks"""] + 1) UpperCamelCase : Tuple = [key for key in input_blocks[i] if f'input_blocks.{i}.0' in key] UpperCamelCase : Dict = [key for key in input_blocks[i] if f'input_blocks.{i}.1' in key] if f'input_blocks.{i}.0.op.weight' in checkpoint: UpperCamelCase : Tuple = checkpoint[ f'input_blocks.{i}.0.op.weight' ] UpperCamelCase : Any = checkpoint[ f'input_blocks.{i}.0.op.bias' ] continue UpperCamelCase : Optional[Any] = renew_resnet_paths(snake_case_ ) UpperCamelCase : Dict = {"""old""": f'input_blocks.{i}.0', """new""": f'down_blocks.{block_id}.resnets.{layer_in_block_id}'} UpperCamelCase : int = {"""old""": """resnets.2.op""", """new""": """downsamplers.0.op"""} assign_to_checkpoint( snake_case_ ,snake_case_ ,snake_case_ ,additional_replacements=[meta_path, resnet_op] ,config=snake_case_ ) if len(snake_case_ ): UpperCamelCase : Optional[int] = renew_attention_paths(snake_case_ ) UpperCamelCase : Any = { """old""": f'input_blocks.{i}.1', """new""": f'down_blocks.{block_id}.attentions.{layer_in_block_id}', } UpperCamelCase : Dict = { f'input_blocks.{i}.1.qkv.bias': { """key""": f'down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias', """query""": f'down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias', """value""": f'down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias', }, f'input_blocks.{i}.1.qkv.weight': { """key""": f'down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight', """query""": f'down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight', """value""": f'down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight', }, } assign_to_checkpoint( snake_case_ ,snake_case_ ,snake_case_ ,additional_replacements=[meta_path] ,attention_paths_to_split=snake_case_ ,config=snake_case_ ,) UpperCamelCase : Optional[Any] = middle_blocks[0] UpperCamelCase : Optional[Any] = middle_blocks[1] UpperCamelCase : Any = middle_blocks[2] UpperCamelCase : List[str] = renew_resnet_paths(snake_case_ ) assign_to_checkpoint(snake_case_ ,snake_case_ ,snake_case_ ,config=snake_case_ ) UpperCamelCase : Union[str, Any] = renew_resnet_paths(snake_case_ ) assign_to_checkpoint(snake_case_ ,snake_case_ ,snake_case_ ,config=snake_case_ ) UpperCamelCase : Optional[Any] = renew_attention_paths(snake_case_ ) UpperCamelCase : int = { """middle_block.1.qkv.bias""": { """key""": """mid_block.attentions.0.key.bias""", """query""": """mid_block.attentions.0.query.bias""", """value""": """mid_block.attentions.0.value.bias""", }, """middle_block.1.qkv.weight""": { """key""": """mid_block.attentions.0.key.weight""", """query""": """mid_block.attentions.0.query.weight""", """value""": """mid_block.attentions.0.value.weight""", }, } assign_to_checkpoint( snake_case_ ,snake_case_ ,snake_case_ ,attention_paths_to_split=snake_case_ ,config=snake_case_ ) for i in range(snake_case_ ): UpperCamelCase : int = i // (config["""num_res_blocks"""] + 1) UpperCamelCase : Dict = i % (config["""num_res_blocks"""] + 1) UpperCamelCase : List[Any] = [shave_segments(snake_case_ ,2 ) for name in output_blocks[i]] UpperCamelCase : Optional[int] = {} for layer in output_block_layers: UpperCamelCase , UpperCamelCase : Dict = layer.split(""".""" )[0], shave_segments(snake_case_ ,1 ) if layer_id in output_block_list: output_block_list[layer_id].append(snake_case_ ) else: UpperCamelCase : Tuple = [layer_name] if len(snake_case_ ) > 1: UpperCamelCase : Optional[Any] = [key for key in output_blocks[i] if f'output_blocks.{i}.0' in key] UpperCamelCase : Optional[Any] = [key for key in output_blocks[i] if f'output_blocks.{i}.1' in key] UpperCamelCase : Optional[int] = renew_resnet_paths(snake_case_ ) UpperCamelCase : int = renew_resnet_paths(snake_case_ ) UpperCamelCase : List[str] = {"""old""": f'output_blocks.{i}.0', """new""": f'up_blocks.{block_id}.resnets.{layer_in_block_id}'} assign_to_checkpoint(snake_case_ ,snake_case_ ,snake_case_ ,additional_replacements=[meta_path] ,config=snake_case_ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): UpperCamelCase : Optional[Any] = list(output_block_list.values() ).index(["""conv.weight""", """conv.bias"""] ) UpperCamelCase : Optional[Any] = checkpoint[ f'output_blocks.{i}.{index}.conv.weight' ] UpperCamelCase : Optional[int] = checkpoint[ f'output_blocks.{i}.{index}.conv.bias' ] # Clear attentions as they have been attributed above. if len(snake_case_ ) == 2: UpperCamelCase : int = [] if len(snake_case_ ): UpperCamelCase : Any = renew_attention_paths(snake_case_ ) UpperCamelCase : Optional[Any] = { """old""": f'output_blocks.{i}.1', """new""": f'up_blocks.{block_id}.attentions.{layer_in_block_id}', } UpperCamelCase : Optional[Any] = { f'output_blocks.{i}.1.qkv.bias': { """key""": f'up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias', """query""": f'up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias', """value""": f'up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias', }, f'output_blocks.{i}.1.qkv.weight': { """key""": f'up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight', """query""": f'up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight', """value""": f'up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight', }, } assign_to_checkpoint( snake_case_ ,snake_case_ ,snake_case_ ,additional_replacements=[meta_path] ,attention_paths_to_split=to_split if any("""qkv""" in key for key in attentions ) else None ,config=snake_case_ ,) else: UpperCamelCase : Union[str, Any] = renew_resnet_paths(snake_case_ ,n_shave_prefix_segments=1 ) for path in resnet_0_paths: UpperCamelCase : Tuple = """.""".join(["""output_blocks""", str(snake_case_ ), path["""old"""]] ) UpperCamelCase : List[Any] = """.""".join(["""up_blocks""", str(snake_case_ ), """resnets""", str(snake_case_ ), path["""new"""]] ) UpperCamelCase : Union[str, Any] = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": __A : Optional[int] = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') __A : str = parser.parse_args() __A : int = torch.load(args.checkpoint_path) with open(args.config_file) as f: __A : str = json.loads(f.read()) __A : int = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] __A : int = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: __A : Optional[int] = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __A : str = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __A : List[str] = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
27
"""simple docstring""" import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring''' UpperCamelCase : List[str] = args.log_outputs UpperCamelCase : Tuple = """_""".join(args.dataset.split("""/""" ) + [args.config, args.split] ) # load metric UpperCamelCase : List[Any] = load_metric("""wer""" ) UpperCamelCase : Any = load_metric("""cer""" ) # compute metrics UpperCamelCase : str = wer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) UpperCamelCase : Dict = cer.compute(references=result["""target"""] ,predictions=result["""prediction"""] ) # print & log results UpperCamelCase : Optional[int] = f'WER: {wer_result}\nCER: {cer_result}' print(snake_case_ ) with open(f'{dataset_id}_eval_results.txt' ,"""w""" ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: UpperCamelCase : Optional[Any] = f'log_{dataset_id}_predictions.txt' UpperCamelCase : str = f'log_{dataset_id}_targets.txt' with open(snake_case_ ,"""w""" ) as p, open(snake_case_ ,"""w""" ) as t: # mapping function to write output def write_to_file(snake_case_ : Union[str, Any] ,snake_case_ : Tuple ): p.write(f'{i}' + """\n""" ) p.write(batch["""prediction"""] + """\n""" ) t.write(f'{i}' + """\n""" ) t.write(batch["""target"""] + """\n""" ) result.map(snake_case_ ,with_indices=snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Dict = """[,?.!\-\;\:\"“%‘”�—’…–]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training UpperCamelCase : str = re.sub(snake_case_ ,"""""" ,text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! UpperCamelCase : List[str] = ["""\n\n""", """\n""", """ """, """ """] for t in token_sequences_to_ignore: UpperCamelCase : Tuple = """ """.join(text.split(snake_case_ ) ) return text def A_ ( snake_case_ : str ): '''simple docstring''' # load dataset UpperCamelCase : Union[str, Any] = load_dataset(args.dataset ,args.config ,split=args.split ,use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor UpperCamelCase : List[Any] = AutoFeatureExtractor.from_pretrained(args.model_id ) UpperCamelCase : Dict = feature_extractor.sampling_rate # resample audio UpperCamelCase : Optional[Any] = dataset.cast_column("""audio""" ,Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: UpperCamelCase : int = 0 if torch.cuda.is_available() else -1 UpperCamelCase : Union[str, Any] = pipeline("""automatic-speech-recognition""" ,model=args.model_id ,device=args.device ) # map function to decode audio def map_to_pred(snake_case_ : Union[str, Any] ): UpperCamelCase : List[Any] = asr( batch["""audio"""]["""array"""] ,chunk_length_s=args.chunk_length_s ,stride_length_s=args.stride_length_s ) UpperCamelCase : Union[str, Any] = prediction["""text"""] UpperCamelCase : Optional[Any] = normalize_text(batch["""sentence"""] ) return batch # run inference on all examples UpperCamelCase : Any = dataset.map(snake_case_ ,remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_ ,snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) __A : Optional[Any] = parser.parse_args() main(args)
27
1
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class lowerCamelCase ( unittest.TestCase ): @property def a_ ( self ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def a_ ( self ): UpperCamelCase : int = ort.SessionOptions() UpperCamelCase : Any = False return options def a_ ( self ): UpperCamelCase : Union[str, Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) UpperCamelCase : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) UpperCamelCase : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default UpperCamelCase : List[Any] = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = """A red cat sitting on a park bench""" UpperCamelCase : List[Any] = np.random.RandomState(0 ) UpperCamelCase : Optional[int] = pipe( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , mask_image=SCREAMING_SNAKE_CASE_ , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=SCREAMING_SNAKE_CASE_ , output_type="""np""" , ) UpperCamelCase : Union[str, Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1e-2
27
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = 'EncodecFeatureExtractor' lowercase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.feature_extractor UpperCamelCase : Any = False def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True ): return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE_ , language=SCREAMING_SNAKE_CASE_ , no_timestamps=SCREAMING_SNAKE_CASE_ ) def __call__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs.pop("""sampling_rate""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Any = args[0] UpperCamelCase : str = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: UpperCamelCase : Optional[int] = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is not None: UpperCamelCase : str = self.feature_extractor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audio is None: return inputs elif text is None: return audio_inputs else: UpperCamelCase : int = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: UpperCamelCase : Optional[Any] = audio_inputs["""padding_mask"""] return inputs def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = kwargs.pop("""audio""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""padding_mask""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : Optional[int] = args[0] UpperCamelCase : Any = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE_ , padding_mask=SCREAMING_SNAKE_CASE_ ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Dict = to_numpy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase : int = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = to_numpy(SCREAMING_SNAKE_CASE_ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) UpperCamelCase : List[str] = seq_len - padding_mask.shape[-1] UpperCamelCase : Optional[int] = 1 - self.feature_extractor.padding_value UpperCamelCase : Any = np.pad(SCREAMING_SNAKE_CASE_ , ((0, 0), (0, difference)) , """constant""" , constant_values=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] UpperCamelCase : Optional[Any] = sliced_audio.reshape(SCREAMING_SNAKE_CASE_ , -1 ) return audio_values
27
1
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py __A : Tuple = '''src/diffusers''' # Matches is_xxx_available() __A : List[str] = re.compile(R'''is\_([a-z_]*)_available\(\)''') # Matches from xxx import bla __A : Union[str, Any] = re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') __A : List[str] = ''' {0} = None ''' __A : Dict = ''' class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) ''' __A : List[str] = ''' def {0}(*args, **kwargs): requires_backends({0}, {1}) ''' def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Any = _re_backend.findall(snake_case_ ) if len(snake_case_ ) == 0: return None return "_and_".join(snake_case_ ) def A_ ( ): '''simple docstring''' with open(os.path.join(snake_case_ ,"""__init__.py""" ) ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: UpperCamelCase : Tuple = f.readlines() # Get to the point we do the actual imports for type checking UpperCamelCase : Dict = 0 UpperCamelCase : Dict = {} # Go through the end of the file while line_index < len(snake_case_ ): # If the line contains is_backend_available, we grab all objects associated with the `else` block UpperCamelCase : Dict = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith("""else:""" ): line_index += 1 line_index += 1 UpperCamelCase : List[str] = [] # Until we unindent, add backend objects to the list while line_index < len(snake_case_ ) and len(lines[line_index] ) > 1: UpperCamelCase : List[Any] = lines[line_index] UpperCamelCase : Dict = _re_single_line_import.search(snake_case_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(snake_case_ ) > 0: UpperCamelCase : Dict = objects else: line_index += 1 return backend_specific_objects def A_ ( snake_case_ : Tuple ,snake_case_ : str ): '''simple docstring''' if name.isupper(): return DUMMY_CONSTANT.format(snake_case_ ) elif name.islower(): return DUMMY_FUNCTION.format(snake_case_ ,snake_case_ ) else: return DUMMY_CLASS.format(snake_case_ ,snake_case_ ) def A_ ( snake_case_ : Union[str, Any]=None ): '''simple docstring''' if backend_specific_objects is None: UpperCamelCase : Optional[Any] = read_init() # For special correspondence backend to module name as used in the function requires_modulename UpperCamelCase : str = {} for backend, objects in backend_specific_objects.items(): UpperCamelCase : Optional[int] = """[""" + """, """.join(f'"{b}"' for b in backend.split("""_and_""" ) ) + """]""" UpperCamelCase : Tuple = """# This file is autogenerated by the command `make fix-copies`, do not edit.\n""" dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(snake_case_ ,snake_case_ ) for o in objects] ) UpperCamelCase : str = dummy_file return dummy_files def A_ ( snake_case_ : Tuple=False ): '''simple docstring''' UpperCamelCase : int = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py UpperCamelCase : Any = {"""torch""": """pt"""} # Locate actual dummy modules and read their content. UpperCamelCase : Any = os.path.join(snake_case_ ,"""utils""" ) UpperCamelCase : str = { backend: os.path.join(snake_case_ ,f'dummy_{short_names.get(snake_case_ ,snake_case_ )}_objects.py' ) for backend in dummy_files.keys() } UpperCamelCase : Dict = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(snake_case_ ): with open(snake_case_ ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: UpperCamelCase : int = f.read() else: UpperCamelCase : str = """""" for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( f'Updating diffusers.utils.dummy_{short_names.get(snake_case_ ,snake_case_ )}_objects.py as the main ' """__init__ has new objects.""" ) with open(dummy_file_paths[backend] ,"""w""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: f.write(dummy_files[backend] ) else: raise ValueError( """The main __init__ has objects that are not present in """ f'diffusers.utils.dummy_{short_names.get(snake_case_ ,snake_case_ )}_objects.py. Run `make fix-copies` ' """to fix this.""" ) if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') __A : Tuple = parser.parse_args() check_dummies(args.fix_and_overwrite)
27
"""simple docstring""" import requests from bsa import BeautifulSoup def A_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus" ): '''simple docstring''' UpperCamelCase : Any = BeautifulSoup(requests.get(snake_case_ ).text ,"""html.parser""" ) UpperCamelCase : Optional[int] = soup.findAll("""h1""" ) UpperCamelCase : List[Any] = soup.findAll("""div""" ,{"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" ,{"""class""": """panel-title"""} ) values += soup.findAll("""div""" ,{"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(snake_case_ ,snake_case_ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
27
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Optional[int] = logging.get_logger(__name__) __A : Optional[int] = { '''google/mobilenet_v2_1.4_224''': '''https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json''', '''google/mobilenet_v2_1.0_224''': '''https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json''', '''google/mobilenet_v2_0.75_160''': '''https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json''', '''google/mobilenet_v2_0.35_96''': '''https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json''', # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[Any] = 'mobilenet_v2' def __init__( self , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=1.0 , 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_="relu6" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0.8 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.001 , SCREAMING_SNAKE_CASE_=255 , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) if depth_multiplier <= 0: raise ValueError("""depth_multiplier must be greater than zero.""" ) UpperCamelCase : Dict = num_channels UpperCamelCase : str = image_size UpperCamelCase : List[str] = depth_multiplier UpperCamelCase : Dict = depth_divisible_by UpperCamelCase : int = min_depth UpperCamelCase : Optional[int] = expand_ratio UpperCamelCase : Any = output_stride UpperCamelCase : Tuple = first_layer_is_expansion UpperCamelCase : Optional[Any] = finegrained_output UpperCamelCase : Dict = hidden_act UpperCamelCase : Dict = tf_padding UpperCamelCase : List[Any] = classifier_dropout_prob UpperCamelCase : str = initializer_range UpperCamelCase : Optional[int] = layer_norm_eps UpperCamelCase : Tuple = semantic_loss_ignore_index class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[Any] = version.parse('1.11' ) @property def a_ ( self ): return OrderedDict([("""pixel_values""", {0: """batch"""})] ) @property def a_ ( self ): if self.task == "image-classification": return OrderedDict([("""logits""", {0: """batch"""})] ) else: return OrderedDict([("""last_hidden_state""", {0: """batch"""}), ("""pooler_output""", {0: """batch"""})] ) @property def a_ ( self ): return 1e-4
27
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCamelCase ( _UpperCAmelCase ): 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_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Union[str, Any] = use_token_type_ids UpperCamelCase : Dict = use_labels UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : str = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : int = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Dict = num_labels UpperCamelCase : Tuple = num_choices UpperCamelCase : Optional[int] = scope UpperCamelCase : List[Any] = q_groups UpperCamelCase : Tuple = k_groups UpperCamelCase : Any = v_groups UpperCamelCase : List[str] = post_attention_groups UpperCamelCase : Tuple = intermediate_groups UpperCamelCase : int = output_groups def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = SqueezeBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = SqueezeBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = 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 a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = SqueezeBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : str = SqueezeBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = 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.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = SqueezeBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = config_and_inputs UpperCamelCase : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase : Dict = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : str = True lowercase : str = False def a_ ( self ): UpperCamelCase : Any = SqueezeBertModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = SqueezeBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) UpperCamelCase : Dict = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
1
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : str = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( """`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got """ f'{test_file} instead.' ) UpperCamelCase : List[Any] = components[-1] if not test_fn.endswith("""py""" ): raise ValueError(f'`test_file` should be a python file. Got {test_fn} instead.' ) if not test_fn.startswith("""test_modeling_""" ): raise ValueError( f'`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.' ) UpperCamelCase : Dict = components[:-1] + [test_fn.replace(""".py""" ,"""""" )] UpperCamelCase : List[str] = """.""".join(snake_case_ ) return test_module_path def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[Any] = get_module_path(snake_case_ ) UpperCamelCase : List[Any] = importlib.import_module(snake_case_ ) return test_module def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Optional[Any] = [] UpperCamelCase : Any = get_test_module(snake_case_ ) for attr in dir(snake_case_ ): if attr.endswith("""ModelTester""" ): tester_classes.append(getattr(snake_case_ ,snake_case_ ) ) # sort with class names return sorted(snake_case_ ,key=lambda snake_case_ : x.__name__ ) def A_ ( snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : Tuple = [] UpperCamelCase : Optional[int] = get_test_module(snake_case_ ) for attr in dir(snake_case_ ): UpperCamelCase : Optional[int] = getattr(snake_case_ ,snake_case_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). UpperCamelCase : int = getattr(snake_case_ ,"""all_model_classes""" ,[] ) if len(snake_case_ ) > 0: test_classes.append(snake_case_ ) # sort with class names return sorted(snake_case_ ,key=lambda snake_case_ : x.__name__ ) def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : str = get_test_classes(snake_case_ ) UpperCamelCase : Optional[Any] = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(snake_case_ ,key=lambda snake_case_ : x.__name__ ) def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : Optional[Any] = test_class() if hasattr(snake_case_ ,"""setUp""" ): test.setUp() UpperCamelCase : Tuple = None if hasattr(snake_case_ ,"""model_tester""" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: UpperCamelCase : int = test.model_tester.__class__ return model_tester def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : Dict = get_test_classes(snake_case_ ) UpperCamelCase : Optional[Any] = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(snake_case_ ) # sort with class names return sorted(snake_case_ ,key=lambda snake_case_ : x.__name__ ) def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : Optional[Any] = get_test_classes_for_model(snake_case_ ,snake_case_ ) UpperCamelCase : Optional[int] = [] for test_class in test_classes: UpperCamelCase : str = get_model_tester_from_test_class(snake_case_ ) if tester_class is not None: tester_classes.append(snake_case_ ) # sort with class names return sorted(snake_case_ ,key=lambda snake_case_ : x.__name__ ) def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Dict = get_test_classes(snake_case_ ) UpperCamelCase : Optional[int] = {test_class: get_model_tester_from_test_class(snake_case_ ) for test_class in test_classes} return test_tester_mapping def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : List[str] = get_model_classes(snake_case_ ) UpperCamelCase : Union[str, Any] = { model_class: get_test_classes_for_model(snake_case_ ,snake_case_ ) for model_class in model_classes } return model_test_mapping def A_ ( snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : List[Any] = get_model_classes(snake_case_ ) UpperCamelCase : List[Any] = { model_class: get_tester_classes_for_model(snake_case_ ,snake_case_ ) for model_class in model_classes } return model_to_tester_mapping def A_ ( snake_case_ : List[Any] ): '''simple docstring''' if isinstance(snake_case_ ,snake_case_ ): return o elif isinstance(snake_case_ ,snake_case_ ): return o.__name__ elif isinstance(snake_case_ ,(list, tuple) ): return [to_json(snake_case_ ) for x in o] elif isinstance(snake_case_ ,snake_case_ ): return {to_json(snake_case_ ): to_json(snake_case_ ) for k, v in o.items()} else: return o
27
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
1