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 argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __A : int = logging.get_logger(__name__) __A : Optional[int] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } __A : Optional[int] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Dict ,snake_case_ : Tuple ,snake_case_ : Optional[int] ,snake_case_ : List[Any] ): '''simple docstring''' for attribute in key.split(""".""" ): UpperCamelCase : str = getattr(snake_case_ ,snake_case_ ) if weight_type is not None: UpperCamelCase : Dict = getattr(snake_case_ ,snake_case_ ).shape else: UpperCamelCase : List[str] = hf_pointer.shape assert hf_shape == value.shape, ( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": UpperCamelCase : int = value elif weight_type == "weight_g": UpperCamelCase : str = value elif weight_type == "weight_v": UpperCamelCase : Union[str, Any] = value elif weight_type == "bias": UpperCamelCase : Union[str, Any] = value else: UpperCamelCase : int = value logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def A_ ( snake_case_ : List[str] ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : Optional[Any] = [] UpperCamelCase : str = fairseq_model.state_dict() UpperCamelCase : List[str] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight UpperCamelCase : str = None for name, value in fairseq_dict.items(): UpperCamelCase : Optional[Any] = False if "conv_layers" in name: load_conv_layer( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,hf_model.config.feat_extract_norm == """group""" ,) UpperCamelCase : List[str] = True elif name.split(""".""" )[0] == "proj": UpperCamelCase : Optional[Any] = fairseq_model.proj UpperCamelCase : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: UpperCamelCase : Optional[int] = True if "*" in mapped_key: UpperCamelCase : Optional[Any] = name.split(snake_case_ )[0].split(""".""" )[-2] UpperCamelCase : List[str] = mapped_key.replace("""*""" ,snake_case_ ) if "weight_g" in name: UpperCamelCase : str = """weight_g""" elif "weight_v" in name: UpperCamelCase : Optional[int] = """weight_v""" elif "bias" in name: UpperCamelCase : List[str] = """bias""" elif "weight" in name: UpperCamelCase : List[str] = """weight""" else: UpperCamelCase : int = None set_recursively(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f'Unused weights: {unused_weights}' ) return proj_weight def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Dict ,snake_case_ : List[str] ,snake_case_ : Any ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : List[str] = full_name.split("""conv_layers.""" )[-1] UpperCamelCase : int = name.split(""".""" ) UpperCamelCase : Any = int(items[0] ) UpperCamelCase : Union[str, Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) UpperCamelCase : List[Any] = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) UpperCamelCase : List[str] = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) UpperCamelCase : Optional[int] = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) UpperCamelCase : Tuple = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(snake_case_ ) def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase , UpperCamelCase : str = emb.weight.shape UpperCamelCase : Union[str, Any] = nn.Linear(snake_case_ ,snake_case_ ,bias=snake_case_ ) UpperCamelCase : List[str] = emb.weight.data return lin_layer def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' with open(snake_case_ ,"""r""" ,encoding="""utf-8""" ) as f: UpperCamelCase : int = f.readlines() UpperCamelCase : List[Any] = [line.split(""" """ )[0] for line in lines] UpperCamelCase : int = len(snake_case_ ) UpperCamelCase : List[str] = { """<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3, } vocab_dict.update(dict(zip(snake_case_ ,range(4 ,num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def A_ ( snake_case_ : Optional[Any] ,snake_case_ : List[str] ,snake_case_ : Tuple ,snake_case_ : Any ,snake_case_ : Any ,snake_case_ : Optional[Any] ,snake_case_ : Optional[Any] ,): '''simple docstring''' UpperCamelCase : List[Any] = WavaVecaConfig.from_pretrained(snake_case_ ) UpperCamelCase : Tuple = SpeechaTextaConfig.from_pretrained( snake_case_ ,vocab_size=snake_case_ ,decoder_layers=snake_case_ ,do_stable_layer_norm=snake_case_ ) UpperCamelCase : List[str] = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=1_6_0_0_0 ,padding_value=0 ,do_normalize=snake_case_ ,return_attention_mask=snake_case_ ,) UpperCamelCase , UpperCamelCase , UpperCamelCase : Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) UpperCamelCase : Any = model[0].eval() # set weights for wav2vec2 encoder UpperCamelCase : Optional[int] = WavaVecaModel(snake_case_ ) UpperCamelCase : List[str] = recursively_load_weights_wavaveca(model.encoder ,snake_case_ ) UpperCamelCase : List[Any] = SpeechaTextaForCausalLM(snake_case_ ) UpperCamelCase , UpperCamelCase : Tuple = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() ,strict=snake_case_ ) # set output linear layer unexpected_keys.remove("""embed_out""" ) UpperCamelCase : Any = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f'The following keys are missing when loading the decoder weights: {missing_keys}' ) logger.warning(f'The following keys are unexpected when loading the decoder weights: {unexpected_keys}' ) UpperCamelCase : Tuple = SpeechEncoderDecoderModel(encoder=snake_case_ ,decoder=snake_case_ ) UpperCamelCase : Dict = False # add projection layer UpperCamelCase : Optional[Any] = nn.Parameter(projection_layer.weight ) UpperCamelCase : int = nn.Parameter(projection_layer.bias ) UpperCamelCase : Optional[Any] = create_vocab_dict(snake_case_ ) with open(os.path.join(snake_case_ ,"""vocab.json""" ) ,"""w""" ) as fp: json.dump(snake_case_ ,snake_case_ ) UpperCamelCase : List[str] = SpeechaTextaTokenizer(os.path.join(snake_case_ ,"""vocab.json""" ) ) tokenizer.save_pretrained(snake_case_ ) UpperCamelCase : Dict = hf_wavavec.config.to_dict() UpperCamelCase : str = tokenizer.pad_token_id UpperCamelCase : List[str] = tokenizer.bos_token_id UpperCamelCase : List[Any] = tokenizer.eos_token_id UpperCamelCase : int = """speech_to_text_2""" UpperCamelCase : Any = """wav2vec2""" UpperCamelCase : str = SpeechEncoderDecoderConfig.from_dict(snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) feature_extractor.save_pretrained(snake_case_ ) if __name__ == "__main__": __A : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument( '''--encoder_config_path''', default='''facebook/wav2vec2-large-lv60''', type=str, help='''Path to hf encoder wav2vec2 checkpoint config''', ) parser.add_argument( '''--decoder_config_path''', default='''facebook/s2t-small-mustc-en-fr-st''', type=str, help='''Path to hf decoder s2t checkpoint config''', ) parser.add_argument('''--vocab_size''', default=10224, type=int, help='''Vocab size of decoder''') parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''') __A : List[str] = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
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 math import os import sys def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Union[str, Any] = """""" try: with open(snake_case_ ,"""rb""" ) as binary_file: UpperCamelCase : Any = binary_file.read() for dat in data: UpperCamelCase : int = f'{dat:08b}' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def A_ ( snake_case_ : dict[str, str] ,snake_case_ : str ,snake_case_ : int ,snake_case_ : str ): '''simple docstring''' lexicon.pop(snake_case_ ) UpperCamelCase : Union[str, Any] = last_match_id if math.loga(snake_case_ ).is_integer(): for curr_key in lexicon: UpperCamelCase : Any = """0""" + lexicon[curr_key] UpperCamelCase : int = bin(snake_case_ )[2:] def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : str = {"""0""": """0""", """1""": """1"""} UpperCamelCase , UpperCamelCase : Dict = """""", """""" UpperCamelCase : Optional[int] = len(snake_case_ ) for i in range(len(snake_case_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue UpperCamelCase : Tuple = lexicon[curr_string] result += last_match_id add_key_to_lexicon(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) index += 1 UpperCamelCase : Any = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": UpperCamelCase : Dict = lexicon[curr_string] result += last_match_id return result def A_ ( snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : str = os.path.getsize(snake_case_ ) UpperCamelCase : Union[str, Any] = bin(snake_case_ )[2:] UpperCamelCase : List[str] = len(snake_case_ ) return "0" * (length_length - 1) + file_length_binary + compressed def A_ ( snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : int = 8 try: with open(snake_case_ ,"""wb""" ) as opened_file: UpperCamelCase : Dict = [ to_write[i : i + byte_length] for i in range(0 ,len(snake_case_ ) ,snake_case_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(snake_case_ ,2 ).to_bytes(1 ,byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def A_ ( snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[str] = read_file_binary(snake_case_ ) UpperCamelCase : Optional[int] = compress_data(snake_case_ ) UpperCamelCase : Any = add_file_length(snake_case_ ,snake_case_ ) write_file_binary(snake_case_ ,snake_case_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
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""" def A_ ( snake_case_ : int ): '''simple docstring''' if n == 1 or not isinstance(snake_case_ ,snake_case_ ): return 0 elif n == 2: return 1 else: UpperCamelCase : Optional[Any] = [0, 1] for i in range(2 ,n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : Union[str, Any] = 0 UpperCamelCase : str = 2 while digits < n: index += 1 UpperCamelCase : Dict = len(str(fibonacci(snake_case_ ) ) ) return index def A_ ( snake_case_ : int = 1_0_0_0 ): '''simple docstring''' return fibonacci_digits_index(snake_case_ ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
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 unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer __A : int = ['''gpt2'''] __A : List[str] = '''gpt2''' if is_tf_available(): class lowerCamelCase ( tf.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ ): super().__init__() UpperCamelCase : List[str] = tokenizer UpperCamelCase : Union[str, Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = TFGPTaLMHeadModel.from_config(SCREAMING_SNAKE_CASE_ ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name="""text""" ),) ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = self.tokenizer(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = tokenized["""input_ids"""].to_tensor() UpperCamelCase : List[str] = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) UpperCamelCase : int = self.model(input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""logits"""] return outputs @require_tf @require_keras_nlp class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().setUp() UpperCamelCase : Union[str, Any] = [GPTaTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) for checkpoint in (TOKENIZER_CHECKPOINTS)] UpperCamelCase : Optional[Any] = [TFGPTaTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCamelCase : Dict = [ """This is a straightforward English test sentence.""", """This one has some weird characters\rto\nsee\r\nif those\u00E9break things.""", """Now we're going to add some Chinese: 一 二 三 一二三""", """And some much more rare Chinese: 齉 堃 齉堃""", """Je vais aussi écrire en français pour tester les accents""", """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""", ] UpperCamelCase : Dict = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def a_ ( self ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: UpperCamelCase : Dict = tokenizer([test_inputs] , return_tensors="""tf""" ) UpperCamelCase : Any = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors UpperCamelCase : List[Any] = python_outputs[key].numpy() UpperCamelCase : Dict = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(SCREAMING_SNAKE_CASE_ , tf.intaa ) == tf_outputs_values ) ) @slow def a_ ( self ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase : str = tf.function(SCREAMING_SNAKE_CASE_ ) for test_inputs in self.test_sentences: UpperCamelCase : int = tf.constant(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = compiled_tokenizer(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = tf_tokenizer(SCREAMING_SNAKE_CASE_ ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def a_ ( self ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase : Optional[Any] = ModelToSave(tokenizer=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = tf.convert_to_tensor([self.test_sentences[0]] ) UpperCamelCase : Union[str, Any] = model.serving(SCREAMING_SNAKE_CASE_ ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCamelCase : Any = Path(SCREAMING_SNAKE_CASE_ ) / """saved.model""" tf.saved_model.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , signatures={"""serving_default""": model.serving} ) UpperCamelCase : Optional[Any] = tf.saved_model.load(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = loaded_model.signatures["""serving_default"""](SCREAMING_SNAKE_CASE_ )["""output_0"""] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def a_ ( self ): for tf_tokenizer in self.tf_tokenizers: UpperCamelCase : int = tf.convert_to_tensor([self.test_sentences[0]] ) UpperCamelCase : int = tf_tokenizer(SCREAMING_SNAKE_CASE_ ) # Build model with some sample inputs UpperCamelCase : Tuple = tf_tokenizer.get_config() UpperCamelCase : Tuple = TFGPTaTokenizer.from_config(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model_from_config(SCREAMING_SNAKE_CASE_ ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def a_ ( self ): for tf_tokenizer in self.tf_tokenizers: # for the test to run UpperCamelCase : int = 12_3123 for max_length in [3, 5, 1024]: UpperCamelCase : Optional[int] = tf.convert_to_tensor([self.test_sentences[0]] ) UpperCamelCase : str = tf_tokenizer(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = out["""input_ids"""].numpy().shape[1] assert out_length == max_length
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 itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch __A : Optional[Any] = random.Random() def A_ ( snake_case_ : str ,snake_case_ : List[str]=1.0 ,snake_case_ : Any=None ,snake_case_ : Optional[Any]=None ): '''simple docstring''' if rng is None: UpperCamelCase : Any = global_rng UpperCamelCase : int = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class lowerCamelCase ( unittest.TestCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=400 , SCREAMING_SNAKE_CASE_=2000 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=1_6000 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=80 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="hann_window" , SCREAMING_SNAKE_CASE_=80 , SCREAMING_SNAKE_CASE_=7600 , SCREAMING_SNAKE_CASE_=1e-10 , SCREAMING_SNAKE_CASE_=True , ): UpperCamelCase : List[Any] = parent UpperCamelCase : Any = batch_size UpperCamelCase : List[Any] = min_seq_length UpperCamelCase : List[str] = max_seq_length UpperCamelCase : Union[str, Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase : Tuple = feature_size UpperCamelCase : int = padding_value UpperCamelCase : Dict = sampling_rate UpperCamelCase : Tuple = do_normalize UpperCamelCase : List[Any] = num_mel_bins UpperCamelCase : Dict = hop_length UpperCamelCase : Optional[Any] = win_length UpperCamelCase : Union[str, Any] = win_function UpperCamelCase : Optional[int] = fmin UpperCamelCase : str = fmax UpperCamelCase : Optional[int] = mel_floor UpperCamelCase : Any = return_attention_mask def a_ ( self ): return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def a_ ( self , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False ): def _flatten(SCREAMING_SNAKE_CASE_ ): return list(itertools.chain(*SCREAMING_SNAKE_CASE_ ) ) if equal_length: UpperCamelCase : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size UpperCamelCase : Any = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase : Tuple = [np.asarray(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] return speech_inputs def a_ ( self , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False ): if equal_length: UpperCamelCase : List[str] = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size UpperCamelCase : List[Any] = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase : Tuple = [np.asarray(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] return speech_inputs @require_torch class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : List[Any] = SpeechTaFeatureExtractor def a_ ( self ): UpperCamelCase : Optional[Any] = SpeechTaFeatureExtractionTester(self ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.all(np.mean(SCREAMING_SNAKE_CASE_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(SCREAMING_SNAKE_CASE_ , axis=0 ) - 1 ) < 1e-3 ) ) def a_ ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus UpperCamelCase : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : Optional[int] = [np.asarray(SCREAMING_SNAKE_CASE_ ) for speech_input in speech_inputs] # Test not batched input UpperCamelCase : Optional[Any] = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values UpperCamelCase : Dict = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) # Test batched UpperCamelCase : Optional[Any] = feat_extract(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values UpperCamelCase : Dict = feat_extract(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) def a_ ( self ): UpperCamelCase : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : List[Any] = ["""longest""", """max_length""", """do_not_pad"""] UpperCamelCase : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = feat_extract(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) UpperCamelCase : Dict = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def a_ ( self ): UpperCamelCase : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : Optional[Any] = range(800 , 1400 , 200 ) UpperCamelCase : Any = [floats_list((1, x) )[0] for x in lengths] UpperCamelCase : int = ["""longest""", """max_length""", """do_not_pad"""] UpperCamelCase : str = [None, 1600, None] for max_length, padding in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = feat_extract(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def a_ ( self ): UpperCamelCase : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : Union[str, Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : str = feat_extract( SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=1000 , padding="""max_length""" , return_tensors="""np""" ) UpperCamelCase : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def a_ ( self ): UpperCamelCase : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : int = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : str = feat_extract( SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=1000 , padding="""longest""" , return_tensors="""np""" ) UpperCamelCase : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) UpperCamelCase : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : Dict = feat_extract( SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=2000 , padding="""longest""" , return_tensors="""np""" ) UpperCamelCase : Any = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : Dict = np.random.rand(100 ).astype(np.floataa ) UpperCamelCase : Any = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase : Any = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) UpperCamelCase : int = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def a_ ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus UpperCamelCase : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase : Tuple = [np.asarray(SCREAMING_SNAKE_CASE_ ) for speech_input in speech_inputs] # Test feature size UpperCamelCase : Optional[Any] = feature_extractor(audio_target=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input UpperCamelCase : List[str] = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_values UpperCamelCase : List[str] = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) # Test batched UpperCamelCase : int = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values UpperCamelCase : Tuple = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase : Optional[Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCamelCase : int = np.asarray(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values UpperCamelCase : List[str] = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) def a_ ( self ): UpperCamelCase : Dict = self.feat_extract_tester.prepare_inputs_for_target() UpperCamelCase : Any = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase : List[str] = feat_extract.model_input_names[0] UpperCamelCase : Optional[int] = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(SCREAMING_SNAKE_CASE_ ) == len(SCREAMING_SNAKE_CASE_ ) for x, y in zip(SCREAMING_SNAKE_CASE_ , processed_features[input_name] ) ) ) UpperCamelCase : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = BatchFeature({input_name: speech_inputs} , tensor_type="""np""" ) UpperCamelCase : str = processed_features[input_name] if len(batch_features_input.shape ) < 3: UpperCamelCase : Union[str, Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def a_ ( self ): UpperCamelCase : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase : List[Any] = feat_extract.model_input_names[0] UpperCamelCase : Any = BatchFeature({input_name: speech_inputs} , tensor_type="""pt""" ) UpperCamelCase : Dict = processed_features[input_name] if len(batch_features_input.shape ) < 3: UpperCamelCase : str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def a_ ( self ): UpperCamelCase : Any = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase : int = self.feat_extract_tester.prepare_inputs_for_target() UpperCamelCase : str = feat_extract.model_input_names[0] UpperCamelCase : str = BatchFeature({input_name: speech_inputs} ) UpperCamelCase : Optional[int] = feat_extract.num_mel_bins # hack! UpperCamelCase : int = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding="""longest""" , return_tensors="""np""" )[input_name] UpperCamelCase : Dict = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding="""longest""" , return_tensors="""pt""" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def a_ ( self ): UpperCamelCase : List[Any] = self.feat_extract_dict UpperCamelCase : List[Any] = True UpperCamelCase : Optional[Any] = self.feature_extraction_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() UpperCamelCase : str = [len(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] UpperCamelCase : str = feat_extract.model_input_names[0] UpperCamelCase : List[Any] = BatchFeature({input_name: speech_inputs} ) UpperCamelCase : Tuple = feat_extract.num_mel_bins # hack! UpperCamelCase : Optional[int] = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding="""longest""" , return_tensors="""np""" ) self.assertIn("""attention_mask""" , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.feat_extract_dict UpperCamelCase : Union[str, Any] = True UpperCamelCase : List[str] = self.feature_extraction_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = self.feat_extract_tester.prepare_inputs_for_target() UpperCamelCase : Any = [len(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] UpperCamelCase : int = feat_extract.model_input_names[0] UpperCamelCase : Any = BatchFeature({input_name: speech_inputs} ) UpperCamelCase : str = min(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = feat_extract.num_mel_bins # hack! UpperCamelCase : Optional[Any] = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) self.assertIn("""attention_mask""" , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): from datasets import load_dataset UpperCamelCase : List[str] = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech UpperCamelCase : Union[str, Any] = ds.sort("""id""" ).select(range(SCREAMING_SNAKE_CASE_ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def a_ ( self ): # fmt: off UpperCamelCase : int = torch.tensor( [2.3804e-03, 2.0752e-03, 1.9836e-03, 2.1057e-03, 1.6174e-03, 3.0518e-04, 9.1553e-05, 3.3569e-04, 9.7656e-04, 1.8311e-03, 2.0142e-03, 2.1057e-03, 1.7395e-03, 4.5776e-04, -3.9673e-04, 4.5776e-04, 1.0071e-03, 9.1553e-05, 4.8828e-04, 1.1597e-03, 7.3242e-04, 9.4604e-04, 1.8005e-03, 1.8311e-03, 8.8501e-04, 4.2725e-04, 4.8828e-04, 7.3242e-04, 1.0986e-03, 2.1057e-03] ) # fmt: on UpperCamelCase : List[Any] = self._load_datasamples(1 ) UpperCamelCase : int = SpeechTaFeatureExtractor() UpperCamelCase : str = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , SCREAMING_SNAKE_CASE_ , atol=1e-6 ) ) def a_ ( self ): # fmt: off UpperCamelCase : Dict = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on UpperCamelCase : Tuple = self._load_datasamples(1 ) UpperCamelCase : Optional[Any] = SpeechTaFeatureExtractor() UpperCamelCase : Optional[int] = feature_extractor(audio_target=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
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""" __A : Dict = { '''A''': '''.-''', '''B''': '''-...''', '''C''': '''-.-.''', '''D''': '''-..''', '''E''': '''.''', '''F''': '''..-.''', '''G''': '''--.''', '''H''': '''....''', '''I''': '''..''', '''J''': '''.---''', '''K''': '''-.-''', '''L''': '''.-..''', '''M''': '''--''', '''N''': '''-.''', '''O''': '''---''', '''P''': '''.--.''', '''Q''': '''--.-''', '''R''': '''.-.''', '''S''': '''...''', '''T''': '''-''', '''U''': '''..-''', '''V''': '''...-''', '''W''': '''.--''', '''X''': '''-..-''', '''Y''': '''-.--''', '''Z''': '''--..''', '''1''': '''.----''', '''2''': '''..---''', '''3''': '''...--''', '''4''': '''....-''', '''5''': '''.....''', '''6''': '''-....''', '''7''': '''--...''', '''8''': '''---..''', '''9''': '''----.''', '''0''': '''-----''', '''&''': '''.-...''', '''@''': '''.--.-.''', ''':''': '''---...''', ''',''': '''--..--''', '''.''': '''.-.-.-''', '''\'''': '''.----.''', '''"''': '''.-..-.''', '''?''': '''..--..''', '''/''': '''-..-.''', '''=''': '''-...-''', '''+''': '''.-.-.''', '''-''': '''-....-''', '''(''': '''-.--.''', ''')''': '''-.--.-''', '''!''': '''-.-.--''', ''' ''': '''/''' } # Exclamation mark is not in ITU-R recommendation # fmt: on __A : List[Any] = {value: key for key, value in MORSE_CODE_DICT.items()} def A_ ( snake_case_ : str ): '''simple docstring''' return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def A_ ( snake_case_ : str ): '''simple docstring''' return "".join(REVERSE_DICT[char] for char in message.split() ) def A_ ( ): '''simple docstring''' UpperCamelCase : List[str] = """Morse code here!""" print(snake_case_ ) UpperCamelCase : List[str] = encrypt(snake_case_ ) print(snake_case_ ) UpperCamelCase : Optional[Any] = decrypt(snake_case_ ) print(snake_case_ ) if __name__ == "__main__": main()
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 gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __A : Union[str, Any] = 16 __A : List[Any] = 32 def A_ ( snake_case_ : List[Any] ): '''simple docstring''' return int(x / 2**2_0 ) class lowerCamelCase : def __enter__( self ): gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero UpperCamelCase : Tuple = torch.cuda.memory_allocated() return self def __exit__( self , *SCREAMING_SNAKE_CASE_ ): gc.collect() torch.cuda.empty_cache() UpperCamelCase : Optional[int] = torch.cuda.memory_allocated() UpperCamelCase : List[Any] = torch.cuda.max_memory_allocated() UpperCamelCase : Any = bamb(self.end - self.begin ) UpperCamelCase : Optional[int] = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def A_ ( snake_case_ : Accelerator ,snake_case_ : int = 1_6 ,snake_case_ : str = "bert-base-cased" ,snake_case_ : int = 3_2_0 ,snake_case_ : int = 1_6_0 ,): '''simple docstring''' UpperCamelCase : Optional[int] = AutoTokenizer.from_pretrained(snake_case_ ) UpperCamelCase : Tuple = load_dataset( """glue""" ,"""mrpc""" ,split={"""train""": f'train[:{n_train}]', """validation""": f'validation[:{n_val}]'} ) def tokenize_function(snake_case_ : Dict ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : 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 UpperCamelCase : int = datasets.map( snake_case_ ,batched=snake_case_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,load_from_cache_file=snake_case_ ) # 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_ : int ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(snake_case_ ,padding="""max_length""" ,max_length=1_2_8 ,return_tensors="""pt""" ) return tokenizer.pad(snake_case_ ,padding="""longest""" ,return_tensors="""pt""" ) # Instantiate dataloaders. UpperCamelCase : Any = DataLoader( tokenized_datasets["""train"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) UpperCamelCase : int = DataLoader( tokenized_datasets["""validation"""] ,shuffle=snake_case_ ,collate_fn=snake_case_ ,batch_size=snake_case_ ) return train_dataloader, eval_dataloader def A_ ( snake_case_ : int ,snake_case_ : Any ): '''simple docstring''' # Initialize accelerator UpperCamelCase : Tuple = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : Optional[int] = config["""lr"""] UpperCamelCase : int = int(config["""num_epochs"""] ) UpperCamelCase : Optional[Any] = int(config["""seed"""] ) UpperCamelCase : str = int(config["""batch_size"""] ) UpperCamelCase : str = args.model_name_or_path set_seed(snake_case_ ) UpperCamelCase , UpperCamelCase : str = get_dataloaders(snake_case_ ,snake_case_ ,snake_case_ ,args.n_train ,args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(snake_case_ ,return_dict=snake_case_ ) # Instantiate optimizer UpperCamelCase : List[Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase : List[Any] = optimizer_cls(params=model.parameters() ,lr=snake_case_ ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase : Tuple = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCamelCase : Any = 1 UpperCamelCase : Union[str, Any] = (len(snake_case_ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase : Union[str, Any] = get_linear_schedule_with_warmup( optimizer=snake_case_ ,num_warmup_steps=0 ,num_training_steps=snake_case_ ,) else: UpperCamelCase : Tuple = DummyScheduler(snake_case_ ,total_num_steps=snake_case_ ,warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : List[Any] = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # We need to keep track of how many total steps we have iterated over UpperCamelCase : Optional[Any] = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase : Dict = 0 # Now we train the model UpperCamelCase : List[str] = {} for epoch in range(snake_case_ ,snake_case_ ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(snake_case_ ): UpperCamelCase : Optional[Any] = model(**snake_case_ ) UpperCamelCase : Dict = outputs.loss UpperCamelCase : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(snake_case_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print("""Memory before entering the train : {}""".format(bamb(tracemalloc.begin ) ) ) accelerator.print("""Memory consumed at the end of the train (end-begin): {}""".format(tracemalloc.used ) ) accelerator.print("""Peak Memory consumed during the train (max-begin): {}""".format(tracemalloc.peaked ) ) accelerator.print( """Total Peak Memory consumed during the train (max): {}""".format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) UpperCamelCase : int = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[f'epoch-{epoch}'] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir ,"""peak_memory_utilization.json""" ) ,"""w""" ) as f: json.dump(snake_case_ ,snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : int = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" ,type=snake_case_ ,default="""bert-base-cased""" ,help="""Path to pretrained model or model identifier from huggingface.co/models.""" ,required=snake_case_ ,) parser.add_argument( """--output_dir""" ,type=snake_case_ ,default=""".""" ,help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" ,) parser.add_argument( """--peak_memory_upper_bound""" ,type=snake_case_ ,default=snake_case_ ,help="""The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.""" ,) parser.add_argument( """--n_train""" ,type=snake_case_ ,default=3_2_0 ,help="""Number of training examples to use.""" ,) parser.add_argument( """--n_val""" ,type=snake_case_ ,default=1_6_0 ,help="""Number of validation examples to use.""" ,) parser.add_argument( """--num_epochs""" ,type=snake_case_ ,default=1 ,help="""Number of train epochs.""" ,) UpperCamelCase : List[str] = parser.parse_args() UpperCamelCase : str = {"""lr""": 2e-5, """num_epochs""": args.num_epochs, """seed""": 4_2, """batch_size""": 1_6} training_function(snake_case_ ,snake_case_ ) 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 argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip __A : List[str] = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def A_ ( snake_case_ : str ): '''simple docstring''' if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Any ,snake_case_ : List[str] ): '''simple docstring''' return max(metric_fn(snake_case_ ,snake_case_ ) for gt in ground_truths ) def A_ ( snake_case_ : int ,snake_case_ : Tuple ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : List[Any] = [line.strip() for line in open(snake_case_ ,"""r""" ).readlines()] UpperCamelCase : Dict = [] if args.gold_data_mode == "qa": UpperCamelCase : Dict = pd.read_csv(snake_case_ ,sep="""\t""" ,header=snake_case_ ) for answer_list in data[1]: UpperCamelCase : Dict = ast.literal_eval(snake_case_ ) answers.append(snake_case_ ) else: UpperCamelCase : Optional[int] = [line.strip() for line in open(snake_case_ ,"""r""" ).readlines()] UpperCamelCase : Dict = [[reference] for reference in references] UpperCamelCase : Dict = 0 for prediction, ground_truths in zip(snake_case_ ,snake_case_ ): total += 1 em += metric_max_over_ground_truths(snake_case_ ,snake_case_ ,snake_case_ ) fa += metric_max_over_ground_truths(snake_case_ ,snake_case_ ,snake_case_ ) UpperCamelCase : Optional[Any] = 100.0 * em / total UpperCamelCase : str = 100.0 * fa / total logger.info(f'F1: {fa:.2f}' ) logger.info(f'EM: {em:.2f}' ) def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : str ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Any = args.k UpperCamelCase : int = [line.strip() for line in open(snake_case_ ,"""r""" ).readlines()] UpperCamelCase : Dict = [line.strip() for line in open(snake_case_ ,"""r""" ).readlines()] UpperCamelCase : int = 0 for hypo, reference in zip(snake_case_ ,snake_case_ ): UpperCamelCase : int = set(hypo.split("""\t""" )[:k] ) UpperCamelCase : Optional[Any] = set(reference.split("""\t""" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k UpperCamelCase : Any = 100.0 * em / total logger.info(f'Precision@{k}: {em: .2f}' ) def A_ ( snake_case_ : Optional[int] ,snake_case_ : Optional[Any] ,snake_case_ : Union[str, Any] ): '''simple docstring''' def strip_title(snake_case_ : Optional[Any] ): if title.startswith("""\"""" ): UpperCamelCase : Optional[int] = title[1:] if title.endswith("""\"""" ): UpperCamelCase : List[str] = title[:-1] return title UpperCamelCase : str = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( snake_case_ ,return_tensors="""pt""" ,padding=snake_case_ ,truncation=snake_case_ ,)["""input_ids"""].to(args.device ) UpperCamelCase : int = rag_model.rag.question_encoder(snake_case_ ) UpperCamelCase : Optional[Any] = question_enc_outputs[0] UpperCamelCase : Union[str, Any] = rag_model.retriever( snake_case_ ,question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() ,prefix=rag_model.rag.generator.config.prefix ,n_docs=rag_model.config.n_docs ,return_tensors="""pt""" ,) UpperCamelCase : Optional[Any] = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) UpperCamelCase : Dict = [] for docs in all_docs: UpperCamelCase : Tuple = [strip_title(snake_case_ ) for title in docs["""title"""]] provenance_strings.append("""\t""".join(snake_case_ ) ) return provenance_strings def A_ ( snake_case_ : Dict ,snake_case_ : Union[str, Any] ,snake_case_ : Optional[int] ): '''simple docstring''' with torch.no_grad(): UpperCamelCase : str = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( snake_case_ ,return_tensors="""pt""" ,padding=snake_case_ ,truncation=snake_case_ ) UpperCamelCase : Union[str, Any] = inputs_dict.input_ids.to(args.device ) UpperCamelCase : int = inputs_dict.attention_mask.to(args.device ) UpperCamelCase : Dict = rag_model.generate( # rag_model overwrites generate snake_case_ ,attention_mask=snake_case_ ,num_beams=args.num_beams ,min_length=args.min_length ,max_length=args.max_length ,early_stopping=snake_case_ ,num_return_sequences=1 ,bad_words_ids=[[0, 0]] ,) UpperCamelCase : List[Any] = rag_model.retriever.generator_tokenizer.batch_decode(snake_case_ ,skip_special_tokens=snake_case_ ) if args.print_predictions: for q, a in zip(snake_case_ ,snake_case_ ): logger.info("""Q: {} - A: {}""".format(snake_case_ ,snake_case_ ) ) return answers def A_ ( ): '''simple docstring''' UpperCamelCase : List[str] = argparse.ArgumentParser() parser.add_argument( """--model_type""" ,choices=["""rag_sequence""", """rag_token""", """bart"""] ,type=snake_case_ ,help=( """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the""" """ model_name_or_path""" ) ,) parser.add_argument( """--index_name""" ,default=snake_case_ ,choices=["""exact""", """compressed""", """legacy"""] ,type=snake_case_ ,help="""RAG model retriever type""" ,) parser.add_argument( """--index_path""" ,default=snake_case_ ,type=snake_case_ ,help="""Path to the retrieval index""" ,) parser.add_argument("""--n_docs""" ,default=5 ,type=snake_case_ ,help="""Number of retrieved docs""" ) parser.add_argument( """--model_name_or_path""" ,default=snake_case_ ,type=snake_case_ ,required=snake_case_ ,help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" ,) parser.add_argument( """--eval_mode""" ,choices=["""e2e""", """retrieval"""] ,default="""e2e""" ,type=snake_case_ ,help=( """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates""" """ precision@k.""" ) ,) parser.add_argument("""--k""" ,default=1 ,type=snake_case_ ,help="""k for the precision@k calculation""" ) parser.add_argument( """--evaluation_set""" ,default=snake_case_ ,type=snake_case_ ,required=snake_case_ ,help="""Path to a file containing evaluation samples""" ,) parser.add_argument( """--gold_data_path""" ,default=snake_case_ ,type=snake_case_ ,required=snake_case_ ,help="""Path to a tab-separated file with gold samples""" ,) parser.add_argument( """--gold_data_mode""" ,default="""qa""" ,type=snake_case_ ,choices=["""qa""", """ans"""] ,help=( """Format of the gold data file""" """qa - a single line in the following format: question [tab] answer_list""" """ans - a single line of the gold file contains the expected answer string""" ) ,) parser.add_argument( """--predictions_path""" ,type=snake_case_ ,default="""predictions.txt""" ,help="""Name of the predictions file, to be stored in the checkpoints directory""" ,) parser.add_argument( """--eval_all_checkpoints""" ,action="""store_true""" ,help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" ,) parser.add_argument( """--eval_batch_size""" ,default=8 ,type=snake_case_ ,help="""Batch size per GPU/CPU for evaluation.""" ,) parser.add_argument( """--recalculate""" ,help="""Recalculate predictions even if the prediction file exists""" ,action="""store_true""" ,) parser.add_argument( """--num_beams""" ,default=4 ,type=snake_case_ ,help="""Number of beams to be used when generating answers""" ,) parser.add_argument("""--min_length""" ,default=1 ,type=snake_case_ ,help="""Min length of the generated answers""" ) parser.add_argument("""--max_length""" ,default=5_0 ,type=snake_case_ ,help="""Max length of the generated answers""" ) parser.add_argument( """--print_predictions""" ,action="""store_true""" ,help="""If True, prints predictions while evaluating.""" ,) parser.add_argument( """--print_docs""" ,action="""store_true""" ,help="""If True, prints docs retried while generating.""" ,) UpperCamelCase : str = parser.parse_args() UpperCamelCase : Any = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) return args def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : int = {} if args.model_type is None: UpperCamelCase : int = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("""rag""" ): UpperCamelCase : Any = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration UpperCamelCase : Tuple = args.n_docs if args.index_name is not None: UpperCamelCase : Optional[int] = args.index_name if args.index_path is not None: UpperCamelCase : List[Any] = args.index_path else: UpperCamelCase : List[Any] = BartForConditionalGeneration UpperCamelCase : Any = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("""Evaluate the following checkpoints: %s""" ,snake_case_ ) UpperCamelCase : str = get_scores if args.eval_mode == """e2e""" else get_precision_at_k UpperCamelCase : Optional[int] = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) ) score_fn(snake_case_ ,args.predictions_path ,args.gold_data_path ) continue logger.info("""***** Running evaluation for {} *****""".format(snake_case_ ) ) logger.info(""" Batch size = %d""" ,args.eval_batch_size ) logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) ) if args.model_type.startswith("""rag""" ): UpperCamelCase : List[Any] = RagRetriever.from_pretrained(snake_case_ ,**snake_case_ ) UpperCamelCase : str = model_class.from_pretrained(snake_case_ ,retriever=snake_case_ ,**snake_case_ ) model.retriever.init_retrieval() else: UpperCamelCase : List[Any] = model_class.from_pretrained(snake_case_ ,**snake_case_ ) model.to(args.device ) with open(args.evaluation_set ,"""r""" ) as eval_file, open(args.predictions_path ,"""w""" ) as preds_file: UpperCamelCase : Union[str, Any] = [] for line in tqdm(snake_case_ ): questions.append(line.strip() ) if len(snake_case_ ) == args.eval_batch_size: UpperCamelCase : Optional[int] = evaluate_batch_fn(snake_case_ ,snake_case_ ,snake_case_ ) preds_file.write("""\n""".join(snake_case_ ) + """\n""" ) preds_file.flush() UpperCamelCase : Any = [] if len(snake_case_ ) > 0: UpperCamelCase : List[Any] = evaluate_batch_fn(snake_case_ ,snake_case_ ,snake_case_ ) preds_file.write("""\n""".join(snake_case_ ) ) preds_file.flush() score_fn(snake_case_ ,args.predictions_path ,args.gold_data_path ) if __name__ == "__main__": __A : Tuple = get_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 typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : str = { '''configuration_autoformer''': [ '''AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''AutoformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ '''AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''AutoformerForPrediction''', '''AutoformerModel''', '''AutoformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
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""" __A : dict[tuple[int, int, int], int] = {} def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : int ): '''simple docstring''' # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on UpperCamelCase : str = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one UpperCamelCase : Dict = _calculate(days - 1 ,snake_case_ ,late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 UpperCamelCase : Dict = _calculate(days - 1 ,absent + 1 ,0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter UpperCamelCase : Any = _calculate(days - 1 ,snake_case_ ,0 ) UpperCamelCase : str = state_late + state_absent + state_ontime UpperCamelCase : int = prizestrings return prizestrings def A_ ( snake_case_ : int = 3_0 ): '''simple docstring''' return _calculate(snake_case_ ,absent=0 ,late=0 ) if __name__ == "__main__": print(solution())
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_ : Optional[Any] ,snake_case_ : List[Any] ,snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ): '''simple docstring''' global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: UpperCamelCase : str = mf_knapsack(i - 1 ,snake_case_ ,snake_case_ ,snake_case_ ) else: UpperCamelCase : Union[str, Any] = max( mf_knapsack(i - 1 ,snake_case_ ,snake_case_ ,snake_case_ ) ,mf_knapsack(i - 1 ,snake_case_ ,snake_case_ ,j - wt[i - 1] ) + val[i - 1] ,) UpperCamelCase : List[str] = val return f[i][j] def A_ ( snake_case_ : Any ,snake_case_ : List[Any] ,snake_case_ : Dict ,snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : Optional[Any] = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1 ,n + 1 ): for w_ in range(1 ,w + 1 ): if wt[i - 1] <= w_: UpperCamelCase : List[Any] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] ,dp[i - 1][w_] ) else: UpperCamelCase : Dict = dp[i - 1][w_] return dp[n][w_], dp def A_ ( snake_case_ : int ,snake_case_ : list ,snake_case_ : list ): '''simple docstring''' if not (isinstance(snake_case_ ,(list, tuple) ) and isinstance(snake_case_ ,(list, tuple) )): raise ValueError( """Both the weights and values vectors must be either lists or tuples""" ) UpperCamelCase : int = len(snake_case_ ) if num_items != len(snake_case_ ): UpperCamelCase : Any = ( """The number of weights must be the same as the number of values.\n""" f'But got {num_items} weights and {len(snake_case_ )} values' ) raise ValueError(snake_case_ ) for i in range(snake_case_ ): if not isinstance(wt[i] ,snake_case_ ): UpperCamelCase : List[Any] = ( """All weights must be integers but got weight of """ f'type {type(wt[i] )} at index {i}' ) raise TypeError(snake_case_ ) UpperCamelCase , UpperCamelCase : Union[str, Any] = knapsack(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) UpperCamelCase : set = set() _construct_solution(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) return optimal_val, example_optional_set def A_ ( snake_case_ : list ,snake_case_ : list ,snake_case_ : int ,snake_case_ : int ,snake_case_ : set ): '''simple docstring''' # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(snake_case_ ,snake_case_ ,i - 1 ,snake_case_ ,snake_case_ ) else: optimal_set.add(snake_case_ ) _construct_solution(snake_case_ ,snake_case_ ,i - 1 ,j - wt[i - 1] ,snake_case_ ) if __name__ == "__main__": __A : str = [3, 2, 4, 4] __A : Optional[int] = [4, 3, 2, 3] __A : Any = 4 __A : List[str] = 6 __A : Dict = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] __A , __A : Any = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 __A , __A : List[str] = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print('''optimal_value = ''', optimal_solution) print('''An optimal subset corresponding to the optimal value''', optimal_subset)
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""" def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : str = (1 + 2_4 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def A_ ( snake_case_ : int = 5_0_0_0 ): '''simple docstring''' UpperCamelCase : int = [(i * (3 * i - 1)) // 2 for i in range(1 ,snake_case_ )] for i, pentagonal_i in enumerate(snake_case_ ): for j in range(snake_case_ ,len(snake_case_ ) ): UpperCamelCase : Union[str, Any] = pentagonal_nums[j] UpperCamelCase : Dict = pentagonal_i + pentagonal_j UpperCamelCase : List[Any] = pentagonal_j - pentagonal_i if is_pentagonal(snake_case_ ) and is_pentagonal(snake_case_ ): return b return -1 if __name__ == "__main__": print(F'''{solution() = }''')
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 gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = KandinskyVaaControlnetImgaImgPipeline lowercase : int = ['image_embeds', 'negative_image_embeds', 'image', 'hint'] lowercase : Any = ['image_embeds', 'negative_image_embeds', 'image', 'hint'] lowercase : int = [ 'generator', 'height', 'width', 'strength', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] lowercase : List[Any] = 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 ): torch.manual_seed(0 ) UpperCamelCase : Tuple = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } UpperCamelCase : Optional[Any] = UNetaDConditionModel(**SCREAMING_SNAKE_CASE_ ) return model @property def a_ ( self ): return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "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", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : str = VQModel(**self.dummy_movq_kwargs ) return model def a_ ( self ): UpperCamelCase : Tuple = self.dummy_unet UpperCamelCase : Optional[int] = 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 : str = DDIMScheduler(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : Optional[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( SCREAMING_SNAKE_CASE_ ) # create init_image UpperCamelCase : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : List[str] = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_ ) ).convert("""RGB""" ).resize((256, 256) ) # create hint UpperCamelCase : List[str] = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Optional[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = { """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """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 : Dict = """cpu""" UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Optional[Any] = 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 : int = output.images UpperCamelCase : Dict = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) , return_dict=SCREAMING_SNAKE_CASE_ , )[0] UpperCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] UpperCamelCase : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCamelCase : Tuple = np.array( [0.54985034, 0.55509365, 0.52561504, 0.5570494, 0.5593818, 0.5263979, 0.50285643, 0.5069846, 0.51196736] ) 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 : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy""" ) UpperCamelCase : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) UpperCamelCase : List[Any] = init_image.resize((512, 512) ) UpperCamelCase : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) UpperCamelCase : int = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE_ ) ).float() / 255.0 UpperCamelCase : List[str] = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) UpperCamelCase : Any = """A robot, 4k photo""" UpperCamelCase : List[str] = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) UpperCamelCase : int = pipeline.to(SCREAMING_SNAKE_CASE_ ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCamelCase , UpperCamelCase : str = pipe_prior( SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , strength=0.85 , generator=SCREAMING_SNAKE_CASE_ , negative_prompt="""""" , ).to_tuple() UpperCamelCase : Tuple = pipeline( image=SCREAMING_SNAKE_CASE_ , image_embeds=SCREAMING_SNAKE_CASE_ , negative_image_embeds=SCREAMING_SNAKE_CASE_ , hint=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=100 , height=512 , width=512 , strength=0.5 , output_type="""np""" , ) UpperCamelCase : Any = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
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 __future__ import annotations from typing import Any def A_ ( snake_case_ : list ): '''simple docstring''' if not postfix_notation: return 0 UpperCamelCase : Dict = {"""+""", """-""", """*""", """/"""} UpperCamelCase : list[Any] = [] for token in postfix_notation: if token in operations: UpperCamelCase , UpperCamelCase : Optional[int] = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(snake_case_ ) ) return stack.pop() 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 collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def A_ ( ): '''simple docstring''' UpperCamelCase , UpperCamelCase : Dict = 9, 1_4 # noqa: F841 UpperCamelCase : Union[str, Any] = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 1_4], [3, 4, 9], [5, 4, 1_0], [1, 7, 1_1], ] UpperCamelCase : List[Any] = defaultdict(snake_case_ ) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost] ) adjancency[nodea].append([nodea, cost] ) UpperCamelCase : Tuple = mst(snake_case_ ) UpperCamelCase : Tuple = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: UpperCamelCase : Any = tuple(answer[:2] ) UpperCamelCase : Optional[int] = tuple(edge[::-1] ) assert edge in result or reverse in result
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 numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": __A : Optional[Any] = pd.read_csv('''sample_data.csv''', header=None) __A : List[Any] = df.shape[:1][0] # If you're using some other dataset input the target column __A : Dict = df.iloc[:, 1:2] __A : List[str] = actual_data.values.reshape(len_data, 1) __A : List[str] = MinMaxScaler().fit_transform(actual_data) __A : List[str] = 10 __A : Optional[int] = 5 __A : Optional[int] = 20 __A : Optional[Any] = len_data - periods * look_back __A : int = actual_data[:division] __A : int = actual_data[division - look_back :] __A , __A : Dict = [], [] __A , __A : Tuple = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) __A : List[Any] = np.array(train_x) __A : str = np.array(test_x) __A : Dict = np.array([list(i.ravel()) for i in train_y]) __A : int = np.array([list(i.ravel()) for i in test_y]) __A : Optional[Any] = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss='''mean_squared_error''', optimizer='''adam''') __A : Union[str, Any] = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) __A : Union[str, Any] = model.predict(x_test)
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 unittest import numpy as np from huggingface_hub import hf_hub_download from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from transformers import OneFormerImageProcessor from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput if is_vision_available(): from PIL import Image def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Union[str, Any]="shi-labs/oneformer_demo" ): '''simple docstring''' with open(hf_hub_download(snake_case_ ,snake_case_ ,repo_type="""dataset""" ) ,"""r""" ) as f: UpperCamelCase : Optional[int] = json.load(snake_case_ ) UpperCamelCase : Any = {} UpperCamelCase : Optional[int] = [] UpperCamelCase : int = [] for key, info in class_info.items(): UpperCamelCase : Optional[int] = info["""name"""] class_names.append(info["""name"""] ) if info["isthing"]: thing_ids.append(int(snake_case_ ) ) UpperCamelCase : Any = thing_ids UpperCamelCase : Any = class_names return metadata class lowerCamelCase ( unittest.TestCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=400 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=255 , SCREAMING_SNAKE_CASE_="shi-labs/oneformer_demo" , SCREAMING_SNAKE_CASE_="ade20k_panoptic.json" , SCREAMING_SNAKE_CASE_=10 , ): UpperCamelCase : Optional[Any] = parent UpperCamelCase : List[str] = batch_size UpperCamelCase : List[Any] = num_channels UpperCamelCase : Any = min_resolution UpperCamelCase : List[str] = max_resolution UpperCamelCase : Tuple = do_resize UpperCamelCase : Optional[int] = {"""shortest_edge""": 32, """longest_edge""": 1333} if size is None else size UpperCamelCase : str = do_normalize UpperCamelCase : Tuple = image_mean UpperCamelCase : str = image_std UpperCamelCase : Optional[int] = class_info_file UpperCamelCase : Dict = prepare_metadata(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = num_text UpperCamelCase : Optional[int] = repo_path # for the post_process_functions UpperCamelCase : str = 2 UpperCamelCase : Union[str, Any] = 10 UpperCamelCase : List[Any] = 10 UpperCamelCase : Dict = 3 UpperCamelCase : str = 4 UpperCamelCase : Any = num_labels UpperCamelCase : Dict = do_reduce_labels UpperCamelCase : Union[str, Any] = ignore_index def a_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "num_labels": self.num_labels, "do_reduce_labels": self.do_reduce_labels, "ignore_index": self.ignore_index, "class_info_file": self.class_info_file, "metadata": self.metadata, "num_text": self.num_text, } def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): if not batched: UpperCamelCase : int = image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE_ , Image.Image ): UpperCamelCase , UpperCamelCase : Union[str, Any] = image.size else: UpperCamelCase , UpperCamelCase : List[str] = image.shape[1], image.shape[2] if w < h: UpperCamelCase : Tuple = int(self.size["""shortest_edge"""] * h / w ) UpperCamelCase : str = self.size["""shortest_edge"""] elif w > h: UpperCamelCase : Tuple = self.size["""shortest_edge"""] UpperCamelCase : Union[str, Any] = int(self.size["""shortest_edge"""] * w / h ) else: UpperCamelCase : List[Any] = self.size["""shortest_edge"""] UpperCamelCase : str = self.size["""shortest_edge"""] else: UpperCamelCase : int = [] for image in image_inputs: UpperCamelCase , UpperCamelCase : Dict = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCamelCase : List[Any] = max(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : item[0] )[0] UpperCamelCase : int = max(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : item[1] )[1] return expected_height, expected_width def a_ ( self ): return OneFormerForUniversalSegmentationOutput( # +1 for null class class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , ) @require_torch @require_vision class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Union[str, Any] = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string lowercase : str = image_processing_class def a_ ( self ): UpperCamelCase : Optional[Any] = OneFormerImageProcessorTester(self ) @property def a_ ( self ): return self.image_processing_tester.prepare_image_processor_dict() def a_ ( self ): UpperCamelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_mean""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_std""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_normalize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_resize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """size""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """ignore_index""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """class_info_file""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """num_text""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """repo_path""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """metadata""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_reduce_labels""" ) ) def a_ ( self ): pass def a_ ( self ): # Initialize image_processor UpperCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase : int = prepare_image_inputs(self.image_processing_tester , equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input UpperCamelCase : List[str] = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase : str = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase , UpperCamelCase : Tuple = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = image_processor( SCREAMING_SNAKE_CASE_ , ["""semantic"""] * len(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def a_ ( self ): # Initialize image_processor UpperCamelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase : List[Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) # Test not batched input UpperCamelCase : Optional[Any] = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase : Any = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase , UpperCamelCase : Any = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = image_processor( SCREAMING_SNAKE_CASE_ , ["""semantic"""] * len(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def a_ ( self ): # Initialize image_processor UpperCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase : Dict = prepare_image_inputs(self.image_processing_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) # Test not batched input UpperCamelCase : Optional[int] = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values UpperCamelCase , UpperCamelCase : Optional[Any] = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase , UpperCamelCase : Optional[Any] = self.image_processing_tester.get_expected_values(SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = image_processor( SCREAMING_SNAKE_CASE_ , ["""semantic"""] * len(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def a_ ( self , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="np" ): UpperCamelCase : List[str] = self.image_processing_class(**self.image_processor_dict ) # prepare image and target UpperCamelCase : Union[str, Any] = self.image_processing_tester.num_labels UpperCamelCase : str = None UpperCamelCase : int = None UpperCamelCase : Optional[Any] = prepare_image_inputs(self.image_processing_tester , equal_resolution=SCREAMING_SNAKE_CASE_ ) if with_segmentation_maps: UpperCamelCase : Any = num_labels if is_instance_map: UpperCamelCase : Tuple = list(range(SCREAMING_SNAKE_CASE_ ) ) * 2 UpperCamelCase : List[str] = dict(enumerate(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Optional[Any] = [ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": UpperCamelCase : List[Any] = [Image.fromarray(SCREAMING_SNAKE_CASE_ ) for annotation in annotations] UpperCamelCase : List[Any] = image_processor( SCREAMING_SNAKE_CASE_ , ["""semantic"""] * len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , instance_id_to_semantic_id=SCREAMING_SNAKE_CASE_ , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE_ , ) return inputs def a_ ( self ): pass def a_ ( self ): def common(SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=None ): UpperCamelCase : Dict = self.comm_get_image_processor_inputs( with_segmentation_maps=SCREAMING_SNAKE_CASE_ , is_instance_map=SCREAMING_SNAKE_CASE_ , segmentation_type=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = inputs["""mask_labels"""] UpperCamelCase : Any = inputs["""class_labels"""] UpperCamelCase : Any = inputs["""pixel_values"""] UpperCamelCase : Union[str, Any] = inputs["""text_inputs"""] # check the batch_size for mask_label, class_label, text_input in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(mask_label.shape[0] , class_label.shape[0] ) # this ensure padding has happened self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.image_processing_tester.num_text ) common() common(is_instance_map=SCREAMING_SNAKE_CASE_ ) common(is_instance_map=SCREAMING_SNAKE_CASE_ , segmentation_type="""pil""" ) common(is_instance_map=SCREAMING_SNAKE_CASE_ , segmentation_type="""pil""" ) def a_ ( self ): UpperCamelCase : int = np.zeros((20, 50) ) UpperCamelCase : Dict = 1 UpperCamelCase : List[Any] = 1 UpperCamelCase : Optional[int] = 1 UpperCamelCase : Optional[int] = binary_mask_to_rle(SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 4 ) self.assertEqual(rle[0] , 21 ) self.assertEqual(rle[1] , 45 ) def a_ ( self ): UpperCamelCase : Dict = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) UpperCamelCase : List[str] = self.image_processing_tester.get_fake_oneformer_outputs() UpperCamelCase : int = fature_extractor.post_process_semantic_segmentation(SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) UpperCamelCase : Optional[Any] = [(1, 4) for i in range(self.image_processing_tester.batch_size )] UpperCamelCase : Union[str, Any] = fature_extractor.post_process_semantic_segmentation(SCREAMING_SNAKE_CASE_ , target_sizes=SCREAMING_SNAKE_CASE_ ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) UpperCamelCase : List[str] = self.image_processing_tester.get_fake_oneformer_outputs() UpperCamelCase : Any = image_processor.post_process_instance_segmentation(SCREAMING_SNAKE_CASE_ , threshold=0 ) self.assertTrue(len(SCREAMING_SNAKE_CASE_ ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def a_ ( self ): UpperCamelCase : List[Any] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) UpperCamelCase : Union[str, Any] = self.image_processing_tester.get_fake_oneformer_outputs() UpperCamelCase : Dict = image_processor.post_process_panoptic_segmentation(SCREAMING_SNAKE_CASE_ , threshold=0 ) self.assertTrue(len(SCREAMING_SNAKE_CASE_ ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
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 defaultdict class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N # initially all values are set to -1 UpperCamelCase : int = [ [-1 for i in range(total + 1 )] for j in range(2 ** len(SCREAMING_SNAKE_CASE_ ) ) ] UpperCamelCase : Optional[int] = defaultdict(SCREAMING_SNAKE_CASE_ ) # stores the list of persons for each task # final_mask is used to check if all persons are included by setting all bits # to 1 UpperCamelCase : Dict = (1 << len(SCREAMING_SNAKE_CASE_ )) - 1 def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): # if mask == self.finalmask all persons are distributed tasks, return 1 if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 if task_no > self.total_tasks: return 0 # if case already considered if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement UpperCamelCase : str = self.count_ways_until(SCREAMING_SNAKE_CASE_ , task_no + 1 ) # now assign the tasks one by one to all possible persons and recursively # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively # assign tasks with the new mask value. total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 ) # save the value. UpperCamelCase : List[str] = total_ways_util return self.dp[mask][task_no] def a_ ( self , SCREAMING_SNAKE_CASE_ ): # Store the list of persons for each task for i in range(len(SCREAMING_SNAKE_CASE_ ) ): for j in task_performed[i]: self.task[j].append(SCREAMING_SNAKE_CASE_ ) # call the function to fill the DP table, final answer is stored in dp[0][1] return self.count_ways_until(0 , 1 ) if __name__ == "__main__": __A : int = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. __A : Optional[int] = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) )
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 json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer __A : Optional[int] = logging.get_logger(__name__) __A : Any = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} # See all BART models at https://huggingface.co/models?filter=bart __A : Any = { '''vocab_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''', }, '''merges_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json''', }, } __A : List[str] = { '''facebook/bart-base''': 1024, '''facebook/bart-large''': 1024, '''facebook/bart-large-mnli''': 1024, '''facebook/bart-large-cnn''': 1024, '''facebook/bart-large-xsum''': 1024, '''yjernite/bart_eli5''': 1024, } class lowerCamelCase ( _UpperCAmelCase ): lowercase : Union[str, Any] = VOCAB_FILES_NAMES lowercase : Tuple = PRETRAINED_VOCAB_FILES_MAP lowercase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : str = ['input_ids', 'attention_mask'] lowercase : Dict = BartTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="replace" , 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_=False , SCREAMING_SNAKE_CASE_=True , **SCREAMING_SNAKE_CASE_ , ): super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , errors=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , SCREAMING_SNAKE_CASE_ ) != add_prefix_space: UpperCamelCase : Optional[int] = getattr(SCREAMING_SNAKE_CASE_ , pre_tok_state.pop("""type""" ) ) UpperCamelCase : List[str] = add_prefix_space UpperCamelCase : Optional[int] = pre_tok_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` UpperCamelCase : List[str] = """post_processor""" UpperCamelCase : str = getattr(self.backend_tokenizer , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if tokenizer_component_instance: UpperCamelCase : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: UpperCamelCase : Optional[Any] = tuple(state["""sep"""] ) if "cls" in state: UpperCamelCase : int = tuple(state["""cls"""] ) UpperCamelCase : Dict = False if state.get("""add_prefix_space""" , SCREAMING_SNAKE_CASE_ ) != add_prefix_space: UpperCamelCase : Dict = add_prefix_space UpperCamelCase : List[Any] = True if state.get("""trim_offsets""" , SCREAMING_SNAKE_CASE_ ) != trim_offsets: UpperCamelCase : Dict = trim_offsets UpperCamelCase : Any = True if changes_to_apply: UpperCamelCase : Union[str, Any] = getattr(SCREAMING_SNAKE_CASE_ , state.pop("""type""" ) ) UpperCamelCase : Tuple = component_class(**SCREAMING_SNAKE_CASE_ ) setattr(self.backend_tokenizer , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @property def a_ ( self ): if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else value UpperCamelCase : List[Any] = value def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = kwargs.get("""is_split_into_words""" , SCREAMING_SNAKE_CASE_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' """to use it with pretokenized inputs.""" ) return super()._batch_encode_plus(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = kwargs.get("""is_split_into_words""" , SCREAMING_SNAKE_CASE_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' """to use it with pretokenized inputs.""" ) return super()._encode_plus(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Any = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): UpperCamelCase : int = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : List[Any] = [self.sep_token_id] UpperCamelCase : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
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 os import jsonlines import numpy as np from tqdm import tqdm __A : Optional[Any] = 2048 __A : List[Any] = 4096 __A : str = 42 __A : Optional[int] = os.environ.pop('''PROCESS_TRAIN''', '''false''') __A : List[Any] = {'''null''': 0, '''short''': 1, '''long''': 2, '''yes''': 3, '''no''': 4} def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' def choose_first(snake_case_ : Dict ,snake_case_ : str=False ): assert isinstance(snake_case_ ,snake_case_ ) if len(snake_case_ ) == 1: UpperCamelCase : Union[str, Any] = answer[0] return {k: [answer[k]] for k in answer} if is_long_answer else answer for a in answer: if is_long_answer: UpperCamelCase : Optional[Any] = {k: [a[k]] for k in a} if len(a["""start_token"""] ) > 0: break return a UpperCamelCase : str = {"""id""": example["""id"""]} UpperCamelCase : List[str] = example["""annotations"""] UpperCamelCase : Dict = annotation["""yes_no_answer"""] if 0 in yes_no_answer or 1 in yes_no_answer: UpperCamelCase : Optional[int] = ["""yes"""] if 1 in yes_no_answer else ["""no"""] UpperCamelCase : Optional[int] = [] UpperCamelCase : Optional[Any] = [] UpperCamelCase : Tuple = ["""<cls>"""] else: UpperCamelCase : int = ["""short"""] UpperCamelCase : Union[str, Any] = choose_first(annotation["""short_answers"""] ) if len(out["""start_token"""] ) == 0: # answer will be long if short is not available UpperCamelCase : List[str] = ["""long"""] UpperCamelCase : List[str] = choose_first(annotation["""long_answer"""] ,is_long_answer=snake_case_ ) UpperCamelCase : str = [] answer.update(snake_case_ ) # disregard some samples if len(answer["""start_token"""] ) > 1 or answer["start_token"] == answer["end_token"]: UpperCamelCase : str = True else: UpperCamelCase : List[Any] = False UpperCamelCase : Any = ["""start_token""", """end_token""", """start_byte""", """end_byte""", """text"""] if not all(isinstance(answer[k] ,snake_case_ ) for k in cols ): raise ValueError("""Issue in ID""" ,example["""id"""] ) return answer def A_ ( snake_case_ : Any ,snake_case_ : Optional[Any]=False ): '''simple docstring''' UpperCamelCase : List[str] = _get_single_answer(snake_case_ ) # bytes are of no use del answer["start_byte"] del answer["end_byte"] # handle yes_no answers explicitly if answer["category"][0] in ["yes", "no"]: # category is list with one element UpperCamelCase : Optional[int] = example["""document"""]["""tokens"""] UpperCamelCase : List[Any] = [] for i in range(len(doc["""token"""] ) ): if not doc["is_html"][i]: context.append(doc["""token"""][i] ) return { "context": " ".join(snake_case_ ), "answer": { "start_token": -1_0_0, # ignore index in cross-entropy "end_token": -1_0_0, # ignore index in cross-entropy "category": answer["category"], "span": answer["category"], # extra }, } # later, help in removing all no answers if answer["start_token"] == [-1]: return { "context": "None", "answer": { "start_token": -1, "end_token": -1, "category": "null", "span": "None", # extra }, } # handling normal samples UpperCamelCase : str = ["""start_token""", """end_token"""] answer.update({k: answer[k][0] if len(answer[k] ) > 0 else answer[k] for k in cols} ) # e.g. [10] == 10 UpperCamelCase : Dict = example["""document"""]["""tokens"""] UpperCamelCase : List[str] = answer["""start_token"""] UpperCamelCase : Optional[int] = answer["""end_token"""] UpperCamelCase : Optional[Any] = [] for i in range(len(doc["""token"""] ) ): if not doc["is_html"][i]: context.append(doc["""token"""][i] ) else: if answer["start_token"] > i: start_token -= 1 if answer["end_token"] > i: end_token -= 1 UpperCamelCase : Optional[Any] = """ """.join(context[start_token:end_token] ) # checking above code if assertion: UpperCamelCase : Optional[Any] = doc["""is_html"""][answer["""start_token"""] : answer["""end_token"""]] UpperCamelCase : Dict = doc["""token"""][answer["""start_token"""] : answer["""end_token"""]] UpperCamelCase : Optional[Any] = """ """.join([old[i] for i in range(len(snake_case_ ) ) if not is_html[i]] ) if new != old: print("""ID:""" ,example["""id"""] ) print("""New:""" ,snake_case_ ,end="""\n""" ) print("""Old:""" ,snake_case_ ,end="""\n\n""" ) return { "context": " ".join(snake_case_ ), "answer": { "start_token": start_token, "end_token": end_token - 1, # this makes it inclusive "category": answer["category"], # either long or short "span": new, # extra }, } def A_ ( snake_case_ : Dict ,snake_case_ : Optional[Any] ,snake_case_ : Tuple=2_0_4_8 ,snake_case_ : str=4_0_9_6 ,snake_case_ : Optional[int]=True ): '''simple docstring''' # overlap will be of doc_stride - q_len UpperCamelCase : List[Any] = get_context_and_ans(snake_case_ ,assertion=snake_case_ ) UpperCamelCase : Optional[Any] = out["""answer"""] # later, removing these samples if answer["start_token"] == -1: return { "example_id": example["id"], "input_ids": [[-1]], "labels": { "start_token": [-1], "end_token": [-1], "category": ["null"], }, } UpperCamelCase : Optional[Any] = tokenizer(example["""question"""]["""text"""] ,out["""context"""] ).input_ids UpperCamelCase : Dict = input_ids.index(tokenizer.sep_token_id ) + 1 # return yes/no if answer["category"][0] in ["yes", "no"]: # category is list with one element UpperCamelCase : List[Any] = [] UpperCamelCase : List[str] = [] UpperCamelCase : Optional[Any] = input_ids[:q_len] UpperCamelCase : List[str] = range(snake_case_ ,len(snake_case_ ) ,max_length - doc_stride ) for i in doc_start_indices: UpperCamelCase : str = i + max_length - q_len UpperCamelCase : Optional[Any] = input_ids[i:end_index] inputs.append(q_indices + slice ) category.append(answer["""category"""][0] ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": [-1_0_0] * len(snake_case_ ), "end_token": [-1_0_0] * len(snake_case_ ), "category": category, }, } UpperCamelCase : int = out["""context"""].split() UpperCamelCase : Tuple = splitted_context[answer["""end_token"""]] UpperCamelCase : List[Any] = len( tokenizer( """ """.join(splitted_context[: answer["""start_token"""]] ) ,add_special_tokens=snake_case_ ,).input_ids ) UpperCamelCase : List[str] = len( tokenizer(""" """.join(splitted_context[: answer["""end_token"""]] ) ,add_special_tokens=snake_case_ ).input_ids ) answer["start_token"] += q_len answer["end_token"] += q_len # fixing end token UpperCamelCase : Any = len(tokenizer(snake_case_ ,add_special_tokens=snake_case_ ).input_ids ) if num_sub_tokens > 1: answer["end_token"] += num_sub_tokens - 1 UpperCamelCase : Tuple = input_ids[answer["""start_token"""] : answer["""end_token"""] + 1] # right & left are inclusive UpperCamelCase : Any = answer["""start_token"""] UpperCamelCase : Optional[Any] = answer["""end_token"""] if assertion: UpperCamelCase : str = tokenizer.decode(snake_case_ ) if answer["span"] != new: print("""ISSUE IN TOKENIZATION""" ) print("""OLD:""" ,answer["""span"""] ) print("""NEW:""" ,snake_case_ ,end="""\n\n""" ) if len(snake_case_ ) <= max_length: return { "example_id": example["id"], "input_ids": [input_ids], "labels": { "start_token": [answer["start_token"]], "end_token": [answer["end_token"]], "category": answer["category"], }, } UpperCamelCase : Tuple = input_ids[:q_len] UpperCamelCase : Union[str, Any] = range(snake_case_ ,len(snake_case_ ) ,max_length - doc_stride ) UpperCamelCase : Any = [] UpperCamelCase : str = [] UpperCamelCase : Optional[int] = [] UpperCamelCase : Tuple = [] # null, yes, no, long, short for i in doc_start_indices: UpperCamelCase : Tuple = i + max_length - q_len UpperCamelCase : Optional[Any] = input_ids[i:end_index] inputs.append(q_indices + slice ) assert len(inputs[-1] ) <= max_length, "Issue in truncating length" if start_token >= i and end_token <= end_index - 1: UpperCamelCase : Any = start_token - i + q_len UpperCamelCase : Any = end_token - i + q_len answers_category.append(answer["""category"""][0] ) # ["short"] -> "short" else: UpperCamelCase : Optional[Any] = -1_0_0 UpperCamelCase : List[Any] = -1_0_0 answers_category.append("""null""" ) UpperCamelCase : Optional[int] = inputs[-1][start_token : end_token + 1] answers_start_token.append(snake_case_ ) answers_end_token.append(snake_case_ ) if assertion: if new != old and new != [tokenizer.cls_token_id]: print("""ISSUE in strided for ID:""" ,example["""id"""] ) print("""New:""" ,tokenizer.decode(snake_case_ ) ) print("""Old:""" ,tokenizer.decode(snake_case_ ) ,end="""\n\n""" ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": answers_start_token, "end_token": answers_end_token, "category": answers_category, }, } def A_ ( snake_case_ : Optional[Any] ,snake_case_ : List[str] ,snake_case_ : str=2_0_4_8 ,snake_case_ : List[Any]=4_0_9_6 ,snake_case_ : Any=False ): '''simple docstring''' UpperCamelCase : Optional[Any] = get_strided_contexts_and_ans( snake_case_ ,snake_case_ ,doc_stride=snake_case_ ,max_length=snake_case_ ,assertion=snake_case_ ,) return example def A_ ( snake_case_ : Optional[int] ,snake_case_ : Optional[int] ): '''simple docstring''' with jsonlines.open(snake_case_ ,"""a""" ) as writer: for example in tqdm(snake_case_ ,total=len(snake_case_ ) ,desc="""Saving samples ... """ ): UpperCamelCase : int = example["""labels"""] for ids, start, end, cat in zip( example["""input_ids"""] ,labels["""start_token"""] ,labels["""end_token"""] ,labels["""category"""] ,): if start == -1 and end == -1: continue # leave waste samples with no answer if cat == "null" and np.random.rand() < 0.6: continue # removing 50 % samples writer.write( { """input_ids""": ids, """start_token""": start, """end_token""": end, """category""": CATEGORY_MAPPING[cat], } ) if __name__ == "__main__": from datasets import load_dataset from transformers import BigBirdTokenizer __A : Union[str, Any] = load_dataset('''natural_questions''') __A : List[str] = BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''') __A : Dict = data['''train''' if PROCESS_TRAIN == '''true''' else '''validation'''] __A : Tuple = { '''tokenizer''': tokenizer, '''doc_stride''': DOC_STRIDE, '''max_length''': MAX_LENGTH, '''assertion''': False, } __A : List[Any] = data.map(prepare_inputs, fn_kwargs=fn_kwargs) __A : int = data.remove_columns(['''annotations''', '''document''', '''id''', '''question''']) print(data) np.random.seed(SEED) __A : Union[str, Any] = '''nq-training.jsonl''' if PROCESS_TRAIN == '''true''' else '''nq-validation.jsonl''' save_to_disk(data, file_name=cache_file_name)
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 inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=32 * 8 , SCREAMING_SNAKE_CASE_=32 * 8 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : str = batch_size UpperCamelCase : str = is_training UpperCamelCase : List[str] = use_auxiliary_loss UpperCamelCase : List[str] = num_queries UpperCamelCase : str = num_channels UpperCamelCase : Optional[Any] = min_size UpperCamelCase : Optional[int] = max_size UpperCamelCase : Any = num_labels UpperCamelCase : Optional[int] = hidden_dim UpperCamelCase : str = hidden_dim def a_ ( self ): UpperCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE_ ) > 0.5 ).float() UpperCamelCase : Optional[Any] = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE_ ) > 0.5).long() UpperCamelCase : Union[str, Any] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def a_ ( self ): UpperCamelCase : str = MaskaFormerConfig( hidden_size=self.hidden_dim , ) UpperCamelCase : int = self.num_queries UpperCamelCase : int = self.num_labels UpperCamelCase : Union[str, Any] = [1, 1, 1, 1] UpperCamelCase : Any = self.num_channels UpperCamelCase : Union[str, Any] = 64 UpperCamelCase : Optional[int] = 128 UpperCamelCase : Optional[Any] = self.hidden_dim UpperCamelCase : List[str] = self.hidden_dim UpperCamelCase : Any = self.hidden_dim return config def a_ ( self ): UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : List[Any] = self.prepare_config_and_inputs() UpperCamelCase : Optional[Any] = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask} return config, inputs_dict def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = output.encoder_hidden_states UpperCamelCase : List[str] = output.pixel_decoder_hidden_states UpperCamelCase : Dict = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ) , config.decoder_layers ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): with torch.no_grad(): UpperCamelCase : Dict = MaskaFormerModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model(pixel_values=SCREAMING_SNAKE_CASE_ , pixel_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE_ ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): UpperCamelCase : Optional[Any] = model(pixel_values=SCREAMING_SNAKE_CASE_ , pixel_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ) comm_check_on_output(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model( pixel_values=SCREAMING_SNAKE_CASE_ , pixel_mask=SCREAMING_SNAKE_CASE_ , mask_labels=SCREAMING_SNAKE_CASE_ , class_labels=SCREAMING_SNAKE_CASE_ ) comm_check_on_output(SCREAMING_SNAKE_CASE_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : int = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () lowercase : List[Any] = {'feature-extraction': MaskaFormerModel} if is_torch_available() else {} lowercase : List[Any] = False lowercase : Any = False lowercase : int = False lowercase : Any = False def a_ ( self ): UpperCamelCase : Dict = MaskaFormerModelTester(self ) UpperCamelCase : List[str] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase , UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""" ) def a_ ( self ): pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""" ) def a_ ( self ): pass @unittest.skip(reason="""Mask2Former is not a generative model""" ) def a_ ( self ): pass @unittest.skip(reason="""Mask2Former does not use token embeddings""" ) def a_ ( self ): pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def a_ ( self ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def a_ ( self ): pass def a_ ( self ): UpperCamelCase , UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : int = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase : int = [*signature.parameters.keys()] UpperCamelCase : List[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in ["facebook/mask2former-swin-small-coco-instance"]: UpperCamelCase : str = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = (self.model_tester.min_size,) * 2 UpperCamelCase : Any = { """pixel_values""": torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE_ ), """mask_labels""": torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE_ ), """class_labels""": torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE_ ).long(), } UpperCamelCase : Optional[Any] = self.model_tester.get_config() UpperCamelCase : List[str] = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(**SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.loss is not None ) def a_ ( self ): UpperCamelCase , UpperCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase , UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : List[str] = model_class(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = model(**SCREAMING_SNAKE_CASE_ , output_attentions=SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.attentions is not None ) def a_ ( self ): if not self.model_tester.is_training: return UpperCamelCase : int = self.all_model_classes[1] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() UpperCamelCase : Optional[int] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase : str = model(SCREAMING_SNAKE_CASE_ , mask_labels=SCREAMING_SNAKE_CASE_ , class_labels=SCREAMING_SNAKE_CASE_ ).loss loss.backward() def a_ ( self ): UpperCamelCase : Tuple = self.all_model_classes[1] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() UpperCamelCase : Optional[int] = True UpperCamelCase : int = True UpperCamelCase : Any = model_class(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , mask_labels=SCREAMING_SNAKE_CASE_ , class_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCamelCase : List[str] = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() UpperCamelCase : List[str] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCamelCase : Dict = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __A : List[str] = 1e-4 def A_ ( ): '''simple docstring''' UpperCamelCase : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class lowerCamelCase ( unittest.TestCase ): @cached_property def a_ ( self ): return "facebook/mask2former-swin-small-coco-instance" @cached_property def a_ ( self ): return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def a_ ( self ): UpperCamelCase : Optional[int] = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.default_image_processor UpperCamelCase : str = prepare_img() UpperCamelCase : Tuple = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE_ , (1, 3, 384, 384) ) with torch.no_grad(): UpperCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = torch.tensor( [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Union[str, Any] = torch.tensor( [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : List[Any] = torch.tensor( [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): UpperCamelCase : Union[str, Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase : List[str] = self.default_image_processor UpperCamelCase : List[Any] = prepare_img() UpperCamelCase : List[str] = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = inputs["""pixel_values"""].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE_ , (1, 3, 384, 384) ) with torch.no_grad(): UpperCamelCase : Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) # masks_queries_logits UpperCamelCase : str = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) UpperCamelCase : Dict = [ [-8.7839, -9.0056, -8.8121], [-7.4104, -7.0313, -6.5401], [-6.6105, -6.3427, -6.4675], ] UpperCamelCase : Dict = torch.tensor(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) # class_queries_logits UpperCamelCase : Tuple = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) UpperCamelCase : Dict = torch.tensor( [ [1.8324, -8.0835, -4.1922], [0.8450, -9.0050, -3.6053], [0.3045, -7.7293, -3.0275], ] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): UpperCamelCase : Dict = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase : Union[str, Any] = self.default_image_processor UpperCamelCase : Union[str, Any] = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="""pt""" , ) UpperCamelCase : Optional[int] = inputs["""pixel_values"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = [el.to(SCREAMING_SNAKE_CASE_ ) for el in inputs["""mask_labels"""]] UpperCamelCase : Tuple = [el.to(SCREAMING_SNAKE_CASE_ ) for el in inputs["""class_labels"""]] with torch.no_grad(): UpperCamelCase : Dict = model(**SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.loss is not None )
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 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 : Tuple = ['image_processor', 'tokenizer'] lowercase : Any = 'BlipImageProcessor' lowercase : str = 'AutoTokenizer' def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = False super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = self.image_processor def __call__( self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: UpperCamelCase : int = self.tokenizer UpperCamelCase : List[str] = self.tokenizer( text=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_overflowing_tokens=SCREAMING_SNAKE_CASE_ , return_special_tokens_mask=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_length=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) return text_encoding # add pixel_values UpperCamelCase : int = self.image_processor(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ ) 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_attention_mask=SCREAMING_SNAKE_CASE_ , return_overflowing_tokens=SCREAMING_SNAKE_CASE_ , return_special_tokens_mask=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_length=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) else: UpperCamelCase : int = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE_ ) return encoding_image_processor 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 # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def a_ ( self ): UpperCamelCase : Union[str, Any] = self.tokenizer.model_input_names UpperCamelCase : Optional[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
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""" def A_ ( snake_case_ : int ,snake_case_ : int ): '''simple docstring''' while b: UpperCamelCase , UpperCamelCase : Optional[int] = b, a % b return a def A_ ( snake_case_ : int ,snake_case_ : int ): '''simple docstring''' return a if b == 0 else euclidean_gcd_recursive(snake_case_ ,a % b ) def A_ ( ): '''simple docstring''' print(f'euclidean_gcd(3, 5) = {euclidean_gcd(3 ,5 )}' ) print(f'euclidean_gcd(5, 3) = {euclidean_gcd(5 ,3 )}' ) print(f'euclidean_gcd(1, 3) = {euclidean_gcd(1 ,3 )}' ) print(f'euclidean_gcd(3, 6) = {euclidean_gcd(3 ,6 )}' ) print(f'euclidean_gcd(6, 3) = {euclidean_gcd(6 ,3 )}' ) print(f'euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 ,5 )}' ) print(f'euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 ,3 )}' ) print(f'euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 ,3 )}' ) print(f'euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 ,6 )}' ) print(f'euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 ,3 )}' ) if __name__ == "__main__": main()
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 warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class lowerCamelCase ( _UpperCAmelCase ): lowercase : Tuple = ['image_processor', 'tokenizer'] lowercase : Union[str, Any] = 'AutoImageProcessor' lowercase : Dict = 'AutoTokenizer' 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 : Tuple = 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 : int = self.image_processor UpperCamelCase : int = False 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 : Any = kwargs.pop("""images""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: UpperCamelCase : List[Any] = args[0] UpperCamelCase : Optional[int] = args[1:] if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: UpperCamelCase : Optional[Any] = self.image_processor(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if text is not None: UpperCamelCase : str = self.tokenizer(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if text is None: return inputs elif images is None: return encodings else: UpperCamelCase : str = 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_ ) @contextmanager def a_ ( self ): warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your images inputs, or in a separate call.""" ) UpperCamelCase : Tuple = True UpperCamelCase : Dict = self.tokenizer yield UpperCamelCase : Optional[Any] = self.image_processor UpperCamelCase : Dict = False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=None ): if added_vocab is None: UpperCamelCase : Tuple = self.tokenizer.get_added_vocab() UpperCamelCase : List[str] = {} while tokens: UpperCamelCase : Union[str, Any] = re.search(r"""<s_(.*?)>""" , SCREAMING_SNAKE_CASE_ , re.IGNORECASE ) if start_token is None: break UpperCamelCase : int = start_token.group(1 ) UpperCamelCase : int = re.search(rf'</s_{key}>' , SCREAMING_SNAKE_CASE_ , re.IGNORECASE ) UpperCamelCase : str = start_token.group() if end_token is None: UpperCamelCase : Union[str, Any] = tokens.replace(SCREAMING_SNAKE_CASE_ , """""" ) else: UpperCamelCase : Optional[Any] = end_token.group() UpperCamelCase : Optional[int] = re.escape(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = re.escape(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = re.search(f'{start_token_escaped}(.*?){end_token_escaped}' , SCREAMING_SNAKE_CASE_ , re.IGNORECASE ) if content is not None: UpperCamelCase : str = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node UpperCamelCase : Any = self.tokenajson(SCREAMING_SNAKE_CASE_ , is_inner_value=SCREAMING_SNAKE_CASE_ , added_vocab=SCREAMING_SNAKE_CASE_ ) if value: if len(SCREAMING_SNAKE_CASE_ ) == 1: UpperCamelCase : Any = value[0] UpperCamelCase : Union[str, Any] = value else: # leaf nodes UpperCamelCase : int = [] for leaf in content.split(r"""<sep/>""" ): UpperCamelCase : List[str] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": UpperCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE_ ) if len(output[key] ) == 1: UpperCamelCase : List[Any] = output[key][0] UpperCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE_ ) + len(SCREAMING_SNAKE_CASE_ ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] , is_inner_value=SCREAMING_SNAKE_CASE_ , added_vocab=SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def a_ ( self ): 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 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 ...configuration_utils import PretrainedConfig from ...utils import logging __A : str = logging.get_logger(__name__) __A : Union[str, Any] = { '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[str] = 'audio-spectrogram-transformer' def __init__( self , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=128 , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : List[Any] = num_attention_heads UpperCamelCase : Any = intermediate_size UpperCamelCase : Optional[int] = hidden_act UpperCamelCase : List[str] = hidden_dropout_prob UpperCamelCase : Optional[int] = attention_probs_dropout_prob UpperCamelCase : Union[str, Any] = initializer_range UpperCamelCase : Tuple = layer_norm_eps UpperCamelCase : Tuple = patch_size UpperCamelCase : Tuple = qkv_bias UpperCamelCase : Optional[Any] = frequency_stride UpperCamelCase : Dict = time_stride UpperCamelCase : Any = max_length UpperCamelCase : Any = num_mel_bins
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 math def A_ ( ): '''simple docstring''' UpperCamelCase : Dict = input("""Enter message: """ ) UpperCamelCase : Optional[int] = int(input(f'Enter key [2-{len(snake_case_ ) - 1}]: ' ) ) UpperCamelCase : Union[str, Any] = input("""Encryption/Decryption [e/d]: """ ) if mode.lower().startswith("""e""" ): UpperCamelCase : int = encrypt_message(snake_case_ ,snake_case_ ) elif mode.lower().startswith("""d""" ): UpperCamelCase : str = decrypt_message(snake_case_ ,snake_case_ ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f'Output:\n{text + "|"}' ) def A_ ( snake_case_ : int ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[str] = [""""""] * key for col in range(snake_case_ ): UpperCamelCase : Optional[Any] = col while pointer < len(snake_case_ ): cipher_text[col] += message[pointer] pointer += key return "".join(snake_case_ ) def A_ ( snake_case_ : int ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : Any = math.ceil(len(snake_case_ ) / key ) UpperCamelCase : Tuple = key UpperCamelCase : Any = (num_cols * num_rows) - len(snake_case_ ) UpperCamelCase : List[str] = [""""""] * num_cols UpperCamelCase : Dict = 0 UpperCamelCase : Optional[int] = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): UpperCamelCase : Dict = 0 row += 1 return "".join(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
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""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool __A : str = { '''Acehnese Arabic''': '''ace_Arab''', '''Acehnese Latin''': '''ace_Latn''', '''Mesopotamian Arabic''': '''acm_Arab''', '''Ta\'izzi-Adeni Arabic''': '''acq_Arab''', '''Tunisian Arabic''': '''aeb_Arab''', '''Afrikaans''': '''afr_Latn''', '''South Levantine Arabic''': '''ajp_Arab''', '''Akan''': '''aka_Latn''', '''Amharic''': '''amh_Ethi''', '''North Levantine Arabic''': '''apc_Arab''', '''Modern Standard Arabic''': '''arb_Arab''', '''Modern Standard Arabic Romanized''': '''arb_Latn''', '''Najdi Arabic''': '''ars_Arab''', '''Moroccan Arabic''': '''ary_Arab''', '''Egyptian Arabic''': '''arz_Arab''', '''Assamese''': '''asm_Beng''', '''Asturian''': '''ast_Latn''', '''Awadhi''': '''awa_Deva''', '''Central Aymara''': '''ayr_Latn''', '''South Azerbaijani''': '''azb_Arab''', '''North Azerbaijani''': '''azj_Latn''', '''Bashkir''': '''bak_Cyrl''', '''Bambara''': '''bam_Latn''', '''Balinese''': '''ban_Latn''', '''Belarusian''': '''bel_Cyrl''', '''Bemba''': '''bem_Latn''', '''Bengali''': '''ben_Beng''', '''Bhojpuri''': '''bho_Deva''', '''Banjar Arabic''': '''bjn_Arab''', '''Banjar Latin''': '''bjn_Latn''', '''Standard Tibetan''': '''bod_Tibt''', '''Bosnian''': '''bos_Latn''', '''Buginese''': '''bug_Latn''', '''Bulgarian''': '''bul_Cyrl''', '''Catalan''': '''cat_Latn''', '''Cebuano''': '''ceb_Latn''', '''Czech''': '''ces_Latn''', '''Chokwe''': '''cjk_Latn''', '''Central Kurdish''': '''ckb_Arab''', '''Crimean Tatar''': '''crh_Latn''', '''Welsh''': '''cym_Latn''', '''Danish''': '''dan_Latn''', '''German''': '''deu_Latn''', '''Southwestern Dinka''': '''dik_Latn''', '''Dyula''': '''dyu_Latn''', '''Dzongkha''': '''dzo_Tibt''', '''Greek''': '''ell_Grek''', '''English''': '''eng_Latn''', '''Esperanto''': '''epo_Latn''', '''Estonian''': '''est_Latn''', '''Basque''': '''eus_Latn''', '''Ewe''': '''ewe_Latn''', '''Faroese''': '''fao_Latn''', '''Fijian''': '''fij_Latn''', '''Finnish''': '''fin_Latn''', '''Fon''': '''fon_Latn''', '''French''': '''fra_Latn''', '''Friulian''': '''fur_Latn''', '''Nigerian Fulfulde''': '''fuv_Latn''', '''Scottish Gaelic''': '''gla_Latn''', '''Irish''': '''gle_Latn''', '''Galician''': '''glg_Latn''', '''Guarani''': '''grn_Latn''', '''Gujarati''': '''guj_Gujr''', '''Haitian Creole''': '''hat_Latn''', '''Hausa''': '''hau_Latn''', '''Hebrew''': '''heb_Hebr''', '''Hindi''': '''hin_Deva''', '''Chhattisgarhi''': '''hne_Deva''', '''Croatian''': '''hrv_Latn''', '''Hungarian''': '''hun_Latn''', '''Armenian''': '''hye_Armn''', '''Igbo''': '''ibo_Latn''', '''Ilocano''': '''ilo_Latn''', '''Indonesian''': '''ind_Latn''', '''Icelandic''': '''isl_Latn''', '''Italian''': '''ita_Latn''', '''Javanese''': '''jav_Latn''', '''Japanese''': '''jpn_Jpan''', '''Kabyle''': '''kab_Latn''', '''Jingpho''': '''kac_Latn''', '''Kamba''': '''kam_Latn''', '''Kannada''': '''kan_Knda''', '''Kashmiri Arabic''': '''kas_Arab''', '''Kashmiri Devanagari''': '''kas_Deva''', '''Georgian''': '''kat_Geor''', '''Central Kanuri Arabic''': '''knc_Arab''', '''Central Kanuri Latin''': '''knc_Latn''', '''Kazakh''': '''kaz_Cyrl''', '''Kabiyè''': '''kbp_Latn''', '''Kabuverdianu''': '''kea_Latn''', '''Khmer''': '''khm_Khmr''', '''Kikuyu''': '''kik_Latn''', '''Kinyarwanda''': '''kin_Latn''', '''Kyrgyz''': '''kir_Cyrl''', '''Kimbundu''': '''kmb_Latn''', '''Northern Kurdish''': '''kmr_Latn''', '''Kikongo''': '''kon_Latn''', '''Korean''': '''kor_Hang''', '''Lao''': '''lao_Laoo''', '''Ligurian''': '''lij_Latn''', '''Limburgish''': '''lim_Latn''', '''Lingala''': '''lin_Latn''', '''Lithuanian''': '''lit_Latn''', '''Lombard''': '''lmo_Latn''', '''Latgalian''': '''ltg_Latn''', '''Luxembourgish''': '''ltz_Latn''', '''Luba-Kasai''': '''lua_Latn''', '''Ganda''': '''lug_Latn''', '''Luo''': '''luo_Latn''', '''Mizo''': '''lus_Latn''', '''Standard Latvian''': '''lvs_Latn''', '''Magahi''': '''mag_Deva''', '''Maithili''': '''mai_Deva''', '''Malayalam''': '''mal_Mlym''', '''Marathi''': '''mar_Deva''', '''Minangkabau Arabic ''': '''min_Arab''', '''Minangkabau Latin''': '''min_Latn''', '''Macedonian''': '''mkd_Cyrl''', '''Plateau Malagasy''': '''plt_Latn''', '''Maltese''': '''mlt_Latn''', '''Meitei Bengali''': '''mni_Beng''', '''Halh Mongolian''': '''khk_Cyrl''', '''Mossi''': '''mos_Latn''', '''Maori''': '''mri_Latn''', '''Burmese''': '''mya_Mymr''', '''Dutch''': '''nld_Latn''', '''Norwegian Nynorsk''': '''nno_Latn''', '''Norwegian Bokmål''': '''nob_Latn''', '''Nepali''': '''npi_Deva''', '''Northern Sotho''': '''nso_Latn''', '''Nuer''': '''nus_Latn''', '''Nyanja''': '''nya_Latn''', '''Occitan''': '''oci_Latn''', '''West Central Oromo''': '''gaz_Latn''', '''Odia''': '''ory_Orya''', '''Pangasinan''': '''pag_Latn''', '''Eastern Panjabi''': '''pan_Guru''', '''Papiamento''': '''pap_Latn''', '''Western Persian''': '''pes_Arab''', '''Polish''': '''pol_Latn''', '''Portuguese''': '''por_Latn''', '''Dari''': '''prs_Arab''', '''Southern Pashto''': '''pbt_Arab''', '''Ayacucho Quechua''': '''quy_Latn''', '''Romanian''': '''ron_Latn''', '''Rundi''': '''run_Latn''', '''Russian''': '''rus_Cyrl''', '''Sango''': '''sag_Latn''', '''Sanskrit''': '''san_Deva''', '''Santali''': '''sat_Olck''', '''Sicilian''': '''scn_Latn''', '''Shan''': '''shn_Mymr''', '''Sinhala''': '''sin_Sinh''', '''Slovak''': '''slk_Latn''', '''Slovenian''': '''slv_Latn''', '''Samoan''': '''smo_Latn''', '''Shona''': '''sna_Latn''', '''Sindhi''': '''snd_Arab''', '''Somali''': '''som_Latn''', '''Southern Sotho''': '''sot_Latn''', '''Spanish''': '''spa_Latn''', '''Tosk Albanian''': '''als_Latn''', '''Sardinian''': '''srd_Latn''', '''Serbian''': '''srp_Cyrl''', '''Swati''': '''ssw_Latn''', '''Sundanese''': '''sun_Latn''', '''Swedish''': '''swe_Latn''', '''Swahili''': '''swh_Latn''', '''Silesian''': '''szl_Latn''', '''Tamil''': '''tam_Taml''', '''Tatar''': '''tat_Cyrl''', '''Telugu''': '''tel_Telu''', '''Tajik''': '''tgk_Cyrl''', '''Tagalog''': '''tgl_Latn''', '''Thai''': '''tha_Thai''', '''Tigrinya''': '''tir_Ethi''', '''Tamasheq Latin''': '''taq_Latn''', '''Tamasheq Tifinagh''': '''taq_Tfng''', '''Tok Pisin''': '''tpi_Latn''', '''Tswana''': '''tsn_Latn''', '''Tsonga''': '''tso_Latn''', '''Turkmen''': '''tuk_Latn''', '''Tumbuka''': '''tum_Latn''', '''Turkish''': '''tur_Latn''', '''Twi''': '''twi_Latn''', '''Central Atlas Tamazight''': '''tzm_Tfng''', '''Uyghur''': '''uig_Arab''', '''Ukrainian''': '''ukr_Cyrl''', '''Umbundu''': '''umb_Latn''', '''Urdu''': '''urd_Arab''', '''Northern Uzbek''': '''uzn_Latn''', '''Venetian''': '''vec_Latn''', '''Vietnamese''': '''vie_Latn''', '''Waray''': '''war_Latn''', '''Wolof''': '''wol_Latn''', '''Xhosa''': '''xho_Latn''', '''Eastern Yiddish''': '''ydd_Hebr''', '''Yoruba''': '''yor_Latn''', '''Yue Chinese''': '''yue_Hant''', '''Chinese Simplified''': '''zho_Hans''', '''Chinese Traditional''': '''zho_Hant''', '''Standard Malay''': '''zsm_Latn''', '''Zulu''': '''zul_Latn''', } class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[str] = 'facebook/nllb-200-distilled-600M' lowercase : Union[str, Any] = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) lowercase : List[str] = 'translator' lowercase : Union[str, Any] = AutoTokenizer lowercase : List[str] = AutoModelForSeqaSeqLM lowercase : List[str] = LANGUAGE_CODES lowercase : int = ['text', 'text', 'text'] lowercase : List[str] = ['text'] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) UpperCamelCase : str = self.lang_to_code[src_lang] UpperCamelCase : Optional[int] = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.model.generate(**SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
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 argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": __A : List[Any] = argparse.ArgumentParser( description=( '''Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned''' ''' Distillation''' ) ) parser.add_argument('''--model_type''', default='''roberta''', choices=['''roberta''', '''gpt2''']) parser.add_argument('''--model_name''', default='''roberta-large''', type=str) parser.add_argument('''--dump_checkpoint''', default='''serialization_dir/tf_roberta_048131723.pth''', type=str) parser.add_argument('''--vocab_transform''', action='''store_true''') __A : int = parser.parse_args() if args.model_type == "roberta": __A : int = RobertaForMaskedLM.from_pretrained(args.model_name) __A : Tuple = '''roberta''' elif args.model_type == "gpt2": __A : Optional[int] = GPTaLMHeadModel.from_pretrained(args.model_name) __A : Dict = '''transformer''' __A : Tuple = model.state_dict() __A : Any = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: __A : Tuple = state_dict[F'''{prefix}.{param_name}'''] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: __A : Tuple = F'''{prefix}.embeddings.{w}.weight''' __A : Optional[int] = state_dict[param_name] for w in ["weight", "bias"]: __A : Optional[Any] = F'''{prefix}.embeddings.LayerNorm.{w}''' __A : Optional[int] = state_dict[param_name] # Transformer Blocks # __A : int = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: __A : int = state_dict[ F'''{prefix}.h.{teacher_idx}.{layer}.{w}''' ] __A : Optional[Any] = state_dict[F'''{prefix}.h.{teacher_idx}.attn.bias'''] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: __A : Dict = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}''' ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: __A : Any = state_dict[F'''{layer}'''] if args.vocab_transform: for w in ["weight", "bias"]: __A : Dict = state_dict[F'''lm_head.dense.{w}'''] __A : List[Any] = state_dict[F'''lm_head.layer_norm.{w}'''] elif args.model_type == "gpt2": for w in ["weight", "bias"]: __A : List[Any] = state_dict[F'''{prefix}.ln_f.{w}'''] __A : Tuple = state_dict['''lm_head.weight'''] print(F'''N layers selected for distillation: {std_idx}''') print(F'''Number of params transferred for distillation: {len(compressed_sd.keys())}''') print(F'''Save transferred checkpoint to {args.dump_checkpoint}.''') torch.save(compressed_sd, args.dump_checkpoint)
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 json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __A : Tuple = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ '''text-classification''', '''language-modeling''', '''summarization''', '''token-classification''', '''question-answering''', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __A : str = logging.getLogger() def A_ ( ): '''simple docstring''' UpperCamelCase : int = argparse.ArgumentParser() parser.add_argument("""-f""" ) UpperCamelCase : Tuple = parser.parse_args() return args.f def A_ ( snake_case_ : str ,snake_case_ : Optional[int]="eval" ): '''simple docstring''' UpperCamelCase : str = os.path.join(snake_case_ ,f'{split}_results.json' ) if os.path.exists(snake_case_ ): with open(snake_case_ ,"""r""" ) as f: return json.load(snake_case_ ) raise ValueError(f'can\'t find {path}' ) __A : Any = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowerCamelCase ( _UpperCAmelCase ): def a_ ( self ): UpperCamelCase : Union[str, Any] = self.get_auto_remove_tmp_dir() UpperCamelCase : str = f'\n run_glue.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --eval_steps=2\n --warmup_steps=2\n --seed=42\n --max_seq_length=128\n '.split() with patch.object(SCREAMING_SNAKE_CASE_ , """argv""" , SCREAMING_SNAKE_CASE_ ): run_flax_glue.main() UpperCamelCase : List[Any] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 ) @slow def a_ ( self ): UpperCamelCase : Optional[int] = self.get_auto_remove_tmp_dir() UpperCamelCase : Dict = f'\n run_clm_flax.py\n --model_name_or_path distilgpt2\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --do_train\n --do_eval\n --block_size 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --num_train_epochs 2\n --logging_steps 2 --eval_steps 2\n --output_dir {tmp_dir}\n --overwrite_output_dir\n '.split() with patch.object(SCREAMING_SNAKE_CASE_ , """argv""" , SCREAMING_SNAKE_CASE_ ): run_clm_flax.main() UpperCamelCase : Tuple = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result["""eval_perplexity"""] , 100 ) @slow def a_ ( self ): UpperCamelCase : List[Any] = self.get_auto_remove_tmp_dir() UpperCamelCase : Union[str, Any] = f'\n run_summarization.py\n --model_name_or_path t5-small\n --train_file tests/fixtures/tests_samples/xsum/sample.json\n --validation_file tests/fixtures/tests_samples/xsum/sample.json\n --test_file tests/fixtures/tests_samples/xsum/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --num_train_epochs=3\n --warmup_steps=8\n --do_train\n --do_eval\n --do_predict\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --predict_with_generate\n '.split() with patch.object(SCREAMING_SNAKE_CASE_ , """argv""" , SCREAMING_SNAKE_CASE_ ): run_summarization_flax.main() UpperCamelCase : Union[str, Any] = get_results(SCREAMING_SNAKE_CASE_ , split="""test""" ) self.assertGreaterEqual(result["""test_rouge1"""] , 10 ) self.assertGreaterEqual(result["""test_rouge2"""] , 2 ) self.assertGreaterEqual(result["""test_rougeL"""] , 7 ) self.assertGreaterEqual(result["""test_rougeLsum"""] , 7 ) @slow def a_ ( self ): UpperCamelCase : Any = self.get_auto_remove_tmp_dir() UpperCamelCase : Optional[int] = f'\n run_mlm.py\n --model_name_or_path distilroberta-base\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --max_seq_length 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --logging_steps 2 --eval_steps 2\n --do_train\n --do_eval\n --num_train_epochs=1\n '.split() with patch.object(SCREAMING_SNAKE_CASE_ , """argv""" , SCREAMING_SNAKE_CASE_ ): run_mlm_flax.main() UpperCamelCase : Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result["""eval_perplexity"""] , 42 ) @slow def a_ ( self ): UpperCamelCase : Any = self.get_auto_remove_tmp_dir() UpperCamelCase : Optional[Any] = f'\n run_t5_mlm_flax.py\n --model_name_or_path t5-small\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --do_train\n --do_eval\n --max_seq_length 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --num_train_epochs 2\n --logging_steps 2 --eval_steps 2\n --output_dir {tmp_dir}\n --overwrite_output_dir\n '.split() with patch.object(SCREAMING_SNAKE_CASE_ , """argv""" , SCREAMING_SNAKE_CASE_ ): run_ta_mlm_flax.main() UpperCamelCase : int = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.42 ) @slow def a_ ( self ): # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCamelCase : List[str] = 7 if get_gpu_count() > 1 else 2 UpperCamelCase : Tuple = self.get_auto_remove_tmp_dir() UpperCamelCase : Optional[int] = f'\n run_flax_ner.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/conll/sample.json\n --validation_file tests/fixtures/tests_samples/conll/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --do_train\n --do_eval\n --warmup_steps=2\n --learning_rate=2e-4\n --logging_steps 2 --eval_steps 2\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=2\n --num_train_epochs={epochs}\n --seed 7\n '.split() with patch.object(SCREAMING_SNAKE_CASE_ , """argv""" , SCREAMING_SNAKE_CASE_ ): run_flax_ner.main() UpperCamelCase : Optional[Any] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 ) self.assertGreaterEqual(result["""eval_f1"""] , 0.3 ) @slow def a_ ( self ): UpperCamelCase : List[str] = self.get_auto_remove_tmp_dir() UpperCamelCase : Union[str, Any] = f'\n run_qa.py\n --model_name_or_path bert-base-uncased\n --version_2_with_negative\n --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --num_train_epochs=3\n --warmup_steps=2\n --do_train\n --do_eval\n --logging_steps 2 --eval_steps 2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n '.split() with patch.object(SCREAMING_SNAKE_CASE_ , """argv""" , SCREAMING_SNAKE_CASE_ ): run_qa.main() UpperCamelCase : int = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result["""eval_f1"""] , 30 ) self.assertGreaterEqual(result["""eval_exact"""] , 30 )
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""" from __future__ import annotations import time import numpy as np __A : List[Any] = [8, 5, 9, 7] __A : Union[str, Any] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] __A : str = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Union[str, Any] = claim_vector UpperCamelCase : Dict = allocated_resources_table UpperCamelCase : Tuple = maximum_claim_table def a_ ( self ): return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def a_ ( self ): return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def a_ ( self ): return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(SCREAMING_SNAKE_CASE_ ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def a_ ( self ): return {self.__need().index(SCREAMING_SNAKE_CASE_ ): i for i in self.__need()} def a_ ( self , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = self.__need() UpperCamelCase : Any = self.__allocated_resources_table UpperCamelCase : Tuple = self.__available_resources() UpperCamelCase : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("""_""" * 50 + """\n""" ) while need_list: UpperCamelCase : Optional[Any] = False for each_need in need_list: UpperCamelCase : Any = True for index, need in enumerate(SCREAMING_SNAKE_CASE_ ): if need > available_resources[index]: UpperCamelCase : Any = False break if execution: UpperCamelCase : Dict = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: UpperCamelCase : Tuple = original_need_index print(f'Process {process_number + 1} is executing.' ) # remove the process run from stack need_list.remove(SCREAMING_SNAKE_CASE_ ) # update available/freed resources stack UpperCamelCase : Dict = np.array(SCREAMING_SNAKE_CASE_ ) + np.array( alloc_resources_table[process_number] ) print( """Updated available resource stack for processes: """ + """ """.join([str(SCREAMING_SNAKE_CASE_ ) for x in available_resources] ) ) break if safe: print("""The process is in a safe state.\n""" ) else: print("""System in unsafe state. Aborting...\n""" ) break def a_ ( self ): print(""" """ * 9 + """Allocated Resource Table""" ) for item in self.__allocated_resources_table: print( f'P{self.__allocated_resources_table.index(SCREAMING_SNAKE_CASE_ ) + 1}' + """ """.join(f'{it:>8}' for it in item ) + """\n""" ) print(""" """ * 9 + """System Resource Table""" ) for item in self.__maximum_claim_table: print( f'P{self.__maximum_claim_table.index(SCREAMING_SNAKE_CASE_ ) + 1}' + """ """.join(f'{it:>8}' for it in item ) + """\n""" ) print( """Current Usage by Active Processes: """ + """ """.join(str(SCREAMING_SNAKE_CASE_ ) for x in self.__claim_vector ) ) print( """Initial Available Resources: """ + """ """.join(str(SCREAMING_SNAKE_CASE_ ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
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""" def A_ ( snake_case_ : str ): '''simple docstring''' if not all(char in """01""" for char in bin_string ): raise ValueError("""Non-binary value was passed to the function""" ) if not bin_string: raise ValueError("""Empty string was passed to the function""" ) UpperCamelCase : Any = """""" while len(snake_case_ ) % 3 != 0: UpperCamelCase : List[str] = """0""" + bin_string UpperCamelCase : Tuple = [ bin_string[index : index + 3] for index in range(len(snake_case_ ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: UpperCamelCase : int = 0 for index, val in enumerate(snake_case_ ): oct_val += int(2 ** (2 - index) * int(snake_case_ ) ) oct_string += str(snake_case_ ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
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 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
"""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 os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __A : Any = logging.get_logger(__name__) __A : Optional[Any] = {'''vocab_file''': '''spiece.model'''} __A : Any = { '''vocab_file''': { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/spiece.model''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/spiece.model''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/spiece.model''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model''', } } __A : int = { '''albert-base-v1''': 512, '''albert-large-v1''': 512, '''albert-xlarge-v1''': 512, '''albert-xxlarge-v1''': 512, '''albert-base-v2''': 512, '''albert-large-v2''': 512, '''albert-xlarge-v2''': 512, '''albert-xxlarge-v2''': 512, } __A : List[str] = '''▁''' class lowerCamelCase ( _UpperCAmelCase ): lowercase : int = VOCAB_FILES_NAMES lowercase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP lowercase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_="[MASK]" , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. UpperCamelCase : Any = ( AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ , normalized=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__( do_lower_case=SCREAMING_SNAKE_CASE_ , remove_space=SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = do_lower_case UpperCamelCase : Any = remove_space UpperCamelCase : str = keep_accents UpperCamelCase : Union[str, Any] = vocab_file UpperCamelCase : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE_ ) @property def a_ ( self ): return len(self.sp_model ) def a_ ( self ): UpperCamelCase : Tuple = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): UpperCamelCase : List[Any] = self.__dict__.copy() UpperCamelCase : int = None return state def __setstate__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): UpperCamelCase : Optional[Any] = {} UpperCamelCase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): if self.remove_space: UpperCamelCase : Tuple = """ """.join(inputs.strip().split() ) else: UpperCamelCase : List[str] = inputs UpperCamelCase : List[Any] = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: UpperCamelCase : List[Any] = unicodedata.normalize("""NFKD""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = """""".join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE_ )] ) if self.do_lower_case: UpperCamelCase : Any = outputs.lower() return outputs def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = self.preprocess_text(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.sp_model.encode(SCREAMING_SNAKE_CASE_ , out_type=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): UpperCamelCase : Union[str, Any] = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: UpperCamelCase : List[Any] = cur_pieces[1:] else: UpperCamelCase : Optional[int] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(SCREAMING_SNAKE_CASE_ ) else: new_pieces.append(SCREAMING_SNAKE_CASE_ ) return new_pieces def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = [] UpperCamelCase : Optional[int] = """""" UpperCamelCase : Optional[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE_ ) + token UpperCamelCase : Dict = True UpperCamelCase : Union[str, Any] = [] 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_ = None ): UpperCamelCase : List[Any] = [self.sep_token_id] UpperCamelCase : Dict = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def 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 not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : List[Any] = [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] 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 : 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 : Tuple = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE_ ) return (out_vocab_file,)
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 requests __A : List[Any] = '''''' # <-- Put your OpenWeatherMap appid here! __A : Tuple = '''https://api.openweathermap.org/data/2.5/''' def A_ ( snake_case_ : str = "Chicago" ,snake_case_ : str = APPID ): '''simple docstring''' return requests.get(URL_BASE + """weather""" ,params=locals() ).json() def A_ ( snake_case_ : str = "Kolkata, India" ,snake_case_ : str = APPID ): '''simple docstring''' return requests.get(URL_BASE + """forecast""" ,params=locals() ).json() def A_ ( snake_case_ : float = 55.68 ,snake_case_ : float = 12.57 ,snake_case_ : str = APPID ): '''simple docstring''' return requests.get(URL_BASE + """onecall""" ,params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __A : Optional[int] = input('''Enter a location:''').strip() if location: pprint(current_weather(location)) else: break
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 contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging __A : Optional[int] = logging.get_logger(__name__) class lowerCamelCase : lowercase : List[str] = None @experimental def A_ ( snake_case_ : Dict ,snake_case_ : Tuple ,snake_case_ : Any ,snake_case_ : str ,snake_case_ : Union[str, Any] ,snake_case_ : List[Any] ,snake_case_ : Optional[int] ): '''simple docstring''' if ParallelBackendConfig.backend_name is None: return _map_with_multiprocessing_pool( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) return _map_with_joblib(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) def A_ ( snake_case_ : List[str] ,snake_case_ : str ,snake_case_ : str ,snake_case_ : List[str] ,snake_case_ : Optional[int] ,snake_case_ : Optional[Any] ,snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : Optional[int] = num_proc if num_proc <= len(snake_case_ ) else len(snake_case_ ) UpperCamelCase : List[Any] = [] # We organize the splits ourselve (contiguous splits) for index in range(snake_case_ ): UpperCamelCase : Union[str, Any] = len(snake_case_ ) // num_proc UpperCamelCase : Optional[Any] = len(snake_case_ ) % num_proc UpperCamelCase : str = div * index + min(snake_case_ ,snake_case_ ) UpperCamelCase : int = start + div + (1 if index < mod else 0) split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc) ) if len(snake_case_ ) != sum(len(i[1] ) for i in split_kwds ): raise ValueError( f'Error dividing inputs iterable among processes. ' f'Total number of objects {len(snake_case_ )}, ' f'length: {sum(len(i[1] ) for i in split_kwds )}' ) logger.info( f'Spawning {num_proc} processes for {len(snake_case_ )} objects in slices of {[len(i[1] ) for i in split_kwds]}' ) UpperCamelCase , UpperCamelCase : Optional[int] = None, None if not disable_tqdm: UpperCamelCase , UpperCamelCase : List[str] = (RLock(),), tqdm.set_lock with Pool(snake_case_ ,initargs=snake_case_ ,initializer=snake_case_ ) as pool: UpperCamelCase : Optional[int] = pool.map(snake_case_ ,snake_case_ ) logger.info(f'Finished {num_proc} processes' ) UpperCamelCase : Optional[int] = [obj for proc_res in mapped for obj in proc_res] logger.info(f'Unpacked {len(snake_case_ )} objects' ) return mapped def A_ ( snake_case_ : Tuple ,snake_case_ : int ,snake_case_ : str ,snake_case_ : List[Any] ,snake_case_ : Any ,snake_case_ : Tuple ,snake_case_ : int ): '''simple docstring''' # progress bar is not yet supported for _map_with_joblib, because tqdm couldn't accurately be applied to joblib, # and it requires monkey-patching joblib internal classes which is subject to change import joblib with joblib.parallel_backend(ParallelBackendConfig.backend_name ,n_jobs=snake_case_ ): return joblib.Parallel()( joblib.delayed(snake_case_ )((function, obj, types, None, True, None) ) for obj in iterable ) @experimental @contextlib.contextmanager def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[str] = backend_name if backend_name == "spark": from joblibspark import register_spark register_spark() # TODO: call create_cache_and_write_probe if "download" in steps # TODO: raise NotImplementedError when Dataset.map etc is called try: yield finally: UpperCamelCase : List[Any] = None
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 __future__ import annotations import math import random from typing import Any class lowerCamelCase : def __init__( self ): UpperCamelCase : list[Any] = [] UpperCamelCase : int = 0 UpperCamelCase : int = 0 def a_ ( self ): return self.head == self.tail def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.data.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = self.tail + 1 def a_ ( self ): UpperCamelCase : List[str] = self.data[self.head] UpperCamelCase : Optional[Any] = self.head + 1 return ret def a_ ( self ): return self.tail - self.head def a_ ( self ): print(self.data ) print("""**************""" ) print(self.data[self.head : self.tail] ) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = data UpperCamelCase : MyNode | None = None UpperCamelCase : MyNode | None = None UpperCamelCase : int = 1 def a_ ( self ): return self.data def a_ ( self ): return self.left def a_ ( self ): return self.right def a_ ( self ): return self.height def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = data def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = node def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = node def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = height def A_ ( snake_case_ : MyNode | None ): '''simple docstring''' if node is None: return 0 return node.get_height() def A_ ( snake_case_ : int ,snake_case_ : int ): '''simple docstring''' if a > b: return a return b def A_ ( snake_case_ : MyNode ): '''simple docstring''' print("""left rotation node:""" ,node.get_data() ) UpperCamelCase : Optional[int] = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(snake_case_ ) UpperCamelCase : int = my_max(get_height(node.get_right() ) ,get_height(node.get_left() ) ) + 1 node.set_height(snake_case_ ) UpperCamelCase : List[Any] = my_max(get_height(ret.get_right() ) ,get_height(ret.get_left() ) ) + 1 ret.set_height(snake_case_ ) return ret def A_ ( snake_case_ : MyNode ): '''simple docstring''' print("""right rotation node:""" ,node.get_data() ) UpperCamelCase : Tuple = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(snake_case_ ) UpperCamelCase : Union[str, Any] = my_max(get_height(node.get_right() ) ,get_height(node.get_left() ) ) + 1 node.set_height(snake_case_ ) UpperCamelCase : Optional[int] = my_max(get_height(ret.get_right() ) ,get_height(ret.get_left() ) ) + 1 ret.set_height(snake_case_ ) return ret def A_ ( snake_case_ : MyNode ): '''simple docstring''' UpperCamelCase : Any = node.get_left() assert left_child is not None node.set_left(left_rotation(snake_case_ ) ) return right_rotation(snake_case_ ) def A_ ( snake_case_ : MyNode ): '''simple docstring''' UpperCamelCase : List[Any] = node.get_right() assert right_child is not None node.set_right(right_rotation(snake_case_ ) ) return left_rotation(snake_case_ ) def A_ ( snake_case_ : MyNode | None ,snake_case_ : Any ): '''simple docstring''' if node is None: return MyNode(snake_case_ ) if data < node.get_data(): node.set_left(insert_node(node.get_left() ,snake_case_ ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected UpperCamelCase : Any = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child UpperCamelCase : Optional[int] = right_rotation(snake_case_ ) else: UpperCamelCase : str = lr_rotation(snake_case_ ) else: node.set_right(insert_node(node.get_right() ,snake_case_ ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: UpperCamelCase : int = node.get_right() assert right_child is not None if data < right_child.get_data(): UpperCamelCase : str = rl_rotation(snake_case_ ) else: UpperCamelCase : Union[str, Any] = left_rotation(snake_case_ ) UpperCamelCase : str = my_max(get_height(node.get_right() ) ,get_height(node.get_left() ) ) + 1 node.set_height(snake_case_ ) return node def A_ ( snake_case_ : MyNode ): '''simple docstring''' while True: UpperCamelCase : List[str] = root.get_right() if right_child is None: break UpperCamelCase : int = right_child return root.get_data() def A_ ( snake_case_ : MyNode ): '''simple docstring''' while True: UpperCamelCase : str = root.get_left() if left_child is None: break UpperCamelCase : str = left_child return root.get_data() def A_ ( snake_case_ : MyNode ,snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Any = root.get_left() UpperCamelCase : str = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: UpperCamelCase : Tuple = get_left_most(snake_case_ ) root.set_data(snake_case_ ) root.set_right(del_node(snake_case_ ,snake_case_ ) ) elif left_child is not None: UpperCamelCase : List[str] = left_child elif right_child is not None: UpperCamelCase : Optional[Any] = right_child else: return None elif root.get_data() > data: if left_child is None: print("""No such data""" ) return root else: root.set_left(del_node(snake_case_ ,snake_case_ ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(snake_case_ ,snake_case_ ) ) if get_height(snake_case_ ) - get_height(snake_case_ ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): UpperCamelCase : str = left_rotation(snake_case_ ) else: UpperCamelCase : List[Any] = rl_rotation(snake_case_ ) elif get_height(snake_case_ ) - get_height(snake_case_ ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): UpperCamelCase : Optional[Any] = right_rotation(snake_case_ ) else: UpperCamelCase : str = lr_rotation(snake_case_ ) UpperCamelCase : Any = my_max(get_height(root.get_right() ) ,get_height(root.get_left() ) ) + 1 root.set_height(snake_case_ ) return root class lowerCamelCase : def __init__( self ): UpperCamelCase : MyNode | None = None def a_ ( self ): return get_height(self.root ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): print("""insert:""" + str(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Any = insert_node(self.root , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): print("""delete:""" + str(SCREAMING_SNAKE_CASE_ ) ) if self.root is None: print("""Tree is empty!""" ) return UpperCamelCase : Tuple = del_node(self.root , SCREAMING_SNAKE_CASE_ ) def __str__( self , ): # a level traversale, gives a more intuitive look on the tree UpperCamelCase : Union[str, Any] = """""" UpperCamelCase : Any = MyQueue() q.push(self.root ) UpperCamelCase : str = self.get_height() if layer == 0: return output UpperCamelCase : Any = 0 while not q.is_empty(): UpperCamelCase : Tuple = q.pop() UpperCamelCase : List[str] = """ """ * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(SCREAMING_SNAKE_CASE_ ) q.push(SCREAMING_SNAKE_CASE_ ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space UpperCamelCase : str = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , SCREAMING_SNAKE_CASE_ ) - 1: UpperCamelCase : Tuple = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def A_ ( ): '''simple docstring''' import doctest doctest.testmod() if __name__ == "__main__": _test() __A : str = AVLtree() __A : List[str] = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
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 json import sys def A_ ( snake_case_ : List[Any] ,snake_case_ : Union[str, Any] ): '''simple docstring''' with open(snake_case_ ,encoding="""utf-8""" ) as f: UpperCamelCase : Optional[int] = json.load(snake_case_ ) UpperCamelCase : Dict = ["""<details>""", """<summary>Show updated benchmarks!</summary>""", """ """] for benchmark_name in sorted(snake_case_ ): UpperCamelCase : Tuple = results[benchmark_name] UpperCamelCase : Optional[Any] = benchmark_name.split("""/""" )[-1] output_md.append(f'### Benchmark: {benchmark_file_name}' ) UpperCamelCase : List[str] = """| metric |""" UpperCamelCase : Optional[Any] = """|--------|""" UpperCamelCase : int = """| new / old (diff) |""" for metric_name in sorted(snake_case_ ): UpperCamelCase : Dict = benchmark_res[metric_name] UpperCamelCase : Any = metric_vals["""new"""] UpperCamelCase : Tuple = metric_vals.get("""old""" ,snake_case_ ) UpperCamelCase : Optional[Any] = metric_vals.get("""diff""" ,snake_case_ ) UpperCamelCase : Tuple = f' {new_val:f}' if isinstance(snake_case_ ,(int, float) ) else """None""" if old_val is not None: val_str += f' / {old_val:f}' if isinstance(snake_case_ ,(int, float) ) else "None" if dif_val is not None: val_str += f' ({dif_val:f})' if isinstance(snake_case_ ,(int, float) ) else "None" title += " " + metric_name + " |" lines += "---|" value += val_str + " |" output_md += [title, lines, value, " "] output_md.append("""</details>""" ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.writelines("""\n""".join(snake_case_ ) ) if __name__ == "__main__": __A : Optional[Any] = sys.argv[1] __A : List[str] = sys.argv[2] format_json_to_md(input_json_file, output_md_file)
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""" # # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def A_ ( *snake_case_ : Optional[int] ): '''simple docstring''' with open(snake_case_ ,"""r""" ) as fh: fcntl.flock(snake_case_ ,fcntl.LOCK_EX ) try: print(*snake_case_ ) finally: fcntl.flock(snake_case_ ,fcntl.LOCK_UN ) __A : Optional[Any] = int(os.environ['''LOCAL_RANK''']) torch.cuda.set_device(local_rank) __A : Optional[int] = torch.device('''cuda''', local_rank) __A : List[str] = socket.gethostname() __A : Optional[Any] = F'''[{hostname}-{local_rank}]''' try: # test distributed dist.init_process_group('''nccl''') dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank __A : List[Any] = dist.get_rank() __A : List[str] = dist.get_world_size() printflock(F'''{gpu} is OK (global rank: {rank}/{world_size})''') dist.barrier() if rank == 0: printflock(F'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''') except Exception: printflock(F'''{gpu} is broken''') raise
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""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def A_ ( snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : int = create_tensor(snake_case_ ) UpperCamelCase : str = gather(snake_case_ ) assert gathered_tensor.tolist() == list(range(1 ,state.num_processes**2 + 1 ) ) def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : int = [state.process_index] UpperCamelCase : Optional[int] = gather_object(snake_case_ ) assert len(snake_case_ ) == state.num_processes, f'{gathered_obj}, {len(snake_case_ )} != {state.num_processes}' assert gathered_obj == list(range(state.num_processes ) ), f'{gathered_obj} != {list(range(state.num_processes ) )}' def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : List[Any] = create_tensor(snake_case_ ) UpperCamelCase : Tuple = broadcast(snake_case_ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 ,state.num_processes + 1 ) ) def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' # We need to pad the tensor with one more element if we are the main process # to ensure that we can pad if state.is_main_process: UpperCamelCase : Tuple = torch.arange(state.num_processes + 1 ).to(state.device ) else: UpperCamelCase : Union[str, Any] = torch.arange(state.num_processes ).to(state.device ) UpperCamelCase : Dict = pad_across_processes(snake_case_ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 ,state.num_processes ) ) + [0] def A_ ( snake_case_ : str ): '''simple docstring''' # For now runs on only two processes if state.num_processes != 2: return UpperCamelCase : Tuple = create_tensor(snake_case_ ) UpperCamelCase : Dict = reduce(snake_case_ ,"""sum""" ) UpperCamelCase : Dict = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(snake_case_ ,snake_case_ ), f'{reduced_tensor} != {truth_tensor}' def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' # For now runs on only two processes if state.num_processes != 2: return UpperCamelCase : Optional[Any] = create_tensor(snake_case_ ) UpperCamelCase : int = reduce(snake_case_ ,"""mean""" ) UpperCamelCase : List[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(snake_case_ ,snake_case_ ), f'{reduced_tensor} != {truth_tensor}' def A_ ( snake_case_ : str ): '''simple docstring''' # For xla_spawn (TPUs) main() def A_ ( ): '''simple docstring''' UpperCamelCase : Any = PartialState() state.print(f'State: {state}' ) state.print("""testing gather""" ) test_gather(snake_case_ ) state.print("""testing gather_object""" ) test_gather_object(snake_case_ ) state.print("""testing broadcast""" ) test_broadcast(snake_case_ ) state.print("""testing pad_across_processes""" ) test_pad_across_processes(snake_case_ ) state.print("""testing reduce_sum""" ) test_reduce_sum(snake_case_ ) state.print("""testing reduce_mean""" ) test_reduce_mean(snake_case_ ) if __name__ == "__main__": main()
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 unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class lowerCamelCase ( unittest.TestCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=18 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=400 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=[0.48145466, 0.4578275, 0.40821073] , SCREAMING_SNAKE_CASE_=[0.26862954, 0.26130258, 0.27577711] , SCREAMING_SNAKE_CASE_=True , ): UpperCamelCase : List[str] = size if size is not None else {"""height""": 224, """width""": 224} UpperCamelCase : str = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} UpperCamelCase : Tuple = parent UpperCamelCase : Any = batch_size UpperCamelCase : Optional[int] = num_channels UpperCamelCase : Optional[Any] = image_size UpperCamelCase : str = min_resolution UpperCamelCase : Any = max_resolution UpperCamelCase : List[Any] = do_resize UpperCamelCase : str = size UpperCamelCase : Union[str, Any] = do_center_crop UpperCamelCase : Optional[int] = crop_size UpperCamelCase : Any = do_normalize UpperCamelCase : Optional[Any] = image_mean UpperCamelCase : str = image_std UpperCamelCase : List[str] = do_convert_rgb def a_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def a_ ( self , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False ): assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: UpperCamelCase : Tuple = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: UpperCamelCase : str = [] for i in range(self.batch_size ): UpperCamelCase , UpperCamelCase : Tuple = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension UpperCamelCase : List[str] = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE_ , 0 , -1 ) ) for x in image_inputs] if torchify: UpperCamelCase : Optional[int] = [torch.from_numpy(SCREAMING_SNAKE_CASE_ ) for x in image_inputs] return image_inputs @require_torch @require_vision class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : str = ChineseCLIPImageProcessor if is_vision_available() else None def a_ ( self ): UpperCamelCase : Any = ChineseCLIPImageProcessingTester(self , do_center_crop=SCREAMING_SNAKE_CASE_ ) @property def a_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a_ ( self ): UpperCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_resize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """size""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_center_crop""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """center_crop""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_normalize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_mean""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_std""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_convert_rgb""" ) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 224, """width""": 224} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) UpperCamelCase : Any = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def a_ ( self ): pass def a_ ( self ): # Initialize image_processing UpperCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input UpperCamelCase : List[Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCamelCase : List[Any] = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def a_ ( self ): # Initialize image_processing UpperCamelCase : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase : Dict = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE_ , numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) # Test not batched input UpperCamelCase : Optional[int] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCamelCase : str = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def a_ ( self ): # Initialize image_processing UpperCamelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE_ , torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) # Test not batched input UpperCamelCase : Dict = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCamelCase : Union[str, Any] = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) @require_torch @require_vision class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : List[Any] = ChineseCLIPImageProcessor if is_vision_available() else None def a_ ( self ): UpperCamelCase : List[str] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = 3 @property def a_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a_ ( self ): UpperCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_resize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """size""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_center_crop""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """center_crop""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_normalize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_mean""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """image_std""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_convert_rgb""" ) ) def a_ ( self ): pass def a_ ( self ): # Initialize image_processing UpperCamelCase : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase : int = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input UpperCamelCase : Dict = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCamelCase : str = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
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 numpy as np def A_ ( snake_case_ : np.array ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": 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 argparse import struct import unittest class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = data # Initialize hash values UpperCamelCase : Union[str, Any] = [ 0X6a_09_e6_67, 0Xbb_67_ae_85, 0X3c_6e_f3_72, 0Xa5_4f_f5_3a, 0X51_0e_52_7f, 0X9b_05_68_8c, 0X1f_83_d9_ab, 0X5b_e0_cd_19, ] # Initialize round constants UpperCamelCase : List[Any] = [ 0X42_8a_2f_98, 0X71_37_44_91, 0Xb5_c0_fb_cf, 0Xe9_b5_db_a5, 0X39_56_c2_5b, 0X59_f1_11_f1, 0X92_3f_82_a4, 0Xab_1c_5e_d5, 0Xd8_07_aa_98, 0X12_83_5b_01, 0X24_31_85_be, 0X55_0c_7d_c3, 0X72_be_5d_74, 0X80_de_b1_fe, 0X9b_dc_06_a7, 0Xc1_9b_f1_74, 0Xe4_9b_69_c1, 0Xef_be_47_86, 0X0f_c1_9d_c6, 0X24_0c_a1_cc, 0X2d_e9_2c_6f, 0X4a_74_84_aa, 0X5c_b0_a9_dc, 0X76_f9_88_da, 0X98_3e_51_52, 0Xa8_31_c6_6d, 0Xb0_03_27_c8, 0Xbf_59_7f_c7, 0Xc6_e0_0b_f3, 0Xd5_a7_91_47, 0X06_ca_63_51, 0X14_29_29_67, 0X27_b7_0a_85, 0X2e_1b_21_38, 0X4d_2c_6d_fc, 0X53_38_0d_13, 0X65_0a_73_54, 0X76_6a_0a_bb, 0X81_c2_c9_2e, 0X92_72_2c_85, 0Xa2_bf_e8_a1, 0Xa8_1a_66_4b, 0Xc2_4b_8b_70, 0Xc7_6c_51_a3, 0Xd1_92_e8_19, 0Xd6_99_06_24, 0Xf4_0e_35_85, 0X10_6a_a0_70, 0X19_a4_c1_16, 0X1e_37_6c_08, 0X27_48_77_4c, 0X34_b0_bc_b5, 0X39_1c_0c_b3, 0X4e_d8_aa_4a, 0X5b_9c_ca_4f, 0X68_2e_6f_f3, 0X74_8f_82_ee, 0X78_a5_63_6f, 0X84_c8_78_14, 0X8c_c7_02_08, 0X90_be_ff_fa, 0Xa4_50_6c_eb, 0Xbe_f9_a3_f7, 0Xc6_71_78_f2, ] UpperCamelCase : Dict = self.preprocessing(self.data ) self.final_hash() @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = b"""\x80""" + (b"""\x00""" * (63 - (len(SCREAMING_SNAKE_CASE_ ) + 8) % 64)) UpperCamelCase : Any = struct.pack(""">Q""" , (len(SCREAMING_SNAKE_CASE_ ) * 8) ) return data + padding + big_endian_integer def a_ ( self ): # Convert into blocks of 64 bytes UpperCamelCase : int = [ self.preprocessed_data[x : x + 64] for x in range(0 , len(self.preprocessed_data ) , 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers UpperCamelCase : Tuple = list(struct.unpack(""">16L""" , SCREAMING_SNAKE_CASE_ ) ) # add 48 0-ed integers words += [0] * 48 UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Any = self.hashes for index in range(0 , 64 ): if index > 15: # modify the zero-ed indexes at the end of the array UpperCamelCase : Tuple = ( self.ror(words[index - 15] , 7 ) ^ self.ror(words[index - 15] , 18 ) ^ (words[index - 15] >> 3) ) UpperCamelCase : str = ( self.ror(words[index - 2] , 17 ) ^ self.ror(words[index - 2] , 19 ) ^ (words[index - 2] >> 10) ) UpperCamelCase : int = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_00_00_00_00 # Compression UpperCamelCase : Optional[int] = self.ror(SCREAMING_SNAKE_CASE_ , 6 ) ^ self.ror(SCREAMING_SNAKE_CASE_ , 11 ) ^ self.ror(SCREAMING_SNAKE_CASE_ , 25 ) UpperCamelCase : Optional[int] = (e & f) ^ ((~e & 0Xff_ff_ff_ff) & g) UpperCamelCase : Any = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_00_00_00_00 UpperCamelCase : Optional[Any] = self.ror(SCREAMING_SNAKE_CASE_ , 2 ) ^ self.ror(SCREAMING_SNAKE_CASE_ , 13 ) ^ self.ror(SCREAMING_SNAKE_CASE_ , 22 ) UpperCamelCase : Any = (a & b) ^ (a & c) ^ (b & c) UpperCamelCase : Dict = (sa + maj) % 0X1_00_00_00_00 UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : str = ( g, f, e, ((d + tempa) % 0X1_00_00_00_00), c, b, a, ((tempa + tempa) % 0X1_00_00_00_00), ) UpperCamelCase : List[Any] = [a, b, c, d, e, f, g, h] # Modify final values UpperCamelCase : Union[str, Any] = [ ((element + mutated_hash_values[index]) % 0X1_00_00_00_00) for index, element in enumerate(self.hashes ) ] UpperCamelCase : Dict = """""".join([hex(SCREAMING_SNAKE_CASE_ )[2:].zfill(8 ) for value in self.hashes] ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return 0Xff_ff_ff_ff & (value << (32 - rotations)) | (value >> rotations) class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): import hashlib UpperCamelCase : str = bytes("""Test String""" , """utf-8""" ) self.assertEqual(SHAaaa(SCREAMING_SNAKE_CASE_ ).hash , hashlib.shaaaa(SCREAMING_SNAKE_CASE_ ).hexdigest() ) def A_ ( ): '''simple docstring''' import doctest doctest.testmod() UpperCamelCase : str = argparse.ArgumentParser() parser.add_argument( """-s""" ,"""--string""" ,dest="""input_string""" ,default="""Hello World!! Welcome to Cryptography""" ,help="""Hash the string""" ,) parser.add_argument( """-f""" ,"""--file""" ,dest="""input_file""" ,help="""Hash contents of a file""" ) UpperCamelCase : int = parser.parse_args() UpperCamelCase : int = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file ,"""rb""" ) as f: UpperCamelCase : int = f.read() else: UpperCamelCase : str = bytes(snake_case_ ,"""utf-8""" ) print(SHAaaa(snake_case_ ).hash ) if __name__ == "__main__": main()
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 TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __A : List[str] = { '''configuration_convnext''': ['''CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConvNextConfig''', '''ConvNextOnnxConfig'''] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : str = ['''ConvNextFeatureExtractor'''] __A : int = ['''ConvNextImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Dict = [ '''CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ConvNextForImageClassification''', '''ConvNextModel''', '''ConvNextPreTrainedModel''', '''ConvNextBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[int] = [ '''TFConvNextForImageClassification''', '''TFConvNextModel''', '''TFConvNextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys __A : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
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 BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Tuple = BertTokenizer lowercase : int = BertTokenizerFast lowercase : Any = True lowercase : List[str] = True lowercase : List[Any] = filter_non_english def a_ ( self ): super().setUp() UpperCamelCase : List[str] = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] UpperCamelCase : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = """UNwant\u00E9d,running""" UpperCamelCase : Tuple = """unwanted, running""" return input_text, output_text def a_ ( self ): UpperCamelCase : List[Any] = self.tokenizer_class(self.vocab_file ) UpperCamelCase : List[str] = 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_ ) , [9, 6, 7, 12, 10, 11] ) def a_ ( self ): if not self.test_rust_tokenizer: return UpperCamelCase : Any = self.get_tokenizer() UpperCamelCase : Dict = self.get_rust_tokenizer() UpperCamelCase : List[str] = """UNwant\u00E9d,running""" UpperCamelCase : Union[str, Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_rust_tokenizer() UpperCamelCase : Tuple = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # With lower casing UpperCamelCase : List[str] = self.get_tokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.get_rust_tokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = """UNwant\u00E9d,running""" UpperCamelCase : List[str] = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = self.get_rust_tokenizer() UpperCamelCase : Any = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def a_ ( self ): UpperCamelCase : Any = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def a_ ( self ): UpperCamelCase : Any = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def a_ ( self ): UpperCamelCase : Optional[Any] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def a_ ( self ): UpperCamelCase : Union[str, Any] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def a_ ( self ): UpperCamelCase : Tuple = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def a_ ( self ): UpperCamelCase : Any = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def a_ ( self ): UpperCamelCase : Any = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def a_ ( self ): UpperCamelCase : List[Any] = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def a_ ( self ): UpperCamelCase : Any = BasicTokenizer() UpperCamelCase : Any = """a\n'll !!to?'d of, can't.""" UpperCamelCase : Dict = ["""a""", """'""", """ll""", """!""", """!""", """to""", """?""", """'""", """d""", """of""", """,""", """can""", """'""", """t""", """."""] self.assertListEqual(tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] UpperCamelCase : int = {} for i, token in enumerate(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = i UpperCamelCase : Dict = WordpieceTokenizer(vocab=SCREAMING_SNAKE_CASE_ , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def a_ ( self ): self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def a_ ( self ): self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def a_ ( self ): self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def a_ ( self ): UpperCamelCase : str = self.get_tokenizer() UpperCamelCase : Dict = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) @slow def a_ ( self ): UpperCamelCase : Union[str, Any] = self.tokenizer_class.from_pretrained("""bert-base-uncased""" ) UpperCamelCase : List[Any] = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def a_ ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): UpperCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = f'A, naïve {tokenizer_r.mask_token} AllenNLP sentence.' UpperCamelCase : Any = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE_ , """do_lower_case""" ) else False UpperCamelCase : Dict = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def a_ ( self ): UpperCamelCase : Union[str, Any] = ["""的""", """人""", """有"""] UpperCamelCase : Tuple = """""".join(SCREAMING_SNAKE_CASE_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): UpperCamelCase : List[Any] = True UpperCamelCase : Any = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = False UpperCamelCase : str = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) # it is expected that only the first Chinese character is not preceded by "##". UpperCamelCase : Tuple = [ f'##{token}' if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE_ ) ] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
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 unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html __A : List[Any] = '''platform''' import jax import jax.numpy as jnp from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, shift_tokens_right, ) def A_ ( snake_case_ : str ,snake_case_ : Optional[Any] ,snake_case_ : Union[str, Any]=None ,snake_case_ : List[str]=None ,snake_case_ : List[str]=None ,snake_case_ : Tuple=None ,snake_case_ : str=None ,snake_case_ : Any=None ,): '''simple docstring''' if attention_mask is None: UpperCamelCase : List[str] = np.where(input_ids != config.pad_token_id ,1 ,0 ) if decoder_attention_mask is None: UpperCamelCase : List[Any] = np.where(decoder_input_ids != config.pad_token_id ,1 ,0 ) if head_mask is None: UpperCamelCase : int = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCamelCase : int = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCamelCase : int = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=0.02 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Dict = batch_size UpperCamelCase : int = seq_length UpperCamelCase : Any = is_training UpperCamelCase : int = use_labels UpperCamelCase : str = vocab_size UpperCamelCase : str = hidden_size UpperCamelCase : Optional[int] = num_hidden_layers UpperCamelCase : Union[str, Any] = num_attention_heads UpperCamelCase : str = intermediate_size UpperCamelCase : Optional[int] = hidden_act UpperCamelCase : List[str] = hidden_dropout_prob UpperCamelCase : List[str] = attention_probs_dropout_prob UpperCamelCase : int = max_position_embeddings UpperCamelCase : int = eos_token_id UpperCamelCase : Any = pad_token_id UpperCamelCase : int = bos_token_id UpperCamelCase : Any = initializer_range def a_ ( self ): UpperCamelCase : Optional[int] = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) UpperCamelCase : Optional[int] = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) UpperCamelCase : Tuple = shift_tokens_right(SCREAMING_SNAKE_CASE_ , 1 , 2 ) UpperCamelCase : int = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Union[str, Any] = prepare_blenderbot_inputs_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return config, inputs_dict def a_ ( self ): UpperCamelCase , UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() return config, inputs_dict def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = 20 UpperCamelCase : Tuple = model_class_name(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model.encode(inputs_dict["""input_ids"""] ) UpperCamelCase , UpperCamelCase : Any = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) UpperCamelCase : Dict = model.init_cache(decoder_input_ids.shape[0] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) UpperCamelCase : List[str] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCamelCase : Union[str, Any] = model.decode( decoder_input_ids[:, :-1] , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[int] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) UpperCamelCase : Any = model.decode( decoder_input_ids[:, -1:] , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : str = model.decode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'Max diff is {diff}' ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = 20 UpperCamelCase : int = model_class_name(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model.encode(inputs_dict["""input_ids"""] ) UpperCamelCase , UpperCamelCase : Dict = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) UpperCamelCase : List[Any] = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) UpperCamelCase : Optional[Any] = model.init_cache(decoder_input_ids.shape[0] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCamelCase : Optional[Any] = model.decode( decoder_input_ids[:, :-1] , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) UpperCamelCase : List[str] = model.decode( decoder_input_ids[:, -1:] , SCREAMING_SNAKE_CASE_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , decoder_position_ids=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model.decode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'Max diff is {diff}' ) @require_flax class lowerCamelCase ( unittest.TestCase ): lowercase : int = 9_9 def a_ ( self ): UpperCamelCase : Dict = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) UpperCamelCase : List[str] = input_ids.shape[0] UpperCamelCase : int = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def a_ ( self ): UpperCamelCase , UpperCamelCase , UpperCamelCase : Tuple = self._get_config_and_data() UpperCamelCase : Union[str, Any] = FlaxBlenderbotSmallForConditionalGeneration(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = lm_model(input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs["""logits"""].shape , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) UpperCamelCase : Tuple = FlaxBlenderbotSmallForConditionalGeneration(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) UpperCamelCase : Dict = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) UpperCamelCase : Dict = lm_model(input_ids=SCREAMING_SNAKE_CASE_ , decoder_input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = (*summary.shape, config.vocab_size) self.assertEqual(outputs["""logits"""].shape , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) UpperCamelCase : Optional[Any] = shift_tokens_right(SCREAMING_SNAKE_CASE_ , 1 , 2 ) UpperCamelCase : Dict = np.equal(SCREAMING_SNAKE_CASE_ , 1 ).astype(np.floataa ).sum() UpperCamelCase : Tuple = np.equal(SCREAMING_SNAKE_CASE_ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(SCREAMING_SNAKE_CASE_ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase , _UpperCAmelCase ): lowercase : Union[str, Any] = True lowercase : List[str] = ( ( FlaxBlenderbotSmallModel, FlaxBlenderbotSmallForConditionalGeneration, ) if is_flax_available() else () ) lowercase : int = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else () def a_ ( self ): UpperCamelCase : List[str] = FlaxBlenderbotSmallModelTester(self ) def a_ ( self ): UpperCamelCase , UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase , UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase , UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase : str = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model_class(SCREAMING_SNAKE_CASE_ ) @jax.jit def encode_jitted(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): return model.encode(input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) with self.subTest("""JIT Enabled""" ): UpperCamelCase : Union[str, Any] = encode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase : Optional[Any] = encode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(jitted_output.shape , output.shape ) def a_ ( self ): UpperCamelCase , UpperCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) UpperCamelCase : Union[str, Any] = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return model.decode( decoder_input_ids=SCREAMING_SNAKE_CASE_ , decoder_attention_mask=SCREAMING_SNAKE_CASE_ , encoder_outputs=SCREAMING_SNAKE_CASE_ , ) with self.subTest("""JIT Enabled""" ): UpperCamelCase : Dict = decode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase : List[Any] = decode_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def a_ ( self ): for model_class_name in self.all_model_classes: UpperCamelCase : Optional[int] = model_class_name.from_pretrained("""facebook/blenderbot_small-90M""" ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids UpperCamelCase : Union[str, Any] = np.ones((1, 1) ) * model.config.eos_token_id UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
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 gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : List[str] = StableDiffusionDiffEditPipeline lowercase : List[Any] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'height', 'width', 'image'} | {'image_latents'} lowercase : str = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'image'} | {'image_latents'} lowercase : List[Any] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowercase : Union[str, Any] = frozenset([] ) def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : List[str] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Union[str, 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_ , ) UpperCamelCase : Dict = DDIMInverseScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_zero=SCREAMING_SNAKE_CASE_ , ) torch.manual_seed(0 ) UpperCamelCase : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) UpperCamelCase : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=512 , ) UpperCamelCase : List[str] = CLIPTextModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) UpperCamelCase : Any = { """unet""": unet, """scheduler""": scheduler, """inverse_scheduler""": inverse_scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : str = floats_tensor((1, 16, 16) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Dict = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = { """prompt""": """a dog and a newt""", """mask_image""": mask, """image_latents""": latents, """generator""": generator, """num_inference_steps""": 2, """inpaint_strength""": 1.0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : Optional[int] = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_ ) ).convert("""RGB""" ) if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : Optional[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = { """image""": image, """source_prompt""": """a cat and a frog""", """target_prompt""": """a dog and a newt""", """generator""": generator, """num_inference_steps""": 2, """num_maps_per_mask""": 2, """mask_encode_strength""": 1.0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase : Any = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase : List[Any] = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_ ) ).convert("""RGB""" ) if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : Any = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Optional[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = { """image""": image, """prompt""": """a cat and a frog""", """generator""": generator, """num_inference_steps""": 2, """inpaint_strength""": 1.0, """guidance_scale""": 6.0, """decode_latents""": True, """output_type""": """numpy""", } return inputs def a_ ( self ): if not hasattr(self.pipeline_class , """_optional_components""" ): return UpperCamelCase : Optional[Any] = self.get_dummy_components() UpperCamelCase : str = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = pipe(**SCREAMING_SNAKE_CASE_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = self.pipeline_class.from_pretrained(SCREAMING_SNAKE_CASE_ ) pipe_loaded.to(SCREAMING_SNAKE_CASE_ ) pipe_loaded.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) for optional_component in pipe._optional_components: self.assertTrue( getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) is None , f'`{optional_component}` did not stay set to None after loading.' , ) UpperCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = pipe_loaded(**SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Dict = np.abs(output - output_loaded ).max() self.assertLess(SCREAMING_SNAKE_CASE_ , 1e-4 ) def a_ ( self ): UpperCamelCase : Dict = """cpu""" UpperCamelCase : Dict = self.get_dummy_components() UpperCamelCase : Dict = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = self.get_dummy_mask_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = pipe.generate_mask(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) UpperCamelCase : List[Any] = np.array([0] * 9 ) UpperCamelCase : List[Any] = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1e-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def a_ ( self ): UpperCamelCase : Dict = """cpu""" UpperCamelCase : Tuple = self.get_dummy_components() UpperCamelCase : Any = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.get_dummy_inversion_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = pipe.invert(**SCREAMING_SNAKE_CASE_ ).images UpperCamelCase : str = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) UpperCamelCase : Union[str, Any] = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) UpperCamelCase : Dict = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1e-3 ) def a_ ( self ): super().test_inference_batch_single_identical(expected_max_diff=5e-3 ) def a_ ( self ): UpperCamelCase : str = """cpu""" UpperCamelCase : int = self.get_dummy_components() UpperCamelCase : str = {"""beta_start""": 0.00085, """beta_end""": 0.012, """beta_schedule""": """scaled_linear"""} UpperCamelCase : List[Any] = DPMSolverMultistepScheduler(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = DPMSolverMultistepInverseScheduler(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = self.get_dummy_inversion_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = pipe.invert(**SCREAMING_SNAKE_CASE_ ).images UpperCamelCase : Optional[Any] = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) UpperCamelCase : Tuple = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) UpperCamelCase : Optional[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1e-3 ) @require_torch_gpu @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def a_ ( cls ): UpperCamelCase : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png""" ) UpperCamelCase : List[str] = raw_image.convert("""RGB""" ).resize((768, 768) ) UpperCamelCase : Optional[int] = raw_image def a_ ( self ): UpperCamelCase : List[Any] = torch.manual_seed(0 ) UpperCamelCase : List[Any] = StableDiffusionDiffEditPipeline.from_pretrained( """stabilityai/stable-diffusion-2-1""" , safety_checker=SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa ) UpperCamelCase : List[Any] = DDIMScheduler.from_config(pipe.scheduler.config ) UpperCamelCase : List[Any] = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = """a bowl of fruit""" UpperCamelCase : int = """a bowl of pears""" UpperCamelCase : Tuple = pipe.generate_mask( image=self.raw_image , source_prompt=SCREAMING_SNAKE_CASE_ , target_prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = pipe.invert( prompt=SCREAMING_SNAKE_CASE_ , image=self.raw_image , inpaint_strength=0.7 , generator=SCREAMING_SNAKE_CASE_ ).latents UpperCamelCase : Optional[int] = pipe( prompt=SCREAMING_SNAKE_CASE_ , mask_image=SCREAMING_SNAKE_CASE_ , image_latents=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , inpaint_strength=0.7 , output_type="""numpy""" , ).images[0] UpperCamelCase : Dict = ( np.array( load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/diffedit/pears.png""" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5e-1 def a_ ( self ): UpperCamelCase : Union[str, Any] = torch.manual_seed(0 ) UpperCamelCase : int = StableDiffusionDiffEditPipeline.from_pretrained( """stabilityai/stable-diffusion-2-1""" , safety_checker=SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa ) UpperCamelCase : Optional[int] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) UpperCamelCase : Dict = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = """a bowl of fruit""" UpperCamelCase : List[Any] = """a bowl of pears""" UpperCamelCase : List[str] = pipe.generate_mask( image=self.raw_image , source_prompt=SCREAMING_SNAKE_CASE_ , target_prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = pipe.invert( prompt=SCREAMING_SNAKE_CASE_ , image=self.raw_image , inpaint_strength=0.7 , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=25 , ).latents UpperCamelCase : Any = pipe( prompt=SCREAMING_SNAKE_CASE_ , mask_image=SCREAMING_SNAKE_CASE_ , image_latents=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , inpaint_strength=0.7 , num_inference_steps=25 , output_type="""numpy""" , ).images[0] UpperCamelCase : Any = ( np.array( load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/diffedit/pears.png""" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5e-1
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 TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) __A : Dict = { '''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrOCRConfig'''], '''processing_trocr''': ['''TrOCRProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ '''TROCR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrOCRForCausalLM''', '''TrOCRPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys __A : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
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 os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : List[str] = fname.split(os.path.sep )[-1] return re.search(R"""^(.*)_\d+\.jpg$""" ,snake_case_ ).groups()[0] class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ): UpperCamelCase : Union[str, Any] = file_names UpperCamelCase : Any = image_transform UpperCamelCase : Tuple = label_to_id def __len__( self ): return len(self.file_names ) def __getitem__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.file_names[idx] UpperCamelCase : Optional[int] = PIL.Image.open(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = raw_image.convert("""RGB""" ) if self.image_transform is not None: UpperCamelCase : List[str] = self.image_transform(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = extract_label(SCREAMING_SNAKE_CASE_ ) if self.label_to_id is not None: UpperCamelCase : Tuple = self.label_to_id[label] return {"image": image, "label": label} def A_ ( snake_case_ : List[str] ,snake_case_ : Any ): '''simple docstring''' # Initialize accelerator if args.with_tracking: UpperCamelCase : List[Any] = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,log_with="""all""" ,project_dir=args.project_dir ) else: UpperCamelCase : Dict = Accelerator(cpu=args.cpu ,mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : int = config["""lr"""] UpperCamelCase : Any = int(config["""num_epochs"""] ) UpperCamelCase : Any = int(config["""seed"""] ) UpperCamelCase : List[Any] = int(config["""batch_size"""] ) UpperCamelCase : Optional[int] = config["""image_size"""] if not isinstance(snake_case_ ,(list, tuple) ): UpperCamelCase : List[Any] = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps ,"""isdigit""" ): if args.checkpointing_steps == "epoch": UpperCamelCase : int = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): UpperCamelCase : List[str] = int(args.checkpointing_steps ) else: raise ValueError( f'Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.' ) else: UpperCamelCase : int = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: UpperCamelCase : List[Any] = os.path.split(snake_case_ )[-1].split(""".""" )[0] accelerator.init_trackers(snake_case_ ,snake_case_ ) # Grab all the image filenames UpperCamelCase : Optional[Any] = [os.path.join(args.data_dir ,snake_case_ ) for fname in os.listdir(args.data_dir ) if fname.endswith(""".jpg""" )] # Build the label correspondences UpperCamelCase : int = [extract_label(snake_case_ ) for fname in file_names] UpperCamelCase : int = list(set(snake_case_ ) ) id_to_label.sort() UpperCamelCase : Optional[int] = {lbl: i for i, lbl in enumerate(snake_case_ )} # Set the seed before splitting the data. np.random.seed(snake_case_ ) torch.manual_seed(snake_case_ ) torch.cuda.manual_seed_all(snake_case_ ) # Split our filenames between train and validation UpperCamelCase : Any = np.random.permutation(len(snake_case_ ) ) UpperCamelCase : Any = int(0.8 * len(snake_case_ ) ) UpperCamelCase : List[str] = random_perm[:cut] UpperCamelCase : int = random_perm[cut:] # For training we use a simple RandomResizedCrop UpperCamelCase : Any = Compose([RandomResizedCrop(snake_case_ ,scale=(0.5, 1.0) ), ToTensor()] ) UpperCamelCase : Dict = PetsDataset( [file_names[i] for i in train_split] ,image_transform=snake_case_ ,label_to_id=snake_case_ ) # For evaluation, we use a deterministic Resize UpperCamelCase : str = Compose([Resize(snake_case_ ), ToTensor()] ) UpperCamelCase : int = PetsDataset([file_names[i] for i in eval_split] ,image_transform=snake_case_ ,label_to_id=snake_case_ ) # Instantiate dataloaders. UpperCamelCase : Optional[Any] = DataLoader(snake_case_ ,shuffle=snake_case_ ,batch_size=snake_case_ ,num_workers=4 ) UpperCamelCase : Tuple = DataLoader(snake_case_ ,shuffle=snake_case_ ,batch_size=snake_case_ ,num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : List[Any] = create_model("""resnet50d""" ,pretrained=snake_case_ ,num_classes=len(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 : str = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): UpperCamelCase : int = False for param in model.get_classifier().parameters(): UpperCamelCase : List[Any] = True # We normalize the batches of images to be a bit faster. UpperCamelCase : Union[str, Any] = torch.tensor(model.default_cfg["""mean"""] )[None, :, None, None].to(accelerator.device ) UpperCamelCase : Optional[int] = torch.tensor(model.default_cfg["""std"""] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer UpperCamelCase : Any = torch.optim.Adam(params=model.parameters() ,lr=lr / 2_5 ) # Instantiate learning rate scheduler UpperCamelCase : Optional[int] = OneCycleLR(optimizer=snake_case_ ,max_lr=snake_case_ ,epochs=snake_case_ ,steps_per_epoch=len(snake_case_ ) ) # 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 : Tuple = accelerator.prepare( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) # We need to keep track of how many total steps we have iterated over UpperCamelCase : Optional[Any] = 0 # We also need to keep track of the starting epoch so files are named properly UpperCamelCase : Optional[int] = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(f'Resumed from checkpoint: {args.resume_from_checkpoint}' ) accelerator.load_state(args.resume_from_checkpoint ) UpperCamelCase : int = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint UpperCamelCase : Dict = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) UpperCamelCase : str = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` UpperCamelCase : List[Any] = os.path.splitext(snake_case_ )[0] if "epoch" in training_difference: UpperCamelCase : Tuple = int(training_difference.replace("""epoch_""" ,"""""" ) ) + 1 UpperCamelCase : Dict = None else: UpperCamelCase : int = int(training_difference.replace("""step_""" ,"""""" ) ) UpperCamelCase : Optional[int] = resume_step // len(snake_case_ ) resume_step -= starting_epoch * len(snake_case_ ) # Now we train the model for epoch in range(snake_case_ ,snake_case_ ): model.train() if args.with_tracking: UpperCamelCase : List[str] = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step UpperCamelCase : Any = accelerator.skip_first_batches(snake_case_ ,snake_case_ ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader UpperCamelCase : str = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. UpperCamelCase : Optional[Any] = {k: v.to(accelerator.device ) for k, v in batch.items()} UpperCamelCase : Union[str, Any] = (batch["""image"""] - mean) / std UpperCamelCase : str = model(snake_case_ ) UpperCamelCase : List[Any] = torch.nn.functional.cross_entropy(snake_case_ ,batch["""label"""] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(snake_case_ ,snake_case_ ): UpperCamelCase : Union[str, Any] = f'step_{overall_step}' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: UpperCamelCase : int = os.path.join(args.output_dir ,snake_case_ ) accelerator.save_state(snake_case_ ) model.eval() UpperCamelCase : int = 0 UpperCamelCase : List[Any] = 0 for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. UpperCamelCase : str = {k: v.to(accelerator.device ) for k, v in batch.items()} UpperCamelCase : Optional[int] = (batch["""image"""] - mean) / std with torch.no_grad(): UpperCamelCase : Any = model(snake_case_ ) UpperCamelCase : List[str] = outputs.argmax(dim=-1 ) UpperCamelCase , UpperCamelCase : int = accelerator.gather_for_metrics((predictions, batch["""label"""]) ) UpperCamelCase : Dict = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() UpperCamelCase : int = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(f'epoch {epoch}: {1_0_0 * eval_metric:.2f}' ) if args.with_tracking: accelerator.log( { """accuracy""": 1_0_0 * eval_metric, """train_loss""": total_loss.item() / len(snake_case_ ), """epoch""": epoch, } ,step=snake_case_ ,) if checkpointing_steps == "epoch": UpperCamelCase : Any = f'epoch_{epoch}' if args.output_dir is not None: UpperCamelCase : int = os.path.join(args.output_dir ,snake_case_ ) accelerator.save_state(snake_case_ ) if args.with_tracking: accelerator.end_training() def A_ ( ): '''simple docstring''' UpperCamelCase : Dict = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument("""--data_dir""" ,required=snake_case_ ,help="""The data folder on disk.""" ) parser.add_argument("""--fp16""" ,action="""store_true""" ,help="""If passed, will use FP16 training.""" ) 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.""" ,) parser.add_argument("""--cpu""" ,action="""store_true""" ,help="""If passed, will train on the CPU.""" ) parser.add_argument( """--checkpointing_steps""" ,type=snake_case_ ,default=snake_case_ ,help="""Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.""" ,) parser.add_argument( """--output_dir""" ,type=snake_case_ ,default=""".""" ,help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" ,) parser.add_argument( """--resume_from_checkpoint""" ,type=snake_case_ ,default=snake_case_ ,help="""If the training should continue from a checkpoint folder.""" ,) parser.add_argument( """--with_tracking""" ,action="""store_true""" ,help="""Whether to load in all available experiment trackers from the environment and use them for logging.""" ,) parser.add_argument( """--project_dir""" ,type=snake_case_ ,default="""logs""" ,help="""Location on where to store experiment tracking logs` and relevent project information""" ,) UpperCamelCase : int = parser.parse_args() UpperCamelCase : List[Any] = {"""lr""": 3e-2, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 6_4, """image_size""": 2_2_4} training_function(snake_case_ ,snake_case_ ) if __name__ == "__main__": main()
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 torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def A_ ( snake_case_ : Tuple ,snake_case_ : Union[str, Any] ,snake_case_ : str ): '''simple docstring''' # Initialise PyTorch model UpperCamelCase : List[str] = AlbertConfig.from_json_file(snake_case_ ) print(f'Building PyTorch model from configuration: {config}' ) UpperCamelCase : int = AlbertForPreTraining(snake_case_ ) # Load weights from tf checkpoint load_tf_weights_in_albert(snake_case_ ,snake_case_ ,snake_case_ ) # Save pytorch-model print(f'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() ,snake_case_ ) if __name__ == "__main__": __A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--albert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained ALBERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) __A : str = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
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 cva import numpy as np class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if k in (0.04, 0.06): UpperCamelCase : Tuple = k UpperCamelCase : Any = window_size else: raise ValueError("""invalid k value""" ) def __str__( self ): return str(self.k ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = cva.imread(SCREAMING_SNAKE_CASE_ , 0 ) UpperCamelCase , UpperCamelCase : int = img.shape UpperCamelCase : list[list[int]] = [] UpperCamelCase : Optional[int] = img.copy() UpperCamelCase : Tuple = cva.cvtColor(SCREAMING_SNAKE_CASE_ , cva.COLOR_GRAY2RGB ) UpperCamelCase , UpperCamelCase : Any = np.gradient(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = dx**2 UpperCamelCase : List[str] = dy**2 UpperCamelCase : List[str] = dx * dy UpperCamelCase : Optional[Any] = 0.04 UpperCamelCase : Optional[Any] = self.window_size // 2 for y in range(SCREAMING_SNAKE_CASE_ , h - offset ): for x in range(SCREAMING_SNAKE_CASE_ , w - offset ): UpperCamelCase : Tuple = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() UpperCamelCase : Union[str, Any] = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() UpperCamelCase : str = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() UpperCamelCase : Optional[Any] = (wxx * wyy) - (wxy**2) UpperCamelCase : List[str] = wxx + wyy UpperCamelCase : Any = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": __A : List[Any] = HarrisCorner(0.04, 3) __A , __A : Tuple = edge_detect.detect('''path_to_image''') cva.imwrite('''detect.png''', color_img)
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 pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : Optional[int] = torch.nn.Linear(10 , 10 ) UpperCamelCase : Tuple = torch.optim.SGD(model.parameters() , 0.1 ) UpperCamelCase : str = Accelerator() UpperCamelCase : Union[str, Any] = accelerator.prepare(SCREAMING_SNAKE_CASE_ ) try: pickle.loads(pickle.dumps(SCREAMING_SNAKE_CASE_ ) ) except Exception as e: self.fail(f'Accelerated optimizer pickling failed with {e}' ) AcceleratorState._reset_state()
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""" from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class lowerCamelCase : lowercase : int lowercase : int class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : list[list[Edge]] = [[] for _ in range(SCREAMING_SNAKE_CASE_ )] UpperCamelCase : str = size def __getitem__( self , SCREAMING_SNAKE_CASE_ ): return iter(self._graph[vertex] ) @property def a_ ( self ): return self._size def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if weight not in (0, 1): raise ValueError("""Edge weight must be either 0 or 1.""" ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("""Vertex indexes must be in [0; size).""" ) self._graph[from_vertex].append(Edge(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = deque([start_vertex] ) UpperCamelCase : list[int | None] = [None] * self.size UpperCamelCase : str = 0 while queue: UpperCamelCase : str = queue.popleft() UpperCamelCase : Optional[Any] = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: UpperCamelCase : Dict = current_distance + edge.weight UpperCamelCase : Dict = distances[edge.destination_vertex] if ( isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and new_distance >= dest_vertex_distance ): continue UpperCamelCase : int = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("""No path from start_vertex to finish_vertex.""" ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
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 json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process __A : str = logging.getLogger(__name__) __A : List[Any] = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) __A : Tuple = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowerCamelCase : lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(_UpperCAmelCase )} , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) lowercase : bool = field( default=_UpperCAmelCase , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} , ) lowercase : str = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) lowercase : bool = field( default=_UpperCAmelCase , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) def a_ ( self ): if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( """--config_overrides can't be used in combination with --config_name or --model_name_or_path""" ) @dataclass class lowerCamelCase : lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'The name of the dataset to use (via the datasets library).'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) lowercase : Optional[str] = field(default=_UpperCAmelCase , metadata={'help': 'The input training data file (a text file).'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'} , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'An optional input train ref data file for whole word masking in Chinese.'} , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'An optional input validation ref data file for whole word masking in Chinese.'} , ) lowercase : bool = field( default=_UpperCAmelCase , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) lowercase : Optional[int] = field( default=5 , metadata={ 'help': 'The percentage of the train set used as validation set in case there\'s no validation split' } , ) lowercase : Optional[int] = field( default=_UpperCAmelCase , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated. Default to the max input length of the model.' ) } , ) lowercase : Optional[int] = field( default=_UpperCAmelCase , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) lowercase : float = field( default=0.15 , metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} ) lowercase : bool = field( default=_UpperCAmelCase , metadata={ 'help': ( 'Whether to pad all samples to `max_seq_length`. ' 'If False, will pad the samples dynamically when batching to the maximum length in the batch.' ) } , ) def a_ ( self ): if self.train_file is not None: UpperCamelCase : List[Any] = self.train_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: UpperCamelCase : str = self.validation_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def A_ ( snake_case_ : List[str] ,snake_case_ : Tuple ): '''simple docstring''' with open(snake_case_ ,"""r""" ,encoding="""utf-8""" ) as f: UpperCamelCase : Optional[int] = [json.loads(snake_case_ ) for line in f.read().splitlines() if (len(snake_case_ ) > 0 and not line.isspace())] assert len(snake_case_ ) == len(snake_case_ ) UpperCamelCase : Tuple = {c: dataset[c] for c in dataset.column_names} UpperCamelCase : int = refs return Dataset.from_dict(snake_case_ ) def A_ ( ): '''simple docstring''' # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. UpperCamelCase : List[str] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[int] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCamelCase , UpperCamelCase , UpperCamelCase : Dict = parser.parse_args_into_dataclasses() # Detecting last checkpoint. UpperCamelCase : int = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: UpperCamelCase : List[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,handlers=[logging.StreamHandler(sys.stdout )] ,) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + f'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" ,snake_case_ ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. UpperCamelCase : List[str] = load_dataset(data_args.dataset_name ,data_args.dataset_config_name ) if "validation" not in datasets.keys(): UpperCamelCase : List[str] = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=f'train[:{data_args.validation_split_percentage}%]' ,) UpperCamelCase : List[str] = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=f'train[{data_args.validation_split_percentage}%:]' ,) else: UpperCamelCase : List[str] = {} if data_args.train_file is not None: UpperCamelCase : Any = data_args.train_file if data_args.validation_file is not None: UpperCamelCase : Dict = data_args.validation_file UpperCamelCase : Any = data_args.train_file.split(""".""" )[-1] if extension == "txt": UpperCamelCase : int = """text""" UpperCamelCase : List[Any] = load_dataset(snake_case_ ,data_files=snake_case_ ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCamelCase : Dict = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: UpperCamelCase : Tuple = AutoConfig.from_pretrained(model_args.config_name ,**snake_case_ ) elif model_args.model_name_or_path: UpperCamelCase : Any = AutoConfig.from_pretrained(model_args.model_name_or_path ,**snake_case_ ) else: UpperCamelCase : str = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(f'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(f'New config: {config}' ) UpperCamelCase : Dict = { """cache_dir""": model_args.cache_dir, """use_fast""": model_args.use_fast_tokenizer, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: UpperCamelCase : int = AutoTokenizer.from_pretrained(model_args.tokenizer_name ,**snake_case_ ) elif model_args.model_name_or_path: UpperCamelCase : Optional[Any] = AutoTokenizer.from_pretrained(model_args.model_name_or_path ,**snake_case_ ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported by this script.""" """You can do it from another script, save it, and load it from here, using --tokenizer_name.""" ) if model_args.model_name_or_path: UpperCamelCase : Dict = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path ,from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) ,config=snake_case_ ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) else: logger.info("""Training new model from scratch""" ) UpperCamelCase : Dict = AutoModelForMaskedLM.from_config(snake_case_ ) model.resize_token_embeddings(len(snake_case_ ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: UpperCamelCase : Tuple = datasets["""train"""].column_names else: UpperCamelCase : Any = datasets["""validation"""].column_names UpperCamelCase : str = """text""" if """text""" in column_names else column_names[0] UpperCamelCase : Optional[Any] = """max_length""" if data_args.pad_to_max_length else False def tokenize_function(snake_case_ : Optional[int] ): # Remove empty lines UpperCamelCase : Optional[Any] = [line for line in examples["""text"""] if len(snake_case_ ) > 0 and not line.isspace()] return tokenizer(examples["""text"""] ,padding=snake_case_ ,truncation=snake_case_ ,max_length=data_args.max_seq_length ) UpperCamelCase : List[str] = datasets.map( snake_case_ ,batched=snake_case_ ,num_proc=data_args.preprocessing_num_workers ,remove_columns=[text_column_name] ,load_from_cache_file=not data_args.overwrite_cache ,) # Add the chinese references if provided if data_args.train_ref_file is not None: UpperCamelCase : List[Any] = add_chinese_references(tokenized_datasets["""train"""] ,data_args.train_ref_file ) if data_args.validation_ref_file is not None: UpperCamelCase : Any = add_chinese_references( tokenized_datasets["""validation"""] ,data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer UpperCamelCase : List[Any] = data_args.train_ref_file or data_args.validation_ref_file if has_ref: UpperCamelCase : List[str] = False # Data collator # This one will take care of randomly masking the tokens. UpperCamelCase : Dict = DataCollatorForWholeWordMask(tokenizer=snake_case_ ,mlm_probability=data_args.mlm_probability ) # Initialize our Trainer UpperCamelCase : Any = Trainer( model=snake_case_ ,args=snake_case_ ,train_dataset=tokenized_datasets["""train"""] if training_args.do_train else None ,eval_dataset=tokenized_datasets["""validation"""] if training_args.do_eval else None ,tokenizer=snake_case_ ,data_collator=snake_case_ ,) # Training if training_args.do_train: if last_checkpoint is not None: UpperCamelCase : List[Any] = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): UpperCamelCase : Optional[Any] = model_args.model_name_or_path else: UpperCamelCase : int = None UpperCamelCase : Any = trainer.train(resume_from_checkpoint=snake_case_ ) trainer.save_model() # Saves the tokenizer too for easy upload UpperCamelCase : List[str] = os.path.join(training_args.output_dir ,"""train_results.txt""" ) if trainer.is_world_process_zero(): with open(snake_case_ ,"""w""" ) as writer: logger.info("""***** Train results *****""" ) for key, value in sorted(train_result.metrics.items() ): logger.info(f' {key} = {value}' ) writer.write(f'{key} = {value}\n' ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir ,"""trainer_state.json""" ) ) # Evaluation UpperCamelCase : str = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) UpperCamelCase : List[str] = trainer.evaluate() UpperCamelCase : List[str] = math.exp(eval_output["""eval_loss"""] ) UpperCamelCase : Any = perplexity UpperCamelCase : Optional[int] = os.path.join(training_args.output_dir ,"""eval_results_mlm_wwm.txt""" ) if trainer.is_world_process_zero(): with open(snake_case_ ,"""w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in sorted(results.items() ): logger.info(f' {key} = {value}' ) writer.write(f'{key} = {value}\n' ) return results def A_ ( snake_case_ : Dict ): '''simple docstring''' # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
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 importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __A : Optional[int] = logging.get_logger(__name__) __A : int = OrderedDict( [ ('''audio-spectrogram-transformer''', '''ASTFeatureExtractor'''), ('''beit''', '''BeitFeatureExtractor'''), ('''chinese_clip''', '''ChineseCLIPFeatureExtractor'''), ('''clap''', '''ClapFeatureExtractor'''), ('''clip''', '''CLIPFeatureExtractor'''), ('''clipseg''', '''ViTFeatureExtractor'''), ('''conditional_detr''', '''ConditionalDetrFeatureExtractor'''), ('''convnext''', '''ConvNextFeatureExtractor'''), ('''cvt''', '''ConvNextFeatureExtractor'''), ('''data2vec-audio''', '''Wav2Vec2FeatureExtractor'''), ('''data2vec-vision''', '''BeitFeatureExtractor'''), ('''deformable_detr''', '''DeformableDetrFeatureExtractor'''), ('''deit''', '''DeiTFeatureExtractor'''), ('''detr''', '''DetrFeatureExtractor'''), ('''dinat''', '''ViTFeatureExtractor'''), ('''donut-swin''', '''DonutFeatureExtractor'''), ('''dpt''', '''DPTFeatureExtractor'''), ('''encodec''', '''EncodecFeatureExtractor'''), ('''flava''', '''FlavaFeatureExtractor'''), ('''glpn''', '''GLPNFeatureExtractor'''), ('''groupvit''', '''CLIPFeatureExtractor'''), ('''hubert''', '''Wav2Vec2FeatureExtractor'''), ('''imagegpt''', '''ImageGPTFeatureExtractor'''), ('''layoutlmv2''', '''LayoutLMv2FeatureExtractor'''), ('''layoutlmv3''', '''LayoutLMv3FeatureExtractor'''), ('''levit''', '''LevitFeatureExtractor'''), ('''maskformer''', '''MaskFormerFeatureExtractor'''), ('''mctct''', '''MCTCTFeatureExtractor'''), ('''mobilenet_v1''', '''MobileNetV1FeatureExtractor'''), ('''mobilenet_v2''', '''MobileNetV2FeatureExtractor'''), ('''mobilevit''', '''MobileViTFeatureExtractor'''), ('''nat''', '''ViTFeatureExtractor'''), ('''owlvit''', '''OwlViTFeatureExtractor'''), ('''perceiver''', '''PerceiverFeatureExtractor'''), ('''poolformer''', '''PoolFormerFeatureExtractor'''), ('''regnet''', '''ConvNextFeatureExtractor'''), ('''resnet''', '''ConvNextFeatureExtractor'''), ('''segformer''', '''SegformerFeatureExtractor'''), ('''sew''', '''Wav2Vec2FeatureExtractor'''), ('''sew-d''', '''Wav2Vec2FeatureExtractor'''), ('''speech_to_text''', '''Speech2TextFeatureExtractor'''), ('''speecht5''', '''SpeechT5FeatureExtractor'''), ('''swiftformer''', '''ViTFeatureExtractor'''), ('''swin''', '''ViTFeatureExtractor'''), ('''swinv2''', '''ViTFeatureExtractor'''), ('''table-transformer''', '''DetrFeatureExtractor'''), ('''timesformer''', '''VideoMAEFeatureExtractor'''), ('''tvlt''', '''TvltFeatureExtractor'''), ('''unispeech''', '''Wav2Vec2FeatureExtractor'''), ('''unispeech-sat''', '''Wav2Vec2FeatureExtractor'''), ('''van''', '''ConvNextFeatureExtractor'''), ('''videomae''', '''VideoMAEFeatureExtractor'''), ('''vilt''', '''ViltFeatureExtractor'''), ('''vit''', '''ViTFeatureExtractor'''), ('''vit_mae''', '''ViTFeatureExtractor'''), ('''vit_msn''', '''ViTFeatureExtractor'''), ('''wav2vec2''', '''Wav2Vec2FeatureExtractor'''), ('''wav2vec2-conformer''', '''Wav2Vec2FeatureExtractor'''), ('''wavlm''', '''Wav2Vec2FeatureExtractor'''), ('''whisper''', '''WhisperFeatureExtractor'''), ('''xclip''', '''CLIPFeatureExtractor'''), ('''yolos''', '''YolosFeatureExtractor'''), ] ) __A : Tuple = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def A_ ( snake_case_ : str ): '''simple docstring''' for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: UpperCamelCase : List[str] = model_type_to_module_name(snake_case_ ) UpperCamelCase : Union[str, Any] = importlib.import_module(f'.{module_name}' ,"""transformers.models""" ) try: return getattr(snake_case_ ,snake_case_ ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(snake_case_ ,"""__name__""" ,snake_case_ ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. UpperCamelCase : Optional[Any] = importlib.import_module("""transformers""" ) if hasattr(snake_case_ ,snake_case_ ): return getattr(snake_case_ ,snake_case_ ) return None def A_ ( snake_case_ : Union[str, os.PathLike] ,snake_case_ : Optional[Union[str, os.PathLike]] = None ,snake_case_ : bool = False ,snake_case_ : bool = False ,snake_case_ : Optional[Dict[str, str]] = None ,snake_case_ : Optional[Union[bool, str]] = None ,snake_case_ : Optional[str] = None ,snake_case_ : bool = False ,**snake_case_ : str ,): '''simple docstring''' UpperCamelCase : Tuple = get_file_from_repo( snake_case_ ,snake_case_ ,cache_dir=snake_case_ ,force_download=snake_case_ ,resume_download=snake_case_ ,proxies=snake_case_ ,use_auth_token=snake_case_ ,revision=snake_case_ ,local_files_only=snake_case_ ,) if resolved_config_file is None: logger.info( """Could not locate the feature extractor configuration file, will try to use the model config instead.""" ) return {} with open(snake_case_ ,encoding="""utf-8""" ) as reader: return json.load(snake_case_ ) class lowerCamelCase : def __init__( self ): raise EnvironmentError( """AutoFeatureExtractor is designed to be instantiated """ """using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.""" ) @classmethod @replace_list_option_in_docstrings(SCREAMING_SNAKE_CASE_ ) def a_ ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = kwargs.pop("""config""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = kwargs.pop("""trust_remote_code""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = True UpperCamelCase , UpperCamelCase : Union[str, Any] = FeatureExtractionMixin.get_feature_extractor_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = config_dict.get("""feature_extractor_type""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = None if "AutoFeatureExtractor" in config_dict.get("""auto_map""" , {} ): UpperCamelCase : List[Any] = config_dict["""auto_map"""]["""AutoFeatureExtractor"""] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # It could be in `config.feature_extractor_type`` UpperCamelCase : int = getattr(SCREAMING_SNAKE_CASE_ , """feature_extractor_type""" , SCREAMING_SNAKE_CASE_ ) if hasattr(SCREAMING_SNAKE_CASE_ , """auto_map""" ) and "AutoFeatureExtractor" in config.auto_map: UpperCamelCase : List[str] = config.auto_map["""AutoFeatureExtractor"""] if feature_extractor_class is not None: UpperCamelCase : Optional[int] = feature_extractor_class_from_name(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = feature_extractor_auto_map is not None UpperCamelCase : Optional[int] = feature_extractor_class is not None or type(SCREAMING_SNAKE_CASE_ ) in FEATURE_EXTRACTOR_MAPPING UpperCamelCase : Optional[Any] = resolve_trust_remote_code( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if has_remote_code and trust_remote_code: UpperCamelCase : Union[str, Any] = get_class_from_dynamic_module( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = kwargs.pop("""code_revision""" , SCREAMING_SNAKE_CASE_ ) if os.path.isdir(SCREAMING_SNAKE_CASE_ ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(SCREAMING_SNAKE_CASE_ ) in FEATURE_EXTRACTOR_MAPPING: UpperCamelCase : Tuple = FEATURE_EXTRACTOR_MAPPING[type(SCREAMING_SNAKE_CASE_ )] return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) raise ValueError( f'Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a ' f'`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following ' f'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}' ) @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): FEATURE_EXTRACTOR_MAPPING.register(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
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 builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP __A : Tuple = False try: __A : List[Any] = _is_package_available('''google.colab''') except ModuleNotFoundError: pass @input.register class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = [] ): UpperCamelCase : Optional[Any] = 0 UpperCamelCase : List[str] = choices UpperCamelCase : Union[str, Any] = prompt if sys.platform == "win32": UpperCamelCase : List[Any] = """*""" else: UpperCamelCase : List[Any] = """➔ """ def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , SCREAMING_SNAKE_CASE_ ) else: forceWrite(self.choices[index] , SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): if index == self.position: forceWrite(f' {self.arrow_char} ' ) self.write_choice(SCREAMING_SNAKE_CASE_ ) else: forceWrite(f' {self.choices[index]}' ) reset_cursor() def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 1 ): UpperCamelCase : str = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(SCREAMING_SNAKE_CASE_ ) move_cursor(SCREAMING_SNAKE_CASE_ , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP["""up"""] ) def a_ ( self ): self.move_direction(Direction.UP ) @input.mark(KEYMAP["""down"""] ) def a_ ( self ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["""newline"""] ) def a_ ( self ): move_cursor(len(self.choices ) - self.position , """DOWN""" ) return self.position @input.mark(KEYMAP["""interrupt"""] ) def a_ ( self ): move_cursor(len(self.choices ) - self.position , """DOWN""" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(SCREAMING_SNAKE_CASE_ )] for number in range(10 )] ) def a_ ( self ): UpperCamelCase : Dict = int(chr(self.current_selection ) ) UpperCamelCase : Tuple = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , SCREAMING_SNAKE_CASE_ ) else: return else: return def a_ ( self , SCREAMING_SNAKE_CASE_ = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , """\n""" ) if in_colab: forceWrite("""Please input a choice index (starting from 0), and press enter""" , """\n""" ) else: forceWrite("""Please select a choice using the arrow or number keys, and selecting with enter""" , """\n""" ) UpperCamelCase : Optional[int] = default_choice for i in range(len(self.choices ) ): self.print_choice(SCREAMING_SNAKE_CASE_ ) forceWrite("""\n""" ) move_cursor(len(self.choices ) - self.position , """UP""" ) with cursor.hide(): while True: if in_colab: try: UpperCamelCase : Dict = int(builtins.input() ) except ValueError: UpperCamelCase : Tuple = default_choice else: UpperCamelCase : Optional[int] = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , """UP""" ) clear_line() self.write_choice(SCREAMING_SNAKE_CASE_ , """\n""" ) return choice
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 os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) __A : Dict = '''\ Text data. Second line of data.''' __A : Optional[Any] = '''file''' @pytest.fixture(scope="""session""" ) def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : str = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") UpperCamelCase : List[Any] = bytes(snake_case_ ,"""utf-8""" ) with zstd.open(snake_case_ ,"""wb""" ) as f: f.write(snake_case_ ) return path @pytest.fixture def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir ,snake_case_ ) ,"""w""" ) as f: f.write(snake_case_ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" ,["""gzip""", """xz""", """zstd"""] ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Optional[int] ,snake_case_ : Optional[int] ,snake_case_ : List[Any] ,snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : Optional[Any] = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} UpperCamelCase : str = input_paths[compression_format] UpperCamelCase : Union[str, Any] = tmp_path / """cache""" UpperCamelCase : List[Any] = DownloadConfig(cache_dir=snake_case_ ,extract_compressed_file=snake_case_ ) UpperCamelCase : Tuple = cached_path(snake_case_ ,download_config=snake_case_ ) with open(snake_case_ ) as f: UpperCamelCase : Dict = f.read() with open(snake_case_ ) as f: UpperCamelCase : Optional[int] = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" ,[True, False] ) @pytest.mark.parametrize("""default_cache_dir""" ,[True, False] ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : List[Any] ,snake_case_ : Optional[int] ,snake_case_ : Dict ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : Union[str, Any] = """custom_cache""" UpperCamelCase : str = """custom_extracted_dir""" UpperCamelCase : Optional[Any] = tmp_path / """custom_extracted_path""" if default_extracted: UpperCamelCase : Optional[Any] = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" ,snake_case_ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" ,str(snake_case_ ) ) UpperCamelCase : str = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) UpperCamelCase : int = xz_file UpperCamelCase : List[str] = ( DownloadConfig(extract_compressed_file=snake_case_ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir ,extract_compressed_file=snake_case_ ) ) UpperCamelCase : List[Any] = cached_path(snake_case_ ,download_config=snake_case_ ) assert Path(snake_case_ ).parent.parts[-2:] == expected def A_ ( snake_case_ : int ): '''simple docstring''' # absolute path UpperCamelCase : Tuple = str(Path(snake_case_ ).resolve() ) assert cached_path(snake_case_ ) == text_file # relative path UpperCamelCase : str = str(Path(snake_case_ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(snake_case_ ) == text_file def A_ ( snake_case_ : Tuple ): '''simple docstring''' # absolute path UpperCamelCase : Any = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(snake_case_ ): cached_path(snake_case_ ) # relative path UpperCamelCase : Any = """./__missing_file__.txt""" with pytest.raises(snake_case_ ): cached_path(snake_case_ ) def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : str = get_from_cache(f'tmp://{tmpfs_file}' ) with open(snake_case_ ) as f: UpperCamelCase : Any = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" ,snake_case_ ) def A_ ( ): '''simple docstring''' with pytest.raises(snake_case_ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" ,snake_case_ ) def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Any = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(snake_case_ ): http_get("""https://huggingface.co""" ,temp_file=snake_case_ ) with pytest.raises(snake_case_ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" ,snake_case_ ) def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : List[Any] = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(snake_case_ ): ftp_get("""ftp://huggingface.co""" ,temp_file=snake_case_ ) with pytest.raises(snake_case_ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" ,snake_case_ ) def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Any = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(snake_case_ ): fsspec_get("""s3://huggingface.co""" ,temp_file=snake_case_ ) with pytest.raises(snake_case_ ): fsspec_head("""s3://huggingface.co""" )
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 re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets __A : Tuple = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' __A : List[Any] = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' __A : Tuple = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def A_ ( snake_case_ : str ): '''simple docstring''' def remove_articles(snake_case_ : Dict ): UpperCamelCase : str = re.compile(R"""\b(a|an|the)\b""" ,re.UNICODE ) return re.sub(snake_case_ ,""" """ ,snake_case_ ) def white_space_fix(snake_case_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(snake_case_ : Union[str, Any] ): UpperCamelCase : Union[str, Any] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(snake_case_ : Optional[Any] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(snake_case_ ) ) ) ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Union[str, Any] ): '''simple docstring''' return int(normalize_answer(snake_case_ ) == normalize_answer(snake_case_ ) ) def A_ ( snake_case_ : Any ,snake_case_ : Union[str, Any] ): '''simple docstring''' UpperCamelCase : List[Any] = [any(compute_exact(snake_case_ ,snake_case_ ) for ref in refs ) for pred, refs in zip(snake_case_ ,snake_case_ )] return (sum(snake_case_ ) / len(snake_case_ )) * 1_0_0 def A_ ( snake_case_ : str ,snake_case_ : Any ,snake_case_ : List[str] ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : Union[str, Any] = [rgram for rgrams in rgramslist for rgram in rgrams] UpperCamelCase : Dict = Counter(snake_case_ ) UpperCamelCase : Optional[int] = Counter(snake_case_ ) UpperCamelCase : Optional[int] = Counter() for sgram, scount in sgramcounter.items(): UpperCamelCase : List[str] = scount * numref UpperCamelCase : Any = Counter(snake_case_ ) UpperCamelCase : Any = Counter() for cgram, ccount in cgramcounter.items(): UpperCamelCase : Union[str, Any] = ccount * numref # KEEP UpperCamelCase : Optional[Any] = sgramcounter_rep & cgramcounter_rep UpperCamelCase : Optional[int] = keepgramcounter_rep & rgramcounter UpperCamelCase : int = sgramcounter_rep & rgramcounter UpperCamelCase : Union[str, Any] = 0 UpperCamelCase : Tuple = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : List[Any] = 1 UpperCamelCase : List[str] = 1 if len(snake_case_ ) > 0: UpperCamelCase : List[Any] = keeptmpscorea / len(snake_case_ ) if len(snake_case_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) UpperCamelCase : Tuple = keeptmpscorea / sum(keepgramcounterall_rep.values() ) UpperCamelCase : List[Any] = 0 if keepscore_precision > 0 or keepscore_recall > 0: UpperCamelCase : str = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION UpperCamelCase : str = sgramcounter_rep - cgramcounter_rep UpperCamelCase : Optional[int] = delgramcounter_rep - rgramcounter UpperCamelCase : List[Any] = sgramcounter_rep - rgramcounter UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[Any] = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Tuple = 1 if len(snake_case_ ) > 0: UpperCamelCase : str = deltmpscorea / len(snake_case_ ) # ADDITION UpperCamelCase : str = set(snake_case_ ) - set(snake_case_ ) UpperCamelCase : Any = set(snake_case_ ) & set(snake_case_ ) UpperCamelCase : Union[str, Any] = set(snake_case_ ) - set(snake_case_ ) UpperCamelCase : Any = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. UpperCamelCase : Any = 1 UpperCamelCase : Tuple = 1 if len(snake_case_ ) > 0: UpperCamelCase : List[str] = addtmpscore / len(snake_case_ ) if len(snake_case_ ) > 0: UpperCamelCase : Any = addtmpscore / len(snake_case_ ) UpperCamelCase : Optional[Any] = 0 if addscore_precision > 0 or addscore_recall > 0: UpperCamelCase : Optional[int] = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Union[str, Any] ,snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Optional[Any] = len(snake_case_ ) UpperCamelCase : Dict = ssent.split(""" """ ) UpperCamelCase : Optional[Any] = csent.split(""" """ ) UpperCamelCase : Union[str, Any] = [] UpperCamelCase : List[str] = [] UpperCamelCase : str = [] UpperCamelCase : Any = [] UpperCamelCase : Optional[Any] = [] UpperCamelCase : str = [] UpperCamelCase : Any = [] UpperCamelCase : Tuple = [] UpperCamelCase : Any = [] UpperCamelCase : Optional[Any] = [] for rsent in rsents: UpperCamelCase : Any = rsent.split(""" """ ) UpperCamelCase : Union[str, Any] = [] UpperCamelCase : List[str] = [] UpperCamelCase : str = [] ragramslist.append(snake_case_ ) for i in range(0 ,len(snake_case_ ) - 1 ): if i < len(snake_case_ ) - 1: UpperCamelCase : str = ragrams[i] + """ """ + ragrams[i + 1] ragrams.append(snake_case_ ) if i < len(snake_case_ ) - 2: UpperCamelCase : Optional[int] = ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2] ragrams.append(snake_case_ ) if i < len(snake_case_ ) - 3: UpperCamelCase : Any = ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2] + """ """ + ragrams[i + 3] ragrams.append(snake_case_ ) ragramslist.append(snake_case_ ) ragramslist.append(snake_case_ ) ragramslist.append(snake_case_ ) for i in range(0 ,len(snake_case_ ) - 1 ): if i < len(snake_case_ ) - 1: UpperCamelCase : Dict = sagrams[i] + """ """ + sagrams[i + 1] sagrams.append(snake_case_ ) if i < len(snake_case_ ) - 2: UpperCamelCase : Optional[Any] = sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2] sagrams.append(snake_case_ ) if i < len(snake_case_ ) - 3: UpperCamelCase : List[str] = sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2] + """ """ + sagrams[i + 3] sagrams.append(snake_case_ ) for i in range(0 ,len(snake_case_ ) - 1 ): if i < len(snake_case_ ) - 1: UpperCamelCase : Optional[Any] = cagrams[i] + """ """ + cagrams[i + 1] cagrams.append(snake_case_ ) if i < len(snake_case_ ) - 2: UpperCamelCase : Optional[Any] = cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2] cagrams.append(snake_case_ ) if i < len(snake_case_ ) - 3: UpperCamelCase : Optional[int] = cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2] + """ """ + cagrams[i + 3] cagrams.append(snake_case_ ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : str = SARIngram(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : List[Any] = SARIngram(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : List[Any] = SARIngram(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Any = SARIngram(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) UpperCamelCase : Optional[Any] = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 UpperCamelCase : Any = sum([delascore, delascore, delascore, delascore] ) / 4 UpperCamelCase : List[str] = sum([addascore, addascore, addascore, addascore] ) / 4 UpperCamelCase : Any = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def A_ ( snake_case_ : Optional[Any] ,snake_case_ : bool = True ,snake_case_ : str = "13a" ,snake_case_ : bool = True ): '''simple docstring''' # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: UpperCamelCase : int = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: UpperCamelCase : Any = sacrebleu.metrics.bleu._get_tokenizer(snake_case_ )()(snake_case_ ) else: UpperCamelCase : List[str] = sacrebleu.TOKENIZERS[tokenizer]()(snake_case_ ) elif tokenizer == "moses": UpperCamelCase : Any = sacremoses.MosesTokenizer().tokenize(snake_case_ ,return_str=snake_case_ ,escape=snake_case_ ) elif tokenizer == "penn": UpperCamelCase : str = sacremoses.MosesTokenizer().penn_tokenize(snake_case_ ,return_str=snake_case_ ) else: UpperCamelCase : List[str] = sentence if not return_str: UpperCamelCase : Union[str, Any] = normalized_sent.split() return normalized_sent def A_ ( snake_case_ : List[str] ,snake_case_ : List[Any] ,snake_case_ : int ): '''simple docstring''' if not (len(snake_case_ ) == len(snake_case_ ) == len(snake_case_ )): raise ValueError("""Sources length must match predictions and references lengths.""" ) UpperCamelCase : Tuple = 0 for src, pred, refs in zip(snake_case_ ,snake_case_ ,snake_case_ ): sari_score += SARIsent(normalize(snake_case_ ) ,normalize(snake_case_ ) ,[normalize(snake_case_ ) for sent in refs] ) UpperCamelCase : List[Any] = sari_score / len(snake_case_ ) return 1_0_0 * sari_score def A_ ( snake_case_ : Optional[Any] ,snake_case_ : List[Any] ,snake_case_ : List[Any]="exp" ,snake_case_ : Dict=None ,snake_case_ : int=False ,snake_case_ : List[str]=False ,snake_case_ : Optional[Any]=False ,): '''simple docstring''' UpperCamelCase : Dict = len(references[0] ) if any(len(snake_case_ ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) UpperCamelCase : Dict = [[refs[i] for refs in references] for i in range(snake_case_ )] UpperCamelCase : Optional[int] = sacrebleu.corpus_bleu( snake_case_ ,snake_case_ ,smooth_method=snake_case_ ,smooth_value=snake_case_ ,force=snake_case_ ,lowercase=snake_case_ ,use_effective_order=snake_case_ ,) return output.score @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.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ), } ) , codebase_urls=[ """https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py""", """https://github.com/cocoxu/simplification/blob/master/SARI.py""", """https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py""", """https://github.com/mjpost/sacreBLEU""", ] , reference_urls=[ """https://www.aclweb.org/anthology/Q16-1029.pdf""", """https://github.com/mjpost/sacreBLEU""", """https://en.wikipedia.org/wiki/BLEU""", """https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213""", ] , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = {} result.update({"""sari""": compute_sari(sources=SCREAMING_SNAKE_CASE_ , predictions=SCREAMING_SNAKE_CASE_ , references=SCREAMING_SNAKE_CASE_ )} ) result.update({"""sacrebleu""": compute_sacrebleu(predictions=SCREAMING_SNAKE_CASE_ , references=SCREAMING_SNAKE_CASE_ )} ) result.update({"""exact""": compute_em(predictions=SCREAMING_SNAKE_CASE_ , references=SCREAMING_SNAKE_CASE_ )} ) return result
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 argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging __A : Optional[int] = { '''cola''': 2, '''mnli''': 3, '''mrpc''': 2, '''sst-2''': 2, '''sts-b''': 1, '''qqp''': 2, '''qnli''': 2, '''rte''': 2, '''wnli''': 2, } logging.set_verbosity_info() def A_ ( snake_case_ : str ,snake_case_ : str ,snake_case_ : Any ,snake_case_ : Dict=None ): '''simple docstring''' # Initialise PyTorch model UpperCamelCase : Union[str, Any] = XLNetConfig.from_json_file(snake_case_ ) UpperCamelCase : Dict = finetuning_task.lower() if finetuning_task is not None else """""" if finetuning_task in GLUE_TASKS_NUM_LABELS: print(f'Building PyTorch XLNetForSequenceClassification model from configuration: {config}' ) UpperCamelCase : Union[str, Any] = finetuning_task UpperCamelCase : List[str] = GLUE_TASKS_NUM_LABELS[finetuning_task] UpperCamelCase : Optional[Any] = XLNetForSequenceClassification(snake_case_ ) elif "squad" in finetuning_task: UpperCamelCase : Dict = finetuning_task UpperCamelCase : List[str] = XLNetForQuestionAnswering(snake_case_ ) else: UpperCamelCase : int = XLNetLMHeadModel(snake_case_ ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(snake_case_ ,snake_case_ ,snake_case_ ) # Save pytorch-model UpperCamelCase : List[str] = os.path.join(snake_case_ ,snake_case_ ) UpperCamelCase : int = os.path.join(snake_case_ ,snake_case_ ) print(f'Save PyTorch model to {os.path.abspath(snake_case_ )}' ) torch.save(model.state_dict() ,snake_case_ ) print(f'Save configuration file to {os.path.abspath(snake_case_ )}' ) with open(snake_case_ ,"""w""" ,encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--xlnet_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained XLNet model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the folder to store the PyTorch model or dataset/vocab.''', ) parser.add_argument( '''--finetuning_task''', default=None, type=str, help='''Name of a task on which the XLNet TensorFlow model was fine-tuned''', ) __A : Any = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
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 import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 __A : Optional[int] = sys.version_info >= (3, 10) def A_ ( snake_case_ : Optional[Any]=None ,snake_case_ : List[Any]=None ): '''simple docstring''' return field(default_factory=lambda: default ,metadata=snake_case_ ) @dataclass class lowerCamelCase : lowercase : int lowercase : float lowercase : str lowercase : bool @dataclass class lowerCamelCase : lowercase : int = 4_2 lowercase : str = field(default='toto' , metadata={'help': 'help message'} ) @dataclass class lowerCamelCase : lowercase : bool = False lowercase : bool = True lowercase : Optional[bool] = None class lowerCamelCase ( _UpperCAmelCase ): lowercase : Any = 'titi' lowercase : Optional[Any] = 'toto' class lowerCamelCase ( _UpperCAmelCase ): lowercase : Any = 'titi' lowercase : Optional[Any] = 'toto' lowercase : int = 4_2 @dataclass class lowerCamelCase : lowercase : BasicEnum = "toto" def a_ ( self ): UpperCamelCase : str = BasicEnum(self.foo ) @dataclass class lowerCamelCase : lowercase : MixedTypeEnum = "toto" def a_ ( self ): UpperCamelCase : Dict = MixedTypeEnum(self.foo ) @dataclass class lowerCamelCase : lowercase : Optional[int] = None lowercase : Optional[float] = field(default=_UpperCAmelCase , metadata={'help': 'help message'} ) lowercase : Optional[str] = None lowercase : Optional[List[str]] = list_field(default=[] ) lowercase : Optional[List[int]] = list_field(default=[] ) @dataclass class lowerCamelCase : lowercase : List[int] = list_field(default=[] ) lowercase : List[int] = list_field(default=[1, 2, 3] ) lowercase : List[str] = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) lowercase : List[float] = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class lowerCamelCase : lowercase : List[int] = field() lowercase : str = field() lowercase : BasicEnum = field() def a_ ( self ): UpperCamelCase : Dict = BasicEnum(self.required_enum ) @dataclass class lowerCamelCase : lowercase : int lowercase : "BasicEnum" = field() lowercase : "Optional[bool]" = None lowercase : "str" = field(default='toto' , metadata={'help': 'help message'} ) lowercase : "List[str]" = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) if is_python_no_less_than_3_10: @dataclass class lowerCamelCase : lowercase : bool = False lowercase : bool = True lowercase : bool | None = None @dataclass class lowerCamelCase : lowercase : int | None = None lowercase : float | None = field(default=_UpperCAmelCase , metadata={'help': 'help message'} ) lowercase : str | None = None lowercase : list[str] | None = list_field(default=[] ) lowercase : list[int] | None = list_field(default=[] ) class lowerCamelCase ( unittest.TestCase ): def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): UpperCamelCase : List[str] = {k: v for k, v in vars(SCREAMING_SNAKE_CASE_ ).items() if k != """container"""} UpperCamelCase : int = {k: v for k, v in vars(SCREAMING_SNAKE_CASE_ ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , SCREAMING_SNAKE_CASE_ ) and yy.get("""choices""" , SCREAMING_SNAKE_CASE_ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](SCREAMING_SNAKE_CASE_ ) , yy["""type"""](SCREAMING_SNAKE_CASE_ ) ) del xx["type"], yy["type"] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--bar""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--baz""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--flag""" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , const=SCREAMING_SNAKE_CASE_ , nargs="""?""" ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] ((UpperCamelCase) , ) : Optional[Any] = parser.parse_args_into_dataclasses(SCREAMING_SNAKE_CASE_ , look_for_args_file=SCREAMING_SNAKE_CASE_ ) self.assertFalse(example.flag ) def a_ ( self ): UpperCamelCase : Tuple = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=42 , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--baz""" , default="""toto""" , type=SCREAMING_SNAKE_CASE_ , help="""help message""" ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , const=SCREAMING_SNAKE_CASE_ , nargs="""?""" ) expected.add_argument("""--baz""" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , const=SCREAMING_SNAKE_CASE_ , nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=SCREAMING_SNAKE_CASE_ , dest="""baz""" ) expected.add_argument("""--opt""" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(SCREAMING_SNAKE_CASE_ ) for dataclass_type in dataclass_types: UpperCamelCase : Optional[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = parser.parse_args([] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , opt=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Tuple = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , opt=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Optional[int] = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , opt=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Union[str, Any] = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , opt=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Optional[int] = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , opt=SCREAMING_SNAKE_CASE_ ) ) def a_ ( self ): UpperCamelCase : Optional[int] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) UpperCamelCase : Optional[Any] = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) UpperCamelCase : int = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) UpperCamelCase : Optional[int] = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) UpperCamelCase : str = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) UpperCamelCase : Optional[int] = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def a_ ( self ): @dataclass class lowerCamelCase : lowercase : Literal["titi", "toto", 4_2] = "toto" UpperCamelCase : Optional[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) UpperCamelCase : Optional[int] = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) UpperCamelCase : int = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) def a_ ( self ): UpperCamelCase : str = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=SCREAMING_SNAKE_CASE_ ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = parser.parse_args([] ) self.assertEqual( SCREAMING_SNAKE_CASE_ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , ) UpperCamelCase : Optional[Any] = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) ) def a_ ( self ): UpperCamelCase : Dict = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=SCREAMING_SNAKE_CASE_ , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--bar""" , default=SCREAMING_SNAKE_CASE_ , type=SCREAMING_SNAKE_CASE_ , help="""help message""" ) expected.add_argument("""--baz""" , default=SCREAMING_SNAKE_CASE_ , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(SCREAMING_SNAKE_CASE_ ) for dataclass_type in dataclass_types: UpperCamelCase : List[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = parser.parse_args([] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=SCREAMING_SNAKE_CASE_ , bar=SCREAMING_SNAKE_CASE_ , baz=SCREAMING_SNAKE_CASE_ , ces=[] , des=[] ) ) UpperCamelCase : int = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(SCREAMING_SNAKE_CASE_ , Namespace(foo=12 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) ) def a_ ( self ): UpperCamelCase : List[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--required_str""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=SCREAMING_SNAKE_CASE_ , ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=SCREAMING_SNAKE_CASE_ , ) expected.add_argument("""--opt""" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ ) expected.add_argument("""--baz""" , default="""toto""" , type=SCREAMING_SNAKE_CASE_ , help="""help message""" ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=SCREAMING_SNAKE_CASE_ ) self.argparsersEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[int] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } UpperCamelCase : Optional[Any] = parser.parse_dict(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[int] = BasicExample(**SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(SCREAMING_SNAKE_CASE_ , parser.parse_dict , SCREAMING_SNAKE_CASE_ , allow_extra_keys=SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE_ , """temp_json""" ) os.mkdir(SCREAMING_SNAKE_CASE_ ) with open(temp_local_path + """.json""" , """w+""" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] UpperCamelCase : Optional[Any] = BasicExample(**SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase : List[str] = os.path.join(SCREAMING_SNAKE_CASE_ , """temp_yaml""" ) os.mkdir(SCREAMING_SNAKE_CASE_ ) with open(temp_local_path + """.yaml""" , """w+""" ) as f: yaml.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] UpperCamelCase : str = BasicExample(**SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(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 bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger __A : Optional[int] = get_logger(__name__) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase : Any = ( os.path.join(SCREAMING_SNAKE_CASE_ , config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) UpperCamelCase : List[Any] = Extractor def a_ ( self , SCREAMING_SNAKE_CASE_ ): from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" UpperCamelCase : Tuple = os.path.abspath(SCREAMING_SNAKE_CASE_ ) return os.path.join(self.extract_dir , hash_url_to_filename(SCREAMING_SNAKE_CASE_ ) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return force_extract or ( not os.path.isfile(SCREAMING_SNAKE_CASE_ ) and not (os.path.isdir(SCREAMING_SNAKE_CASE_ ) and os.listdir(SCREAMING_SNAKE_CASE_ )) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False ): UpperCamelCase : Any = self.extractor.infer_extractor_format(SCREAMING_SNAKE_CASE_ ) if not extractor_format: return input_path UpperCamelCase : Any = self._get_output_path(SCREAMING_SNAKE_CASE_ ) if self._do_extract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.extractor.extract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return output_path class lowerCamelCase ( _UpperCAmelCase ): @classmethod @abstractmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): ... @staticmethod @abstractmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): ... class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase ): lowercase : List[bytes] = [] @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): with open(SCREAMING_SNAKE_CASE_ , """rb""" ) as f: return f.read(SCREAMING_SNAKE_CASE_ ) @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = b"" ): if not magic_number: UpperCamelCase : Tuple = max(len(SCREAMING_SNAKE_CASE_ ) for cls_magic_number in cls.magic_numbers ) try: UpperCamelCase : List[Any] = cls.read_magic_number(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) except OSError: return False return any(magic_number.startswith(SCREAMING_SNAKE_CASE_ ) for cls_magic_number in cls.magic_numbers ) class lowerCamelCase ( _UpperCAmelCase ): @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return tarfile.is_tarfile(SCREAMING_SNAKE_CASE_ ) @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): def resolved(SCREAMING_SNAKE_CASE_ ) -> str: return os.path.realpath(os.path.abspath(SCREAMING_SNAKE_CASE_ ) ) def badpath(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ).startswith(SCREAMING_SNAKE_CASE_ ) def badlink(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> bool: # Links are interpreted relative to the directory containing the link UpperCamelCase : Any = resolved(os.path.join(SCREAMING_SNAKE_CASE_ , os.path.dirname(info.name ) ) ) return badpath(info.linkname , base=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = resolved(SCREAMING_SNAKE_CASE_ ) for finfo in members: if badpath(finfo.name , SCREAMING_SNAKE_CASE_ ): logger.error(f'Extraction of {finfo.name} is blocked (illegal path)' ) elif finfo.issym() and badlink(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): logger.error(f'Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}' ) elif finfo.islnk() and badlink(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): logger.error(f'Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}' ) else: yield finfo @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = tarfile.open(SCREAMING_SNAKE_CASE_ ) tar_file.extractall(SCREAMING_SNAKE_CASE_ , members=TarExtractor.safemembers(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) tar_file.close() class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[Any] = [b'\x1F\x8B'] @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): with gzip.open(SCREAMING_SNAKE_CASE_ , """rb""" ) as gzip_file: with open(SCREAMING_SNAKE_CASE_ , """wb""" ) as extracted_file: shutil.copyfileobj(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( _UpperCAmelCase ): lowercase : Tuple = [ b'PK\x03\x04', b'PK\x05\x06', # empty archive b'PK\x07\x08', # spanned archive ] @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = b"" ): if super().is_extractable(SCREAMING_SNAKE_CASE_ , magic_number=SCREAMING_SNAKE_CASE_ ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(SCREAMING_SNAKE_CASE_ , """rb""" ) as fp: UpperCamelCase : Tuple = _EndRecData(SCREAMING_SNAKE_CASE_ ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: UpperCamelCase : Tuple = fp.read(SCREAMING_SNAKE_CASE_ ) # CD is where we expect it to be if len(SCREAMING_SNAKE_CASE_ ) == sizeCentralDir: UpperCamelCase : int = struct.unpack(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , """r""" ) as zip_file: zip_file.extractall(SCREAMING_SNAKE_CASE_ ) zip_file.close() class lowerCamelCase ( _UpperCAmelCase ): lowercase : Optional[Any] = [b'\xFD\x37\x7A\x58\x5A\x00'] @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): with lzma.open(SCREAMING_SNAKE_CASE_ ) as compressed_file: with open(SCREAMING_SNAKE_CASE_ , """wb""" ) as extracted_file: shutil.copyfileobj(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[str] = [b'Rar!\x1a\x07\x00', b'Rar!\x1a\x07\x01\x00'] # RAR_ID # RAR5_ID @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not config.RARFILE_AVAILABLE: raise ImportError("""Please pip install rarfile""" ) import rarfile os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = rarfile.RarFile(SCREAMING_SNAKE_CASE_ ) rf.extractall(SCREAMING_SNAKE_CASE_ ) rf.close() class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[str] = [b'\x28\xb5\x2F\xFD'] @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not config.ZSTANDARD_AVAILABLE: raise ImportError("""Please pip install zstandard""" ) import zstandard as zstd UpperCamelCase : List[str] = zstd.ZstdDecompressor() with open(SCREAMING_SNAKE_CASE_ , """rb""" ) as ifh, open(SCREAMING_SNAKE_CASE_ , """wb""" ) as ofh: dctx.copy_stream(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( _UpperCAmelCase ): lowercase : Any = [b'\x42\x5A\x68'] @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): with bza.open(SCREAMING_SNAKE_CASE_ , """rb""" ) as compressed_file: with open(SCREAMING_SNAKE_CASE_ , """wb""" ) as extracted_file: shutil.copyfileobj(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = [b'\x37\x7A\xBC\xAF\x27\x1C'] @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not config.PY7ZR_AVAILABLE: raise ImportError("""Please pip install py7zr""" ) import pyazr os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with pyazr.SevenZipFile(SCREAMING_SNAKE_CASE_ , """r""" ) as archive: archive.extractall(SCREAMING_SNAKE_CASE_ ) class lowerCamelCase ( _UpperCAmelCase ): lowercase : Dict = [b'\x04\x22\x4D\x18'] @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not config.LZ4_AVAILABLE: raise ImportError("""Please pip install lz4""" ) import lza.frame with lza.frame.open(SCREAMING_SNAKE_CASE_ , """rb""" ) as compressed_file: with open(SCREAMING_SNAKE_CASE_ , """wb""" ) as extracted_file: shutil.copyfileobj(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) class lowerCamelCase : # Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip) lowercase : Dict[str, Type[BaseExtractor]] = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def a_ ( cls ): return max( len(SCREAMING_SNAKE_CASE_ ) for extractor in cls.extractors.values() if issubclass(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def a_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): try: return MagicNumberBaseExtractor.read_magic_number(SCREAMING_SNAKE_CASE_ , magic_number_length=SCREAMING_SNAKE_CASE_ ) except OSError: return b"" @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False ): warnings.warn( """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'infer_extractor_format' instead.""" , category=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Tuple = cls.infer_extractor_format(SCREAMING_SNAKE_CASE_ ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ ): # <Added version="2.4.0"/> UpperCamelCase : Union[str, Any] = cls._get_magic_number_max_length() UpperCamelCase : str = cls._read_magic_number(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(SCREAMING_SNAKE_CASE_ , magic_number=SCREAMING_SNAKE_CASE_ ): return extractor_format @classmethod def a_ ( cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "deprecated" , ): os.makedirs(os.path.dirname(SCREAMING_SNAKE_CASE_ ) , exist_ok=SCREAMING_SNAKE_CASE_ ) # Prevent parallel extractions UpperCamelCase : List[Any] = str(Path(SCREAMING_SNAKE_CASE_ ).with_suffix(""".lock""" ) ) with FileLock(SCREAMING_SNAKE_CASE_ ): shutil.rmtree(SCREAMING_SNAKE_CASE_ , ignore_errors=SCREAMING_SNAKE_CASE_ ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): # passed as positional arg warnings.warn( """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'extractor_format' instead.""" , category=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Union[str, Any] = extractor if extractor != """deprecated""" else extractor_format else: UpperCamelCase : str = cls.extractors[extractor_format] return extractor.extract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: warnings.warn( """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """ """exception in 3.0.0.""" , category=SCREAMING_SNAKE_CASE_ , ) for extractor in cls.extractors.values(): if extractor.is_extractable(SCREAMING_SNAKE_CASE_ ): return extractor.extract(SCREAMING_SNAKE_CASE_ , 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 dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class lowerCamelCase : lowercase : str = field( metadata={'help': 'The output directory where the model will be written.'} , ) lowercase : str = field( metadata={ 'help': ( 'The encoder model checkpoint for weights initialization.' 'Don\'t set if you want to train an encoder model from scratch.' ) } , ) lowercase : str = field( metadata={ 'help': ( 'The decoder model checkpoint for weights initialization.' 'Don\'t set if you want to train a decoder model from scratch.' ) } , ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained encoder config name or path if not the same as encoder_model_name'} ) lowercase : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained decoder config name or path if not the same as decoder_model_name'} ) def A_ ( ): '''simple docstring''' UpperCamelCase : Optional[int] = HfArgumentParser((ModelArguments,) ) ((UpperCamelCase) , ) : List[str] = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: UpperCamelCase : Dict = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: UpperCamelCase : Any = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: UpperCamelCase : Union[str, Any] = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: UpperCamelCase : List[str] = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed UpperCamelCase : str = True UpperCamelCase : str = True UpperCamelCase : List[Any] = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=model_args.encoder_model_name_or_path ,decoder_pretrained_model_name_or_path=model_args.decoder_model_name_or_path ,encoder_config=snake_case_ ,decoder_config=snake_case_ ,) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens UpperCamelCase : int = decoder_config.decoder_start_token_id UpperCamelCase : Optional[int] = decoder_config.pad_token_id if decoder_start_token_id is None: UpperCamelCase : Any = decoder_config.bos_token_id if pad_token_id is None: UpperCamelCase : List[str] = decoder_config.eos_token_id # This is necessary to make Flax's generate() work UpperCamelCase : int = decoder_config.eos_token_id UpperCamelCase : Tuple = decoder_start_token_id UpperCamelCase : Union[str, Any] = pad_token_id UpperCamelCase : Union[str, Any] = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) UpperCamelCase : Dict = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) UpperCamelCase : List[str] = tokenizer.convert_ids_to_tokens(model.config.pad_token_id ) model.save_pretrained(model_args.output_dir ) image_processor.save_pretrained(model_args.output_dir ) tokenizer.save_pretrained(model_args.output_dir ) if __name__ == "__main__": main()
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 shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : Optional[Any] = """laion/clap-htsat-unfused""" UpperCamelCase : Tuple = tempfile.mkdtemp() def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return RobertaTokenizer.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE_ ) def a_ ( self , **SCREAMING_SNAKE_CASE_ ): return ClapFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE_ ) def a_ ( self ): shutil.rmtree(self.tmpdirname ) def a_ ( self ): UpperCamelCase : Any = self.get_tokenizer() UpperCamelCase : Any = self.get_feature_extractor() UpperCamelCase : List[Any] = ClapProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase : Optional[Any] = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Dict = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase : Union[str, Any] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) UpperCamelCase : Any = self.get_feature_extractor(do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) UpperCamelCase : str = ClapProcessor.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.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.get_feature_extractor() UpperCamelCase : int = self.get_tokenizer() UpperCamelCase : Optional[int] = ClapProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = floats_list((3, 1000) ) UpperCamelCase : Optional[Any] = feature_extractor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) UpperCamelCase : Union[str, Any] = processor(audios=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[Any] = self.get_feature_extractor() UpperCamelCase : Optional[int] = self.get_tokenizer() UpperCamelCase : int = ClapProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = """This is a test string""" UpperCamelCase : Dict = processor(text=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = tokenizer(SCREAMING_SNAKE_CASE_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def a_ ( self ): UpperCamelCase : Optional[int] = self.get_feature_extractor() UpperCamelCase : List[Any] = self.get_tokenizer() UpperCamelCase : Any = ClapProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCamelCase : List[str] = processor.batch_decode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[int] = self.get_feature_extractor() UpperCamelCase : Dict = self.get_tokenizer() UpperCamelCase : Optional[int] = ClapProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg="""`processor` and `feature_extractor` model input names do not match""" , )
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 string import ascii_uppercase __A : str = {str(ord(c) - 55): c for c in ascii_uppercase} def A_ ( snake_case_ : int ,snake_case_ : int ): '''simple docstring''' if isinstance(snake_case_ ,snake_case_ ): raise TypeError("""int() can't convert non-string with explicit base""" ) if num < 0: raise ValueError("""parameter must be positive int""" ) if isinstance(snake_case_ ,snake_case_ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if isinstance(snake_case_ ,snake_case_ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if base in (0, 1): raise ValueError("""base must be >= 2""" ) if base > 3_6: raise ValueError("""base must be <= 36""" ) UpperCamelCase : Union[str, Any] = """""" UpperCamelCase : int = 0 UpperCamelCase : Union[str, Any] = 0 while div != 1: UpperCamelCase , UpperCamelCase : Union[str, Any] = divmod(snake_case_ ,snake_case_ ) if base >= 1_1 and 9 < mod < 3_6: UpperCamelCase : int = ALPHABET_VALUES[str(snake_case_ )] else: UpperCamelCase : str = str(snake_case_ ) new_value += actual_value UpperCamelCase : Tuple = num // base UpperCamelCase : Optional[int] = div if div == 0: return str(new_value[::-1] ) elif div == 1: new_value += str(snake_case_ ) return str(new_value[::-1] ) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
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 datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer __A : int = '''bart''' __A : List[str] = True @st.cache(allow_output_mutation=snake_case_ ) def A_ ( ): '''simple docstring''' if LOAD_DENSE_INDEX: UpperCamelCase : Tuple = AutoTokenizer.from_pretrained("""yjernite/retribert-base-uncased""" ) UpperCamelCase : str = AutoModel.from_pretrained("""yjernite/retribert-base-uncased""" ).to("""cuda:0""" ) UpperCamelCase : Union[str, Any] = qar_model.eval() else: UpperCamelCase , UpperCamelCase : Optional[Any] = (None, None) if MODEL_TYPE == "bart": UpperCamelCase : Optional[int] = AutoTokenizer.from_pretrained("""yjernite/bart_eli5""" ) UpperCamelCase : Tuple = AutoModelForSeqaSeqLM.from_pretrained("""yjernite/bart_eli5""" ).to("""cuda:0""" ) UpperCamelCase : Optional[Any] = torch.load("""seq2seq_models/eli5_bart_model_blm_2.pth""" ) sas_model.load_state_dict(save_dict["""model"""] ) UpperCamelCase : Optional[Any] = sas_model.eval() else: UpperCamelCase , UpperCamelCase : List[Any] = make_qa_sas_model( model_name="""t5-small""" ,from_file="""seq2seq_models/eli5_t5_model_1024_4.pth""" ,device="""cuda:0""" ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=snake_case_ ) def A_ ( ): '''simple docstring''' if LOAD_DENSE_INDEX: UpperCamelCase : Optional[Any] = faiss.StandardGpuResources() UpperCamelCase : str = datasets.load_dataset(path="""wiki_snippets""" ,name="""wiki40b_en_100_0""" )["""train"""] UpperCamelCase : Optional[int] = np.memmap( """wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat""" ,dtype="""float32""" ,mode="""r""" ,shape=(wikiaab_passages.num_rows, 1_2_8) ,) UpperCamelCase : Optional[Any] = faiss.IndexFlatIP(1_2_8 ) UpperCamelCase : Optional[Any] = faiss.index_cpu_to_gpu(snake_case_ ,1 ,snake_case_ ) wikiaab_gpu_index_flat.add(snake_case_ ) # TODO fix for larger GPU else: UpperCamelCase , UpperCamelCase : List[Any] = (None, None) UpperCamelCase : Dict = Elasticsearch([{"""host""": """localhost""", """port""": """9200"""}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : Tuple = datasets.load_dataset("""eli5""" ,name="""LFQA_reddit""" ) UpperCamelCase : List[str] = elia["""train_eli5"""] UpperCamelCase : int = np.memmap( """eli5_questions_reps.dat""" ,dtype="""float32""" ,mode="""r""" ,shape=(elia_train.num_rows, 1_2_8) ) UpperCamelCase : Tuple = faiss.IndexFlatIP(1_2_8 ) eli5_train_q_index.add(snake_case_ ) return (elia_train, eli5_train_q_index) __A , __A , __A : List[str] = load_indexes() __A , __A , __A , __A : int = load_models() __A , __A : Dict = load_train_data() def A_ ( snake_case_ : Optional[int] ,snake_case_ : List[str]=1_0 ): '''simple docstring''' UpperCamelCase : str = embed_questions_for_retrieval([question] ,snake_case_ ,snake_case_ ) UpperCamelCase , UpperCamelCase : Dict = eli5_train_q_index.search(snake_case_ ,snake_case_ ) UpperCamelCase : Tuple = [elia_train[int(snake_case_ )] for i in I[0]] return nn_examples def A_ ( snake_case_ : List[str] ,snake_case_ : Optional[Any]="wiki40b" ,snake_case_ : Optional[int]="dense" ,snake_case_ : Optional[int]=1_0 ): '''simple docstring''' if source == "none": UpperCamelCase , UpperCamelCase : Any = (""" <P> """.join(["""""" for _ in range(1_1 )] ).strip(), []) else: if method == "dense": UpperCamelCase , UpperCamelCase : List[Any] = query_qa_dense_index( snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) else: UpperCamelCase , UpperCamelCase : Tuple = query_es_index( snake_case_ ,snake_case_ ,index_name="""english_wiki40b_snippets_100w""" ,n_results=snake_case_ ,) UpperCamelCase : Any = [ (res["""article_title"""], res["""section_title"""].strip(), res["""score"""], res["""passage_text"""]) for res in hit_lst ] UpperCamelCase : List[str] = """question: {} context: {}""".format(snake_case_ ,snake_case_ ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda snake_case_ : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda snake_case_ : None), } ) def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Optional[int] ,snake_case_ : Any ,snake_case_ : Any=6_4 ,snake_case_ : List[Any]=2_5_6 ,snake_case_ : int=False ,snake_case_ : List[Any]=2 ,snake_case_ : List[Any]=0.95 ,snake_case_ : int=0.8 ): '''simple docstring''' with torch.no_grad(): UpperCamelCase : Optional[int] = qa_sas_generate( snake_case_ ,snake_case_ ,snake_case_ ,num_answers=1 ,num_beams=snake_case_ ,min_len=snake_case_ ,max_len=snake_case_ ,do_sample=snake_case_ ,temp=snake_case_ ,top_p=snake_case_ ,top_k=snake_case_ ,max_input_length=1_0_2_4 ,device="""cuda:0""" ,)[0] return (answer, support_list) st.title('''Long Form Question Answering with ELI5''') # Start sidebar __A : Union[str, Any] = '''<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>''' __A : List[str] = ''' <html> <head> <style> .img-container { padding-left: 90px; padding-right: 90px; padding-top: 50px; padding-bottom: 50px; background-color: #f0f3f9; } </style> </head> <body> <span class="img-container"> <!-- Inline parent element --> %s </span> </body> </html> ''' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia __A : List[str] = ''' This demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html). First, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset, a pre-processed fixed snapshot of Wikipedia. ''' st.sidebar.markdown(description, unsafe_allow_html=True) __A : str = [ '''Answer the question''', '''View the retrieved document only''', '''View the most similar ELI5 question and answer''', '''Show me everything, please!''', ] __A : List[str] = st.sidebar.checkbox('''Demo options''') if demo_options: __A : str = st.sidebar.selectbox( '''''', action_list, index=3, ) __A : Union[str, Any] = action_list.index(action_st) __A : Optional[int] = st.sidebar.selectbox( '''''', ['''Show full text of passages''', '''Show passage section titles'''], index=0, ) __A : Optional[int] = show_type == '''Show full text of passages''' else: __A : Optional[int] = 3 __A : int = True __A : Optional[Any] = st.sidebar.checkbox('''Retrieval options''') if retrieval_options: __A : Optional[Any] = ''' ### Information retriever options The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs. The answer is then generated by sequence to sequence model which takes the question and retrieved document as input. ''' st.sidebar.markdown(retriever_info) __A : Optional[Any] = st.sidebar.selectbox('''Which Wikipedia format should the model use?''', ['''wiki40b''', '''none''']) __A : Optional[int] = st.sidebar.selectbox('''Which Wikipedia indexer should the model use?''', ['''dense''', '''sparse''', '''mixed''']) else: __A : Union[str, Any] = '''wiki40b''' __A : int = '''dense''' __A : List[str] = '''beam''' __A : int = 2 __A : List[Any] = 64 __A : Optional[Any] = 256 __A : Any = None __A : str = None __A : Any = st.sidebar.checkbox('''Generation options''') if generate_options: __A : List[Any] = ''' ### Answer generation options The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large) weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with **beam** search, or **sample** from the decoder\'s output probabilities. ''' st.sidebar.markdown(generate_info) __A : str = st.sidebar.selectbox('''Would you like to use beam search or sample an answer?''', ['''beam''', '''sampled''']) __A : Optional[int] = st.sidebar.slider( '''Minimum generation length''', min_value=8, max_value=256, value=64, step=8, format=None, key=None ) __A : Optional[int] = st.sidebar.slider( '''Maximum generation length''', min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": __A : Tuple = st.sidebar.slider('''Beam size''', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: __A : Optional[int] = st.sidebar.slider( '''Nucleus sampling p''', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) __A : Tuple = st.sidebar.slider( '''Temperature''', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) __A : int = None # start main text __A : List[str] = [ '''<MY QUESTION>''', '''How do people make chocolate?''', '''Why do we get a fever when we are sick?''', '''How can different animals perceive different colors?''', '''What is natural language processing?''', '''What\'s the best way to treat a sunburn?''', '''What exactly are vitamins ?''', '''How does nuclear energy provide electricity?''', '''What\'s the difference between viruses and bacteria?''', '''Why are flutes classified as woodwinds when most of them are made out of metal ?''', '''Why do people like drinking coffee even though it tastes so bad?''', '''What happens when wine ages? How does it make the wine taste better?''', '''If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?''', '''How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?''', '''How does New Zealand have so many large bird predators?''', ] __A : Optional[int] = st.selectbox( '''What would you like to ask? ---- select <MY QUESTION> to enter a new query''', questions_list, index=1, ) if question_s == "<MY QUESTION>": __A : List[str] = st.text_input('''Enter your question here:''', '''''') else: __A : str = question_s if st.button('''Show me!'''): if action in [0, 1, 3]: if index_type == "mixed": __A , __A : Union[str, Any] = make_support(question, source=wiki_source, method='''dense''', n_results=10) __A , __A : str = make_support(question, source=wiki_source, method='''sparse''', n_results=10) __A : Tuple = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] __A : Any = support_list[:10] __A : Union[str, Any] = '''<P> ''' + ''' <P> '''.join([res[-1] for res in support_list]) else: __A , __A : Any = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: __A , __A : Dict = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == '''sampled'''), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('''### The model generated answer is:''') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('''--- \n ### The model is drawing information from the following Wikipedia passages:''') for i, res in enumerate(support_list): __A : Union[str, Any] = '''https://en.wikipedia.org/wiki/{}'''.format(res[0].replace(''' ''', '''_''')) __A : str = res[1].strip() if sec_titles == "": __A : List[str] = '''[{}]({})'''.format(res[0], wiki_url) else: __A : Any = sec_titles.split(''' & ''') __A : Any = ''' & '''.join( ['''[{}]({}#{})'''.format(sec.strip(), wiki_url, sec.strip().replace(''' ''', '''_''')) for sec in sec_list] ) st.markdown( '''{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'''.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '''> <span style="font-family:arial; font-size:10pt;">''' + res[-1] + '''</span>''', unsafe_allow_html=True ) if action in [2, 3]: __A : Any = find_nearest_training(question) __A : Optional[Any] = nn_train_list[0] st.markdown( '''--- \n ### The most similar question in the ELI5 training set was: \n\n {}'''.format(train_exple['''title''']) ) __A : Union[str, Any] = [ '''{}. {}'''.format(i + 1, ''' \n'''.join([line.strip() for line in ans.split('''\n''') if line.strip() != ''''''])) for i, (ans, sc) in enumerate(zip(train_exple['''answers''']['''text'''], train_exple['''answers''']['''score'''])) if i == 0 or sc > 2 ] st.markdown('''##### Its answers were: \n\n {}'''.format('''\n'''.join(answers_st))) __A : int = ''' --- **Disclaimer** *The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system. Evaluating biases of such a model and ensuring factual generations are still very much open research problems. Therefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.* ''' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
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 __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : Optional[Any] = parent UpperCamelCase : Union[str, Any] = 13 UpperCamelCase : Optional[int] = 7 UpperCamelCase : List[str] = 30 UpperCamelCase : Optional[Any] = self.seq_length + self.mem_len UpperCamelCase : Dict = 15 UpperCamelCase : List[str] = True UpperCamelCase : str = True UpperCamelCase : int = 99 UpperCamelCase : List[Any] = [10, 50, 80] UpperCamelCase : Union[str, Any] = 32 UpperCamelCase : str = 32 UpperCamelCase : List[str] = 4 UpperCamelCase : Tuple = 8 UpperCamelCase : str = 128 UpperCamelCase : Any = 2 UpperCamelCase : int = 2 UpperCamelCase : str = None UpperCamelCase : Union[str, Any] = 1 UpperCamelCase : Tuple = 0 UpperCamelCase : Union[str, Any] = 3 UpperCamelCase : Optional[Any] = self.vocab_size - 1 UpperCamelCase : List[Any] = 0.01 def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : str = None if self.use_labels: UpperCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : List[str] = TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def a_ ( self ): random.seed(self.seed ) tf.random.set_seed(self.seed ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = TFTransfoXLModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ).to_tuple() UpperCamelCase : Optional[int] = {"""input_ids""": input_ids_a, """mems""": mems_a} UpperCamelCase , UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ ).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = TFTransfoXLLMHeadModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ).to_tuple() UpperCamelCase : Tuple = {"""input_ids""": input_ids_a, """labels""": lm_labels} UpperCamelCase , UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ ).to_tuple() UpperCamelCase , UpperCamelCase : Any = model([input_ids_a, mems_a] ).to_tuple() UpperCamelCase : Tuple = {"""input_ids""": input_ids_a, """mems""": mems_a, """labels""": lm_labels} UpperCamelCase , UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = TFTransfoXLForSequenceClassification(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self ): UpperCamelCase : Any = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : int = config_and_inputs UpperCamelCase : int = {"""input_ids""": input_ids_a} return config, inputs_dict @require_tf class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : List[str] = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) lowercase : List[Any] = () if is_tf_available() else () lowercase : List[str] = ( { 'feature-extraction': TFTransfoXLModel, 'text-classification': TFTransfoXLForSequenceClassification, 'text-generation': TFTransfoXLLMHeadModel, 'zero-shot': TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented lowercase : List[str] = False lowercase : Optional[Any] = False lowercase : Optional[Any] = False lowercase : Dict = False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def a_ ( self ): UpperCamelCase : Optional[int] = TFTransfoXLModelTester(self ) UpperCamelCase : Optional[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , d_embed=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): self.model_tester.set_seed() UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): self.model_tester.set_seed() UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase , UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase : List[str] = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: UpperCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: UpperCamelCase : Tuple = model.get_output_embeddings() assert isinstance(SCREAMING_SNAKE_CASE_ , tf.keras.layers.Layer ) UpperCamelCase : List[Any] = model.get_bias() assert name is None else: UpperCamelCase : Optional[Any] = model.get_output_embeddings() assert x is None UpperCamelCase : Tuple = model.get_bias() assert name is None def a_ ( self ): # TODO JP: Make TransfoXL XLA compliant pass @slow def a_ ( self ): for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = TFTransfoXLModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason="""This model doesn't play well with fit() due to not returning a single loss.""" ) def a_ ( self ): pass @require_tf class lowerCamelCase ( unittest.TestCase ): @unittest.skip("""Skip test until #12651 is resolved.""" ) @slow def a_ ( self ): UpperCamelCase : int = TFTransfoXLLMHeadModel.from_pretrained("""transfo-xl-wt103""" ) # fmt: off UpperCamelCase : Optional[Any] = tf.convert_to_tensor([[33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0]] , dtype=tf.intaa ) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off UpperCamelCase : List[Any] = [33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0,33,1,1857,2,1,1009,4,1109,1_1739,4762,358,5,25,245,28,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> UpperCamelCase : List[Any] = model.generate(SCREAMING_SNAKE_CASE_ , max_length=200 , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].numpy().tolist() , 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_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ): '''simple docstring''' def update_area_of_max_square(snake_case_ : int ,snake_case_ : int ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 UpperCamelCase : Tuple = update_area_of_max_square(snake_case_ ,col + 1 ) UpperCamelCase : Optional[int] = update_area_of_max_square(row + 1 ,col + 1 ) UpperCamelCase : List[str] = update_area_of_max_square(row + 1 ,snake_case_ ) if mat[row][col]: UpperCamelCase : Dict = 1 + min([right, diagonal, down] ) UpperCamelCase : int = max(largest_square_area[0] ,snake_case_ ) return sub_problem_sol else: return 0 UpperCamelCase : Dict = [0] update_area_of_max_square(0 ,0 ) return largest_square_area[0] def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ): '''simple docstring''' def update_area_of_max_square_using_dp_array( snake_case_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] UpperCamelCase : Dict = update_area_of_max_square_using_dp_array(snake_case_ ,col + 1 ,snake_case_ ) UpperCamelCase : Union[str, Any] = update_area_of_max_square_using_dp_array(row + 1 ,col + 1 ,snake_case_ ) UpperCamelCase : Dict = update_area_of_max_square_using_dp_array(row + 1 ,snake_case_ ,snake_case_ ) if mat[row][col]: UpperCamelCase : Optional[Any] = 1 + min([right, diagonal, down] ) UpperCamelCase : List[str] = max(largest_square_area[0] ,snake_case_ ) UpperCamelCase : Optional[Any] = sub_problem_sol return sub_problem_sol else: return 0 UpperCamelCase : Tuple = [0] UpperCamelCase : str = [[-1] * cols for _ in range(snake_case_ )] update_area_of_max_square_using_dp_array(0 ,0 ,snake_case_ ) return largest_square_area[0] def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ): '''simple docstring''' UpperCamelCase : Any = [[0] * (cols + 1) for _ in range(rows + 1 )] UpperCamelCase : Union[str, Any] = 0 for row in range(rows - 1 ,-1 ,-1 ): for col in range(cols - 1 ,-1 ,-1 ): UpperCamelCase : int = dp_array[row][col + 1] UpperCamelCase : Union[str, Any] = dp_array[row + 1][col + 1] UpperCamelCase : List[str] = dp_array[row + 1][col] if mat[row][col] == 1: UpperCamelCase : List[Any] = 1 + min(snake_case_ ,snake_case_ ,snake_case_ ) UpperCamelCase : Optional[int] = max(dp_array[row][col] ,snake_case_ ) else: UpperCamelCase : Optional[int] = 0 return largest_square_area def A_ ( snake_case_ : int ,snake_case_ : int ,snake_case_ : list[list[int]] ): '''simple docstring''' UpperCamelCase : Dict = [0] * (cols + 1) UpperCamelCase : Union[str, Any] = [0] * (cols + 1) UpperCamelCase : Tuple = 0 for row in range(rows - 1 ,-1 ,-1 ): for col in range(cols - 1 ,-1 ,-1 ): UpperCamelCase : int = current_row[col + 1] UpperCamelCase : int = next_row[col + 1] UpperCamelCase : Union[str, Any] = next_row[col] if mat[row][col] == 1: UpperCamelCase : Dict = 1 + min(snake_case_ ,snake_case_ ,snake_case_ ) UpperCamelCase : List[str] = max(current_row[col] ,snake_case_ ) else: UpperCamelCase : List[Any] = 0 UpperCamelCase : Optional[int] = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
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 ..utils import DummyObject, requires_backends class lowerCamelCase ( metaclass=_UpperCAmelCase ): lowercase : List[str] = ['flax', 'transformers'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""flax""", """transformers"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""flax""", """transformers"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""flax""", """transformers"""] ) class lowerCamelCase ( metaclass=_UpperCAmelCase ): lowercase : List[Any] = ['flax', 'transformers'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""flax""", """transformers"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""flax""", """transformers"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""flax""", """transformers"""] ) class lowerCamelCase ( metaclass=_UpperCAmelCase ): lowercase : List[str] = ['flax', 'transformers'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""flax""", """transformers"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""flax""", """transformers"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""flax""", """transformers"""] ) class lowerCamelCase ( metaclass=_UpperCAmelCase ): lowercase : Tuple = ['flax', 'transformers'] def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""flax""", """transformers"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""flax""", """transformers"""] ) @classmethod def a_ ( cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""flax""", """transformers"""] )
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""" def A_ ( snake_case_ : int = 2_0_0_0_0_0_0 ): '''simple docstring''' UpperCamelCase : Optional[int] = [0 for i in range(n + 1 )] UpperCamelCase : Dict = 1 UpperCamelCase : Tuple = 1 for i in range(2 ,int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i ,n + 1 ,snake_case_ ): UpperCamelCase : List[Any] = 1 UpperCamelCase : str = 0 for i in range(snake_case_ ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(F'''{solution() = }''')
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 os import sys import unittest __A : str = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, '''utils''')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) __A : Optional[int] = os.path.join('''tests''', '''models''', '''bert''', '''test_modeling_bert.py''') __A : Dict = os.path.join('''tests''', '''models''', '''blip''', '''test_modeling_blip.py''') class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): UpperCamelCase : str = get_test_to_tester_mapping(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = get_test_to_tester_mapping(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = {"""BertModelTest""": """BertModelTester"""} UpperCamelCase : str = { """BlipModelTest""": """BlipModelTester""", """BlipTextImageModelTest""": """BlipTextImageModelsModelTester""", """BlipTextModelTest""": """BlipTextModelTester""", """BlipTextRetrievalModelTest""": """BlipTextRetrievalModelTester""", """BlipVQAModelTest""": """BlipVQAModelTester""", """BlipVisionModelTest""": """BlipVisionModelTester""", } self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = get_model_to_test_mapping(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = get_model_to_test_mapping(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = { """BertForMaskedLM""": ["""BertModelTest"""], """BertForMultipleChoice""": ["""BertModelTest"""], """BertForNextSentencePrediction""": ["""BertModelTest"""], """BertForPreTraining""": ["""BertModelTest"""], """BertForQuestionAnswering""": ["""BertModelTest"""], """BertForSequenceClassification""": ["""BertModelTest"""], """BertForTokenClassification""": ["""BertModelTest"""], """BertLMHeadModel""": ["""BertModelTest"""], """BertModel""": ["""BertModelTest"""], } UpperCamelCase : int = { """BlipForConditionalGeneration""": ["""BlipTextImageModelTest"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTest"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTest"""], """BlipModel""": ["""BlipModelTest"""], """BlipTextModel""": ["""BlipTextModelTest"""], """BlipVisionModel""": ["""BlipVisionModelTest"""], } self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = get_model_to_tester_mapping(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = get_model_to_tester_mapping(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """BertForMaskedLM""": ["""BertModelTester"""], """BertForMultipleChoice""": ["""BertModelTester"""], """BertForNextSentencePrediction""": ["""BertModelTester"""], """BertForPreTraining""": ["""BertModelTester"""], """BertForQuestionAnswering""": ["""BertModelTester"""], """BertForSequenceClassification""": ["""BertModelTester"""], """BertForTokenClassification""": ["""BertModelTester"""], """BertLMHeadModel""": ["""BertModelTester"""], """BertModel""": ["""BertModelTester"""], } UpperCamelCase : Union[str, Any] = { """BlipForConditionalGeneration""": ["""BlipTextImageModelsModelTester"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTester"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTester"""], """BlipModel""": ["""BlipModelTester"""], """BlipTextModel""": ["""BlipTextModelTester"""], """BlipVisionModel""": ["""BlipVisionModelTester"""], } self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ) , 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 warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor __A : List[Any] = logging.get_logger(__name__) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): warnings.warn( """The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use DeiTImageProcessor instead.""" , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
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 __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase : List[str] = parent UpperCamelCase : Tuple = 13 UpperCamelCase : Optional[Any] = 7 UpperCamelCase : List[Any] = True UpperCamelCase : List[str] = True UpperCamelCase : str = False UpperCamelCase : Dict = True UpperCamelCase : Tuple = 99 UpperCamelCase : int = 32 UpperCamelCase : Any = 2 UpperCamelCase : Union[str, Any] = 4 UpperCamelCase : Optional[int] = 37 UpperCamelCase : Any = """gelu""" UpperCamelCase : Any = 0.1 UpperCamelCase : Any = 0.1 UpperCamelCase : Optional[int] = 512 UpperCamelCase : List[Any] = 16 UpperCamelCase : Any = 2 UpperCamelCase : List[Any] = 0.02 UpperCamelCase : List[str] = 3 UpperCamelCase : int = 4 UpperCamelCase : str = None def a_ ( self ): UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Any = None if self.use_input_mask: UpperCamelCase : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Tuple = None UpperCamelCase : List[str] = None UpperCamelCase : Any = None if self.use_labels: UpperCamelCase : List[str] = 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 : str = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : List[Any] = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = TFDistilBertModel(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = {"""input_ids""": input_ids, """attention_mask""": input_mask} UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = [input_ids, input_mask] UpperCamelCase : List[str] = 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 : List[Any] = TFDistilBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = {"""input_ids""": input_ids, """attention_mask""": input_mask} UpperCamelCase : Tuple = model(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 : Union[str, Any] = TFDistilBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = { """input_ids""": input_ids, """attention_mask""": input_mask, } UpperCamelCase : List[str] = model(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 : List[Any] = self.num_labels UpperCamelCase : Tuple = TFDistilBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = {"""input_ids""": input_ids, """attention_mask""": input_mask} UpperCamelCase : Optional[Any] = model(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 : str = self.num_choices UpperCamelCase : Tuple = TFDistilBertForMultipleChoice(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : Tuple = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : Union[str, Any] = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } UpperCamelCase : str = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = self.num_labels UpperCamelCase : str = TFDistilBertForTokenClassification(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self ): UpperCamelCase : int = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : int = config_and_inputs UpperCamelCase : str = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Tuple = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) lowercase : Tuple = ( { 'feature-extraction': TFDistilBertModel, 'fill-mask': TFDistilBertForMaskedLM, 'question-answering': TFDistilBertForQuestionAnswering, 'text-classification': TFDistilBertForSequenceClassification, 'token-classification': TFDistilBertForTokenClassification, 'zero-shot': TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) lowercase : Any = False lowercase : int = False def a_ ( self ): UpperCamelCase : Any = TFDistilBertModelTester(self ) UpperCamelCase : Optional[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_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_distilbert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): UpperCamelCase : Optional[int] = TFDistilBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_tf class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : List[str] = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) UpperCamelCase : Union[str, Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : List[Any] = [1, 6, 768] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = tf.constant( [ [ [0.19261885, -0.13732955, 0.4119799], [0.22150156, -0.07422661, 0.39037204], [0.22756018, -0.0896414, 0.3701467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 )
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 math def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : str = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(snake_case_ ) def A_ ( snake_case_ : float = 1 / 1_2_3_4_5 ): '''simple docstring''' UpperCamelCase : str = 0 UpperCamelCase : Dict = 0 UpperCamelCase : Dict = 3 while True: UpperCamelCase : Union[str, Any] = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(snake_case_ ): UpperCamelCase : List[str] = int(snake_case_ ) total_partitions += 1 if check_partition_perfect(snake_case_ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(snake_case_ ) integer += 1 if __name__ == "__main__": print(F'''{solution() = }''')
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 gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.schedulers import KarrasDiffusionSchedulers 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 ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' UpperCamelCase : Dict = [tensor.shape for tensor in tensor_list] return all(shape == shapes[0] for shape in shapes[1:] ) class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : str = StableDiffusionLatentUpscalePipeline lowercase : Tuple = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { 'height', 'width', 'cross_attention_kwargs', 'negative_prompt_embeds', 'prompt_embeds', } lowercase : str = PipelineTesterMixin.required_optional_params - {'num_images_per_prompt'} lowercase : Tuple = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowercase : Optional[Any] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowercase : List[str] = frozenset([] ) lowercase : str = True @property def a_ ( self ): UpperCamelCase : Tuple = 1 UpperCamelCase : List[str] = 4 UpperCamelCase : str = (16, 16) UpperCamelCase : List[Any] = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE_ ) return image def a_ ( self ): torch.manual_seed(0 ) UpperCamelCase : Optional[int] = UNetaDConditionModel( act_fn="""gelu""" , attention_head_dim=8 , norm_num_groups=SCREAMING_SNAKE_CASE_ , block_out_channels=[32, 32, 64, 64] , time_cond_proj_dim=160 , conv_in_kernel=1 , conv_out_kernel=1 , cross_attention_dim=32 , down_block_types=( """KDownBlock2D""", """KCrossAttnDownBlock2D""", """KCrossAttnDownBlock2D""", """KCrossAttnDownBlock2D""", ) , in_channels=8 , mid_block_type=SCREAMING_SNAKE_CASE_ , only_cross_attention=SCREAMING_SNAKE_CASE_ , out_channels=5 , resnet_time_scale_shift="""scale_shift""" , time_embedding_type="""fourier""" , timestep_post_act="""gelu""" , up_block_types=("""KCrossAttnUpBlock2D""", """KCrossAttnUpBlock2D""", """KCrossAttnUpBlock2D""", """KUpBlock2D""") , ) UpperCamelCase : Optional[Any] = AutoencoderKL( block_out_channels=[32, 32, 64, 64] , in_channels=3 , out_channels=3 , down_block_types=[ """DownEncoderBlock2D""", """DownEncoderBlock2D""", """DownEncoderBlock2D""", """DownEncoderBlock2D""", ] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D""", """UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) UpperCamelCase : Optional[int] = EulerDiscreteScheduler(prediction_type="""sample""" ) UpperCamelCase : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""quick_gelu""" , projection_dim=512 , ) UpperCamelCase : int = CLIPTextModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) UpperCamelCase : Tuple = { """unet""": model.eval(), """vae""": vae.eval(), """scheduler""": scheduler, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase : Any = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Optional[int] = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = { """prompt""": """A painting of a squirrel eating a burger""", """image""": self.dummy_image.cpu(), """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def a_ ( self ): UpperCamelCase : Union[str, Any] = """cpu""" UpperCamelCase : Optional[Any] = self.get_dummy_components() UpperCamelCase : int = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = pipe(**SCREAMING_SNAKE_CASE_ ).images UpperCamelCase : Tuple = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 256, 256, 3) ) UpperCamelCase : Optional[int] = np.array( [0.47222412, 0.41921633, 0.44717434, 0.46874192, 0.42588258, 0.46150726, 0.4677534, 0.45583832, 0.48579055] ) UpperCamelCase : List[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1e-3 ) def a_ ( self ): super().test_attention_slicing_forward_pass(expected_max_diff=7e-3 ) def a_ ( self ): super().test_cpu_offload_forward_pass(expected_max_diff=3e-3 ) def a_ ( self ): super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def a_ ( self ): super().test_inference_batch_single_identical(expected_max_diff=7e-3 ) def a_ ( self ): super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3 ) def a_ ( self ): super().test_save_load_local(expected_max_difference=3e-3 ) def a_ ( self ): super().test_save_load_optional_components(expected_max_difference=3e-3 ) def a_ ( self ): UpperCamelCase : Dict = [ """DDIMScheduler""", """DDPMScheduler""", """PNDMScheduler""", """HeunDiscreteScheduler""", """EulerAncestralDiscreteScheduler""", """KDPM2DiscreteScheduler""", """KDPM2AncestralDiscreteScheduler""", """DPMSolverSDEScheduler""", ] UpperCamelCase : List[Any] = self.get_dummy_components() UpperCamelCase : Tuple = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) # make sure that PNDM does not need warm-up pipe.scheduler.register_to_config(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = 2 UpperCamelCase : Dict = [] for scheduler_enum in KarrasDiffusionSchedulers: if scheduler_enum.name in skip_schedulers: # no sigma schedulers are not supported # no schedulers continue UpperCamelCase : Optional[int] = getattr(SCREAMING_SNAKE_CASE_ , scheduler_enum.name ) UpperCamelCase : Optional[int] = scheduler_cls.from_config(pipe.scheduler.config ) UpperCamelCase : Dict = pipe(**SCREAMING_SNAKE_CASE_ )[0] outputs.append(SCREAMING_SNAKE_CASE_ ) assert check_same_shape(SCREAMING_SNAKE_CASE_ ) @require_torch_gpu @slow class lowerCamelCase ( unittest.TestCase ): def a_ ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self ): UpperCamelCase : Tuple = torch.manual_seed(33 ) UpperCamelCase : List[Any] = StableDiffusionPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" , torch_dtype=torch.floataa ) pipe.to("""cuda""" ) UpperCamelCase : List[str] = StableDiffusionLatentUpscalePipeline.from_pretrained( """stabilityai/sd-x2-latent-upscaler""" , torch_dtype=torch.floataa ) upscaler.to("""cuda""" ) UpperCamelCase : Optional[Any] = """a photo of an astronaut high resolution, unreal engine, ultra realistic""" UpperCamelCase : str = pipe(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , output_type="""latent""" ).images UpperCamelCase : Tuple = upscaler( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , num_inference_steps=20 , guidance_scale=0 , generator=SCREAMING_SNAKE_CASE_ , output_type="""np""" , ).images[0] UpperCamelCase : Tuple = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy""" ) assert np.abs((expected_image - image).mean() ) < 5e-2 def a_ ( self ): UpperCamelCase : List[Any] = torch.manual_seed(33 ) UpperCamelCase : List[Any] = StableDiffusionLatentUpscalePipeline.from_pretrained( """stabilityai/sd-x2-latent-upscaler""" , torch_dtype=torch.floataa ) upscaler.to("""cuda""" ) UpperCamelCase : List[str] = """the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas""" UpperCamelCase : List[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png""" ) UpperCamelCase : List[str] = upscaler( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , num_inference_steps=20 , guidance_scale=0 , generator=SCREAMING_SNAKE_CASE_ , output_type="""np""" , ).images[0] UpperCamelCase : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy""" ) assert np.abs((expected_image - image).max() ) < 5e-2
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""" # coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import sys import transformers __A : Dict = '''3''' print('''Python version:''', sys.version) print('''transformers version:''', transformers.__version__) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) print('''NCCL version:''', torch.cuda.nccl.version()) except ImportError: print('''Torch version:''', None) try: import deepspeed print('''DeepSpeed version:''', deepspeed.__version__) except ImportError: print('''DeepSpeed version:''', None) try: import tensorflow as tf print('''TensorFlow version:''', tf.__version__) print('''TF GPUs available:''', bool(tf.config.list_physical_devices('''GPU'''))) print('''Number of TF GPUs available:''', len(tf.config.list_physical_devices('''GPU'''))) except ImportError: print('''TensorFlow version:''', None)
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 typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A : Dict = { '''configuration_pix2struct''': [ '''PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Pix2StructConfig''', '''Pix2StructTextConfig''', '''Pix2StructVisionConfig''', ], '''processing_pix2struct''': ['''Pix2StructProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = ['''Pix2StructImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ '''PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Pix2StructPreTrainedModel''', '''Pix2StructForConditionalGeneration''', '''Pix2StructVisionModel''', '''Pix2StructTextModel''', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
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 TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __A : List[str] = { '''configuration_blip''': [ '''BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BlipConfig''', '''BlipTextConfig''', '''BlipVisionConfig''', ], '''processing_blip''': ['''BlipProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = ['''BlipImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[Any] = [ '''BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BlipModel''', '''BlipPreTrainedModel''', '''BlipForConditionalGeneration''', '''BlipForQuestionAnswering''', '''BlipVisionModel''', '''BlipTextModel''', '''BlipForImageTextRetrieval''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Dict = [ '''TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFBlipModel''', '''TFBlipPreTrainedModel''', '''TFBlipForConditionalGeneration''', '''TFBlipForQuestionAnswering''', '''TFBlipVisionModel''', '''TFBlipTextModel''', '''TFBlipForImageTextRetrieval''', ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys __A : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
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 from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A : Optional[Any] = {'''configuration_van''': ['''VAN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VanConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ '''VAN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''VanForImageClassification''', '''VanModel''', '''VanPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_van import ( VAN_PRETRAINED_MODEL_ARCHIVE_LIST, VanForImageClassification, VanModel, VanPreTrainedModel, ) else: import sys __A : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
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 typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A : List[str] = { '''configuration_luke''': ['''LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LukeConfig'''], '''tokenization_luke''': ['''LukeTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ '''LUKE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LukeForEntityClassification''', '''LukeForEntityPairClassification''', '''LukeForEntitySpanClassification''', '''LukeForMultipleChoice''', '''LukeForQuestionAnswering''', '''LukeForSequenceClassification''', '''LukeForTokenClassification''', '''LukeForMaskedLM''', '''LukeModel''', '''LukePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys __A : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
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 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
"""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 unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Optional[Any] ,snake_case_ : int ,snake_case_ : str ): '''simple docstring''' if isinstance(snake_case_ ,snake_case_ ): UpperCamelCase : Any = np.full((len(snake_case_ ), sequence_length, 2) ,snake_case_ ) else: UpperCamelCase : Dict = np.full((len(snake_case_ ), sequence_length) ,snake_case_ ) for i, tensor in enumerate(snake_case_ ): if padding_side == "right": if isinstance(snake_case_ ,snake_case_ ): UpperCamelCase : str = tensor[:sequence_length] else: UpperCamelCase : Any = tensor[:sequence_length] else: if isinstance(snake_case_ ,snake_case_ ): UpperCamelCase : int = tensor[:sequence_length] else: UpperCamelCase : str = tensor[:sequence_length] return out_tensor.tolist() def A_ ( snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : Optional[int] = ord(snake_case_ ) if (cp >= 3_3 and cp <= 4_7) or (cp >= 5_8 and cp <= 6_4) or (cp >= 9_1 and cp <= 9_6) or (cp >= 1_2_3 and cp <= 1_2_6): return True UpperCamelCase : Optional[Any] = unicodedata.category(snake_case_ ) if cat.startswith("""P""" ): return True return False @dataclass class lowerCamelCase ( _UpperCAmelCase ): lowercase : PreTrainedTokenizerBase lowercase : Union[bool, str, PaddingStrategy] = True lowercase : Optional[int] = None lowercase : Optional[int] = None lowercase : int = -1_0_0 lowercase : str = "pt" def a_ ( self , SCREAMING_SNAKE_CASE_ ): import torch UpperCamelCase : str = """label""" if """label""" in features[0].keys() else """labels""" UpperCamelCase : Optional[int] = [feature[label_name] for feature in features] if label_name in features[0].keys() else None UpperCamelCase : Union[str, Any] = self.tokenizer.pad( SCREAMING_SNAKE_CASE_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="""pt""" if labels is None else None , ) if labels is None: return batch UpperCamelCase : Tuple = torch.tensor(batch["""entity_ids"""] ).shape[1] UpperCamelCase : Any = self.tokenizer.padding_side if padding_side == "right": UpperCamelCase : str = [ list(SCREAMING_SNAKE_CASE_ ) + [self.label_pad_token_id] * (sequence_length - len(SCREAMING_SNAKE_CASE_ )) for label in labels ] else: UpperCamelCase : List[Any] = [ [self.label_pad_token_id] * (sequence_length - len(SCREAMING_SNAKE_CASE_ )) + list(SCREAMING_SNAKE_CASE_ ) for label in labels ] UpperCamelCase : List[Any] = [feature["""ner_tags"""] for feature in features] UpperCamelCase : List[Any] = padding_tensor(SCREAMING_SNAKE_CASE_ , -1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = [feature["""original_entity_spans"""] for feature in features] UpperCamelCase : Dict = padding_tensor(SCREAMING_SNAKE_CASE_ , (-1, -1) , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = {k: torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.intaa ) for k, v in batch.items()} return batch
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 __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=36 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=1000 , ): UpperCamelCase : Union[str, Any] = parent UpperCamelCase : Optional[Any] = batch_size UpperCamelCase : List[str] = num_channels UpperCamelCase : Optional[Any] = image_size UpperCamelCase : Tuple = patch_size UpperCamelCase : Union[str, Any] = is_training UpperCamelCase : Dict = use_input_mask UpperCamelCase : Optional[Any] = use_token_type_ids UpperCamelCase : Union[str, Any] = use_labels UpperCamelCase : Optional[Any] = vocab_size UpperCamelCase : str = hidden_size UpperCamelCase : str = num_hidden_layers UpperCamelCase : Optional[int] = num_attention_heads UpperCamelCase : List[Any] = intermediate_size UpperCamelCase : Any = hidden_act UpperCamelCase : Dict = hidden_dropout_prob UpperCamelCase : Tuple = attention_probs_dropout_prob UpperCamelCase : Tuple = max_position_embeddings UpperCamelCase : int = type_vocab_size UpperCamelCase : Tuple = type_sequence_label_size UpperCamelCase : Any = initializer_range UpperCamelCase : List[str] = coordinate_size UpperCamelCase : int = shape_size UpperCamelCase : Tuple = num_labels UpperCamelCase : Union[str, Any] = num_choices UpperCamelCase : Optional[Any] = scope UpperCamelCase : Tuple = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) UpperCamelCase : Dict = text_seq_length UpperCamelCase : Optional[int] = (image_size // patch_size) ** 2 + 1 UpperCamelCase : int = self.text_seq_length + self.image_seq_length def a_ ( self ): UpperCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) UpperCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) UpperCamelCase : Optional[Any] = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCamelCase : Optional[Any] = bbox[i, j, 3] UpperCamelCase : Optional[Any] = bbox[i, j, 1] UpperCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: UpperCamelCase : Union[str, Any] = bbox[i, j, 2] UpperCamelCase : List[Any] = bbox[i, j, 0] UpperCamelCase : Dict = tmp_coordinate UpperCamelCase : Optional[int] = tf.constant(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase : List[Any] = None if self.use_input_mask: UpperCamelCase : Optional[int] = random_attention_mask([self.batch_size, self.text_seq_length] ) UpperCamelCase : int = None if self.use_token_type_ids: UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) UpperCamelCase : List[Any] = None UpperCamelCase : List[Any] = None if self.use_labels: UpperCamelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) UpperCamelCase : Optional[Any] = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = TFLayoutLMvaModel(config=SCREAMING_SNAKE_CASE_ ) # text + image UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only UpperCamelCase : Dict = model({"""pixel_values""": pixel_values} , training=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_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_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : List[Any] = TFLayoutLMvaForSequenceClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model( SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=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 , 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] = self.num_labels UpperCamelCase : Optional[Any] = TFLayoutLMvaForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model( SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_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_ ): UpperCamelCase : Union[str, Any] = 2 UpperCamelCase : int = TFLayoutLMvaForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = model( SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , training=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 ): UpperCamelCase : Dict = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Tuple = config_and_inputs UpperCamelCase : List[Any] = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_tf class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : List[Any] = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) lowercase : Union[str, Any] = ( {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel} if is_tf_available() else {} ) lowercase : int = False lowercase : List[str] = False lowercase : int = False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return True def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Any = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) if model_class in get_values(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = { k: tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(SCREAMING_SNAKE_CASE_ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) UpperCamelCase : Union[str, Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def a_ ( self ): UpperCamelCase : Any = TFLayoutLMvaModelTester(self ) UpperCamelCase : Tuple = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase , UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : Optional[int] = model_class(SCREAMING_SNAKE_CASE_ ) if getattr(SCREAMING_SNAKE_CASE_ , """hf_compute_loss""" , SCREAMING_SNAKE_CASE_ ): # The number of elements in the loss should be the same as the number of elements in the label UpperCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=SCREAMING_SNAKE_CASE_ )[0] ] UpperCamelCase : str = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs UpperCamelCase : int = self._prepare_for_class(inputs_dict.copy() , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = prepared_for_class.pop("""input_ids""" ) UpperCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions UpperCamelCase : Optional[Any] = self._prepare_for_class(inputs_dict.copy() , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = prepared_for_class.pop("""input_ids""" ) if "labels" in prepared_for_class: UpperCamelCase : Optional[Any] = prepared_for_class["""labels"""].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: UpperCamelCase : Optional[Any] = -100 UpperCamelCase : Any = tf.convert_to_tensor(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = model(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict UpperCamelCase : str = self._prepare_for_class(inputs_dict.copy() , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple UpperCamelCase : Any = self._prepare_for_class(inputs_dict.copy() , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) # Get keys that were added with the _prepare_for_class function UpperCamelCase : Tuple = prepared_for_class.keys() - inputs_dict.keys() UpperCamelCase : Optional[Any] = inspect.signature(model.call ).parameters UpperCamelCase : int = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple UpperCamelCase : List[Any] = {0: """input_ids"""} for label_key in label_keys: UpperCamelCase : List[str] = signature_names.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = label_key UpperCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple UpperCamelCase : Tuple = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: UpperCamelCase : Dict = prepared_for_class[value] UpperCamelCase : Tuple = tuple(SCREAMING_SNAKE_CASE_ ) # Send to model UpperCamelCase : str = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def a_ ( self ): ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase : str = type self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def a_ ( self ): ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : int = TFLayoutLMvaModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf class lowerCamelCase ( unittest.TestCase ): @cached_property def a_ ( self ): return LayoutLMvaImageProcessor(apply_ocr=SCREAMING_SNAKE_CASE_ ) if is_vision_available() else None @slow def a_ ( self ): UpperCamelCase : Any = TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ) UpperCamelCase : Optional[int] = self.default_image_processor UpperCamelCase : str = prepare_img() UpperCamelCase : List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors="""tf""" ).pixel_values UpperCamelCase : List[Any] = tf.constant([[1, 2]] ) UpperCamelCase : Dict = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass UpperCamelCase : Union[str, Any] = model(input_ids=SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase : Union[str, Any] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
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 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
"""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 copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class lowerCamelCase ( _UpperCAmelCase ): def a_ ( self ): UpperCamelCase : Optional[int] = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def a_ ( self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def a_ ( self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""bool""" ) , type=Value("""int64""" ) ) ) def a_ ( self ): UpperCamelCase : Tuple = pa.array(TypedSequence([1, 2, 3] , type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def a_ ( self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase : int = pa.array(TypedSequence(["""foo""", """bar"""] , type=Value("""int64""" ) ) ) def a_ ( self ): UpperCamelCase : Dict = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def a_ ( self ): UpperCamelCase : List[str] = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=Value("""int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) def a_ ( self ): UpperCamelCase : List[Any] = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def a_ ( self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase : Tuple = pa.array(TypedSequence(["""foo""", """bar"""] , type=ArrayaD((1, 3) , """int64""" ) ) ) def a_ ( self ): UpperCamelCase : List[str] = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def a_ ( self ): UpperCamelCase : int = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def a_ ( self ): import PIL.Image UpperCamelCase : List[str] = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( """datasets.arrow_writer.cast_to_python_objects""" , side_effect=SCREAMING_SNAKE_CASE_ ) as mock_cast_to_python_objects: UpperCamelCase : Optional[int] = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image] , type=Image() ) ) UpperCamelCase , UpperCamelCase : Tuple = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("""optimize_list_casting""" , SCREAMING_SNAKE_CASE_ ) self.assertFalse(kwargs["""optimize_list_casting"""] ) def A_ ( snake_case_ : Any ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : str = pa.BufferReader(snake_case_ ) if isinstance(snake_case_ ,pa.Buffer ) else pa.memory_map(snake_case_ ) UpperCamelCase : List[Any] = pa.ipc.open_stream(snake_case_ ) UpperCamelCase : pa.Table = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 1_0] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def A_ ( snake_case_ : int ,snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Optional[Any] = pa.BufferOutputStream() UpperCamelCase : str = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ ,schema=snake_case_ ,writer_batch_size=snake_case_ ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase , UpperCamelCase : Optional[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : Union[str, Any] = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(snake_case_ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def A_ ( ): '''simple docstring''' UpperCamelCase : Any = pa.BufferOutputStream() UpperCamelCase : str = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""] )} ) with ArrowWriter(stream=snake_case_ ,features=snake_case_ ) as writer: writer.write({"""labels""": 0} ) writer.write({"""labels""": 1} ) UpperCamelCase , UpperCamelCase : Any = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata UpperCamelCase : Tuple = pa.BufferReader(output.getvalue() ) UpperCamelCase : Union[str, Any] = pa.ipc.open_stream(snake_case_ ) UpperCamelCase : pa.Table = f.read_all() UpperCamelCase : List[Any] = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(snake_case_ ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 1_0] ) def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' UpperCamelCase : List[Any] = pa.BufferOutputStream() with ArrowWriter( stream=snake_case_ ,writer_batch_size=snake_case_ ,hash_salt="""split_name""" ,check_duplicates=snake_case_ ,) as writer: with pytest.raises(snake_case_ ): writer.write({"""col_1""": """foo""", """col_2""": 1} ,key=[1, 2] ) UpperCamelCase , UpperCamelCase : int = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" ,[None, 2, 1_0] ) def A_ ( snake_case_ : Optional[int] ): '''simple docstring''' UpperCamelCase : Optional[int] = pa.BufferOutputStream() with ArrowWriter( stream=snake_case_ ,writer_batch_size=snake_case_ ,hash_salt="""split_name""" ,check_duplicates=snake_case_ ,) as writer: with pytest.raises(snake_case_ ): writer.write({"""col_1""": """foo""", """col_2""": 1} ,key=1_0 ) writer.write({"""col_1""": """bar""", """col_2""": 2} ,key=1_0 ) UpperCamelCase , UpperCamelCase : Any = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" ,[None, 2, 1_0] ) def A_ ( snake_case_ : Any ): '''simple docstring''' UpperCamelCase : List[Any] = pa.BufferOutputStream() with ArrowWriter( stream=snake_case_ ,writer_batch_size=snake_case_ ,hash_salt="""split_name""" ,check_duplicates=snake_case_ ,) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ,key=1 ) writer.write({"""col_1""": """bar""", """col_2""": 2} ,key=2 ) UpperCamelCase , UpperCamelCase : Dict = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 1_0] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def A_ ( snake_case_ : Optional[int] ,snake_case_ : int ): '''simple docstring''' UpperCamelCase : Any = pa.BufferOutputStream() UpperCamelCase : Optional[Any] = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ ,schema=snake_case_ ,writer_batch_size=snake_case_ ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) writer.write_batch({"""col_1""": [], """col_2""": []} ) UpperCamelCase , UpperCamelCase : Dict = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : str = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(snake_case_ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 1_0] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def A_ ( snake_case_ : Any ,snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : Any = pa.BufferOutputStream() UpperCamelCase : Dict = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ ,schema=snake_case_ ,writer_batch_size=snake_case_ ) as writer: writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) ) UpperCamelCase , UpperCamelCase : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : Union[str, Any] = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(snake_case_ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" ,[None, 1, 1_0] ) @pytest.mark.parametrize( """fields""" ,[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Optional[Any] ): '''simple docstring''' UpperCamelCase : Tuple = pa.BufferOutputStream() UpperCamelCase : Tuple = pa.schema(snake_case_ ) if fields else None with ArrowWriter(stream=snake_case_ ,schema=snake_case_ ,writer_batch_size=snake_case_ ) as writer: writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]} ) ) writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]} ) ) UpperCamelCase , UpperCamelCase : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : List[Any] = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(snake_case_ ,metadata=writer._schema.metadata ) _check_output(output.getvalue() ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def A_ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase : List[Any] = {"""col_1""": pa.string(), """col_2""": pa.intaa()} UpperCamelCase : Any = os.path.join(snake_case_ ,"""test.arrow""" ) with ArrowWriter(path=snake_case_ ,schema=pa.schema(snake_case_ ) ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) UpperCamelCase , UpperCamelCase : List[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(snake_case_ ,metadata=writer._schema.metadata ) _check_output(snake_case_ ,1 ) def A_ ( snake_case_ : Dict ): '''simple docstring''' if pa.types.is_list(snake_case_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def A_ ( snake_case_ : Optional[int] ,snake_case_ : Dict ): '''simple docstring''' if isinstance(lst[0] ,snake_case_ ): change_first_primitive_element_in_list(lst[0] ,snake_case_ ) else: UpperCamelCase : List[Any] = value @pytest.mark.parametrize("""optimized_int_type, expected_dtype""" ,[(None, pa.intaa()), (Value("""int32""" ), pa.intaa())] ) @pytest.mark.parametrize("""sequence""" ,[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def A_ ( snake_case_ : Tuple ,snake_case_ : List[Any] ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Optional[Any] = pa.array(TypedSequence(snake_case_ ,optimized_int_type=snake_case_ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( """col, expected_dtype""" ,[ ("""attention_mask""", pa.inta()), ("""special_tokens_mask""", pa.inta()), ("""token_type_ids""", pa.inta()), ("""input_ids""", pa.intaa()), ("""other""", pa.intaa()), ] ,) @pytest.mark.parametrize("""sequence""" ,[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def A_ ( snake_case_ : Union[str, Any] ,snake_case_ : Union[str, Any] ,snake_case_ : str ): '''simple docstring''' # in range UpperCamelCase : str = pa.array(OptimizedTypedSequence(snake_case_ ,col=snake_case_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications UpperCamelCase : str = copy.deepcopy(snake_case_ ) UpperCamelCase : Tuple = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(snake_case_ ,snake_case_ ) UpperCamelCase : int = pa.array(OptimizedTypedSequence(snake_case_ ,col=snake_case_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("""raise_exception""" ,[False, True] ) def A_ ( snake_case_ : Dict ,snake_case_ : Tuple ): '''simple docstring''' UpperCamelCase : Tuple = str(tmp_path / """dataset-train.arrow""" ) try: with ArrowWriter(path=snake_case_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def A_ ( snake_case_ : List[str] ): '''simple docstring''' UpperCamelCase : Dict = """mock://dataset-train.arrow""" with ArrowWriter(path=snake_case_ ,storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs ,type(snake_case_ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase , UpperCamelCase : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : Union[str, Any] = pa.BufferOutputStream() with ParquetWriter(stream=snake_case_ ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase , UpperCamelCase : List[str] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 UpperCamelCase : List[str] = pa.BufferReader(output.getvalue() ) UpperCamelCase : pa.Table = pq.read_table(snake_case_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("""embed_local_files""" ,[False, True] ) def A_ ( snake_case_ : str ,snake_case_ : List[Any] ): '''simple docstring''' import PIL.Image UpperCamelCase : Optional[Any] = str(tmp_path / """test_image_rgb.jpg""" ) PIL.Image.fromarray(np.zeros((5, 5) ,dtype=np.uinta ) ).save(snake_case_ ,format="""png""" ) UpperCamelCase : List[str] = pa.BufferOutputStream() with ParquetWriter( stream=snake_case_ ,features=Features({"""image""": Image()} ) ,embed_local_files=snake_case_ ) as writer: writer.write({"""image""": image_path} ) writer.finalize() UpperCamelCase : Union[str, Any] = pa.BufferReader(output.getvalue() ) UpperCamelCase : pa.Table = pq.read_table(snake_case_ ) UpperCamelCase : Any = pa_table.to_pydict() if embed_local_files: assert isinstance(out["""image"""][0]["""path"""] ,snake_case_ ) with open(snake_case_ ,"""rb""" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def A_ ( ): '''simple docstring''' UpperCamelCase : int = pa.schema([pa.field("""col_1""" ,pa.string() ,nullable=snake_case_ )] ) UpperCamelCase : Dict = pa.BufferOutputStream() with ArrowWriter(stream=snake_case_ ) as writer: writer._build_writer(inferred_schema=snake_case_ ) assert writer._schema == pa.schema([pa.field("""col_1""" ,pa.string() )] )
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""" # using dfs for finding eulerian path traversal def A_ ( snake_case_ : List[Any] ,snake_case_ : Any ,snake_case_ : Optional[Any] ,snake_case_ : Dict=None ): '''simple docstring''' UpperCamelCase : str = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: UpperCamelCase , UpperCamelCase : Any = True, True UpperCamelCase : Optional[Any] = dfs(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) return path def A_ ( snake_case_ : List[Any] ,snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : int = 0 UpperCamelCase : Any = -1 for i in range(snake_case_ ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 UpperCamelCase : int = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def A_ ( snake_case_ : int ,snake_case_ : List[Any] ): '''simple docstring''' UpperCamelCase : int = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] UpperCamelCase , UpperCamelCase : int = check_circuit_or_path(snake_case_ ,snake_case_ ) if check == 3: print("""graph is not Eulerian""" ) print("""no path""" ) return UpperCamelCase : str = 1 if check == 2: UpperCamelCase : Optional[Any] = odd_node print("""graph has a Euler path""" ) if check == 1: print("""graph has a Euler cycle""" ) UpperCamelCase : Tuple = dfs(snake_case_ ,snake_case_ ,snake_case_ ) print(snake_case_ ) def A_ ( ): '''simple docstring''' UpperCamelCase : Optional[int] = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} UpperCamelCase : int = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} UpperCamelCase : Union[str, Any] = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} UpperCamelCase : List[Any] = {1: [2, 3], 2: [1, 3], 3: [1, 2]} UpperCamelCase : int = { 1: [], 2: [] # all degree is zero } UpperCamelCase : Any = 1_0 check_euler(snake_case_ ,snake_case_ ) check_euler(snake_case_ ,snake_case_ ) check_euler(snake_case_ ,snake_case_ ) check_euler(snake_case_ ,snake_case_ ) check_euler(snake_case_ ,snake_case_ ) if __name__ == "__main__": 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""" def A_ ( snake_case_ : list[list[int]] ,snake_case_ : int ,snake_case_ : int ,snake_case_ : set ): '''simple docstring''' UpperCamelCase , UpperCamelCase : int = len(snake_case_ ), len(grid[0] ) if ( min(snake_case_ ,snake_case_ ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) UpperCamelCase : Optional[int] = 0 count += depth_first_search(snake_case_ ,row + 1 ,snake_case_ ,snake_case_ ) count += depth_first_search(snake_case_ ,row - 1 ,snake_case_ ,snake_case_ ) count += depth_first_search(snake_case_ ,snake_case_ ,col + 1 ,snake_case_ ) count += depth_first_search(snake_case_ ,snake_case_ ,col - 1 ,snake_case_ ) visit.remove((row, col) ) return count if __name__ == "__main__": 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""" from __future__ import annotations def A_ ( snake_case_ : list[int | str] ): '''simple docstring''' create_state_space_tree(snake_case_ ,[] ,0 ,[0 for i in range(len(snake_case_ ) )] ) def A_ ( snake_case_ : list[int | str] ,snake_case_ : list[int | str] ,snake_case_ : int ,snake_case_ : list[int] ,): '''simple docstring''' if index == len(snake_case_ ): print(snake_case_ ) return for i in range(len(snake_case_ ) ): if not index_used[i]: current_sequence.append(sequence[i] ) UpperCamelCase : Optional[int] = True create_state_space_tree(snake_case_ ,snake_case_ ,index + 1 ,snake_case_ ) current_sequence.pop() UpperCamelCase : List[str] = False __A : list[int | str] = [3, 1, 2, 4] generate_all_permutations(sequence) __A : list[int | str] = ["A", "B", "C"] generate_all_permutations(sequence_a)
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 ...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
"""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 argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() __A : List[Any] = logging.get_logger(__name__) __A : Any = torch.device('''cpu''') def A_ ( ): '''simple docstring''' UpperCamelCase : Optional[Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" UpperCamelCase : List[str] = Image.open(requests.get(snake_case_ ,stream=snake_case_ ).raw ) return im def A_ ( snake_case_ : List[str] ): '''simple docstring''' if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.17_03e00, 2.11_07e00, -2.08_11e00, 8.86_85e-01, 2.43_60e-01] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.96_36e-01, 2.34_78e-01, -1.69_63e00, -1.73_81e00, -8.63_37e-01] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.27_68e-01, -4.74_29e-01, -1.08_97e00, -1.02_48e00, 3.55_23e-02] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.53_30e-01, 2.42_11e-01, -6.01_85e-01, -8.27_89e-01, -6.04_46e-02] ) def A_ ( snake_case_ : str ,snake_case_ : Tuple ,snake_case_ : Any ): '''simple docstring''' UpperCamelCase : Any = dct.pop(snake_case_ ) UpperCamelCase : List[Any] = val def A_ ( snake_case_ : Dict ): '''simple docstring''' UpperCamelCase : Optional[Any] = [] for k in state_dict.keys(): UpperCamelCase : int = k if ".pwconv" in k: UpperCamelCase : Optional[int] = k_new.replace(""".pwconv""" ,""".point_wise_conv""" ) if ".dwconv" in k: UpperCamelCase : Optional[Any] = k_new.replace(""".dwconv""" ,""".depth_wise_conv""" ) if ".Proj." in k: UpperCamelCase : List[str] = k_new.replace(""".Proj.""" ,""".proj.""" ) if "patch_embed" in k_new: UpperCamelCase : List[str] = k_new.replace("""patch_embed""" ,"""swiftformer.patch_embed.patch_embedding""" ) if "network" in k_new: UpperCamelCase : List[str] = k_new.split(""".""" ) if ls[2].isdigit(): UpperCamelCase : List[str] = """swiftformer.encoder.network.""" + ls[1] + """.blocks.""" + ls[2] + """.""" + """.""".join(ls[3:] ) else: UpperCamelCase : Dict = k_new.replace("""network""" ,"""swiftformer.encoder.network""" ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def A_ ( snake_case_ : Optional[Any] ,snake_case_ : Any ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : Any = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size UpperCamelCase : Union[str, Any] = 1_0_0_0 UpperCamelCase : Union[str, Any] = """huggingface/label-files""" UpperCamelCase : Any = """imagenet-1k-id2label.json""" UpperCamelCase : Optional[Any] = 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 : Dict = idalabel UpperCamelCase : Any = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": UpperCamelCase : str = [3, 3, 6, 4] UpperCamelCase : str = [4_8, 5_6, 1_1_2, 2_2_0] elif swiftformer_name == "swiftformer_s": UpperCamelCase : Any = [3, 3, 9, 6] UpperCamelCase : Optional[int] = [4_8, 6_4, 1_6_8, 2_2_4] elif swiftformer_name == "swiftformer_l1": UpperCamelCase : str = [4, 3, 1_0, 5] UpperCamelCase : List[str] = [4_8, 9_6, 1_9_2, 3_8_4] elif swiftformer_name == "swiftformer_l3": UpperCamelCase : Any = [4, 4, 1_2, 6] UpperCamelCase : Tuple = [6_4, 1_2_8, 3_2_0, 5_1_2] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith("""https""" ): UpperCamelCase : int = torch.hub.load_state_dict_from_url(snake_case_ ,map_location="""cpu""" ,check_hash=snake_case_ ) else: UpperCamelCase : Tuple = torch.load(snake_case_ ,map_location="""cpu""" ) UpperCamelCase : Optional[int] = checkpoint UpperCamelCase : Dict = create_rename_keys(snake_case_ ) for rename_key_src, rename_key_dest in rename_keys: rename_key(snake_case_ ,snake_case_ ,snake_case_ ) # load HuggingFace model UpperCamelCase : Union[str, Any] = SwiftFormerForImageClassification(snake_case_ ).eval() hf_model.load_state_dict(snake_case_ ) # prepare test inputs UpperCamelCase : Dict = prepare_img() UpperCamelCase : List[Any] = ViTImageProcessor.from_pretrained("""preprocessor_config""" ) UpperCamelCase : Tuple = processor(images=snake_case_ ,return_tensors="""pt""" ) # compare outputs from both models UpperCamelCase : Tuple = get_expected_output(snake_case_ ) UpperCamelCase : List[str] = hf_model(inputs["""pixel_values"""] ).logits assert hf_logits.shape == torch.Size([1, 1_0_0_0] ) assert torch.allclose(hf_logits[0, 0:5] ,snake_case_ ,atol=1e-3 ) Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(f'Saving model {swiftformer_name} to {pytorch_dump_folder_path}' ) hf_model.save_pretrained(snake_case_ ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swiftformer_name''', default='''swiftformer_xs''', choices=['''swiftformer_xs''', '''swiftformer_s''', '''swiftformer_l1''', '''swiftformer_l3'''], type=str, help='''Name of the SwiftFormer model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''./converted_outputs/''', type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--original_ckpt''', default=None, type=str, help='''Path to the original model checkpoint.''') __A : List[Any] = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
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 collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : List[str] = { '''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json''', '''google/bigbird-roberta-large''': '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json''', '''google/bigbird-base-trivia-itc''': '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json''', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class lowerCamelCase ( _UpperCAmelCase ): lowercase : str = 'big_bird' def __init__( self , SCREAMING_SNAKE_CASE_=5_0358 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_="gelu_new" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=66 , SCREAMING_SNAKE_CASE_="block_sparse" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=3 , 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_ , sep_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : List[Any] = vocab_size UpperCamelCase : Optional[int] = max_position_embeddings UpperCamelCase : List[Any] = hidden_size UpperCamelCase : Any = num_hidden_layers UpperCamelCase : List[Any] = num_attention_heads UpperCamelCase : Any = intermediate_size UpperCamelCase : Dict = hidden_act UpperCamelCase : Any = hidden_dropout_prob UpperCamelCase : int = attention_probs_dropout_prob UpperCamelCase : List[str] = initializer_range UpperCamelCase : str = type_vocab_size UpperCamelCase : str = layer_norm_eps UpperCamelCase : Dict = use_cache UpperCamelCase : List[Any] = rescale_embeddings UpperCamelCase : List[Any] = attention_type UpperCamelCase : List[Any] = use_bias UpperCamelCase : List[Any] = block_size UpperCamelCase : Any = num_random_blocks UpperCamelCase : List[str] = classifier_dropout class lowerCamelCase ( _UpperCAmelCase ): @property def a_ ( self ): if self.task == "multiple-choice": UpperCamelCase : Dict = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCamelCase : Dict = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
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 argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def A_ ( snake_case_ : Tuple ): '''simple docstring''' return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] ,unknown_args[1::2] )} def A_ ( ): '''simple docstring''' UpperCamelCase : Optional[int] = ArgumentParser( """HuggingFace Datasets CLI tool""" ,usage="""datasets-cli <command> [<args>]""" ,allow_abbrev=snake_case_ ) UpperCamelCase : Optional[int] = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(snake_case_ ) EnvironmentCommand.register_subcommand(snake_case_ ) TestCommand.register_subcommand(snake_case_ ) RunBeamCommand.register_subcommand(snake_case_ ) DummyDataCommand.register_subcommand(snake_case_ ) # Parse args UpperCamelCase , UpperCamelCase : List[Any] = parser.parse_known_args() if not hasattr(snake_case_ ,"""func""" ): parser.print_help() exit(1 ) UpperCamelCase : Any = parse_unknown_args(snake_case_ ) # Run UpperCamelCase : Any = args.func(snake_case_ ,**snake_case_ ) service.run() if __name__ == "__main__": main()
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 TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import TaTokenizer else: from ...utils.dummy_sentencepiece_objects import TaTokenizer __A : Dict = TaTokenizer if is_tokenizers_available(): from ..ta.tokenization_ta_fast import TaTokenizerFast else: from ...utils.dummy_tokenizers_objects import TaTokenizerFast __A : List[str] = TaTokenizerFast __A : str = {'''configuration_mt5''': ['''MT5Config''', '''MT5OnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : int = [ '''MT5EncoderModel''', '''MT5ForConditionalGeneration''', '''MT5ForQuestionAnswering''', '''MT5Model''', '''MT5PreTrainedModel''', '''MT5Stack''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Dict = ['''TFMT5EncoderModel''', '''TFMT5ForConditionalGeneration''', '''TFMT5Model'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = ['''FlaxMT5EncoderModel''', '''FlaxMT5ForConditionalGeneration''', '''FlaxMT5Model'''] if TYPE_CHECKING: from .configuration_mta import MTaConfig, MTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mta import ( MTaEncoderModel, MTaForConditionalGeneration, MTaForQuestionAnswering, MTaModel, MTaPreTrainedModel, MTaStack, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel else: import sys __A : Any = _LazyModule( __name__, globals()['''__file__'''], _import_structure, extra_objects={'''MT5Tokenizer''': MTaTokenizer, '''MT5TokenizerFast''': MTaTokenizerFast}, module_spec=__spec__, )
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""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __A : Tuple = logging.get_logger(__name__) __A : Any = { '''google/umt5-small''': '''https://huggingface.co/google/umt5-small/resolve/main/config.json''', # See all umt5 models at https://huggingface.co/models?filter=umt5 } class lowerCamelCase ( _UpperCAmelCase ): lowercase : List[Any] = 'umt5' lowercase : Union[str, Any] = ['past_key_values'] def __init__( self , SCREAMING_SNAKE_CASE_=25_0112 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=128 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=1e-6 , SCREAMING_SNAKE_CASE_=1.0 , SCREAMING_SNAKE_CASE_="gated-gelu" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="T5Tokenizer" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , **SCREAMING_SNAKE_CASE_ , ): super().__init__( is_encoder_decoder=SCREAMING_SNAKE_CASE_ , tokenizer_class=SCREAMING_SNAKE_CASE_ , tie_word_embeddings=SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Optional[int] = vocab_size UpperCamelCase : Union[str, Any] = d_model UpperCamelCase : List[Any] = d_kv UpperCamelCase : List[str] = d_ff UpperCamelCase : Optional[int] = num_layers UpperCamelCase : Union[str, Any] = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry UpperCamelCase : Tuple = num_heads UpperCamelCase : Tuple = relative_attention_num_buckets UpperCamelCase : Union[str, Any] = relative_attention_max_distance UpperCamelCase : Tuple = dropout_rate UpperCamelCase : List[str] = layer_norm_epsilon UpperCamelCase : List[Any] = initializer_factor UpperCamelCase : int = feed_forward_proj UpperCamelCase : Any = use_cache UpperCamelCase : Any = self.feed_forward_proj.split("""-""" ) UpperCamelCase : Optional[int] = act_info[-1] UpperCamelCase : Union[str, Any] = act_info[0] == """gated""" if len(SCREAMING_SNAKE_CASE_ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE_ ) > 2: raise ValueError( f'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.' """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """'gated-gelu' or 'relu'""" ) if feed_forward_proj == "gated-gelu": UpperCamelCase : List[str] = """gelu_new""" @property def a_ ( self ): return self.d_model @property def a_ ( self ): return self.num_heads @property def a_ ( self ): return self.num_layers class lowerCamelCase ( _UpperCAmelCase ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def a_ ( self ): UpperCamelCase : Any = { """input_ids""": {0: """batch""", 1: """encoder_sequence"""}, """attention_mask""": {0: """batch""", 1: """encoder_sequence"""}, } if self.use_past: UpperCamelCase : Tuple = """past_encoder_sequence + sequence""" UpperCamelCase : Optional[Any] = {0: """batch"""} UpperCamelCase : str = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: UpperCamelCase : Dict = {0: """batch""", 1: """decoder_sequence"""} UpperCamelCase : int = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE_ , direction="""inputs""" ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def a_ ( self ): return 13 @property def a_ ( self ): return 5e-4
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 os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Any = CpmAntTokenizer lowercase : Optional[Any] = False def a_ ( self ): super().setUp() UpperCamelCase : Union[str, Any] = [ """<d>""", """</d>""", """<s>""", """</s>""", """</_>""", """<unk>""", """<pad>""", """</n>""", """我""", """是""", """C""", """P""", """M""", """A""", """n""", """t""", ] 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] ) ) @tooslow def a_ ( self ): UpperCamelCase : Optional[int] = CpmAntTokenizer.from_pretrained("""openbmb/cpm-ant-10b""" ) UpperCamelCase : Union[str, Any] = """今天天气真好!""" UpperCamelCase : int = ["""今天""", """天气""", """真""", """好""", """!"""] UpperCamelCase : Optional[Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = """今天天气真好!""" UpperCamelCase : List[Any] = [tokenizer.bos_token] + tokens UpperCamelCase : Dict = [6, 9802, 1_4962, 2082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
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 uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch __A : str = logging.get_logger(__name__) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ): if not conversation_id: UpperCamelCase : Optional[int] = uuid.uuida() if past_user_inputs is None: UpperCamelCase : Any = [] if generated_responses is None: UpperCamelCase : List[str] = [] UpperCamelCase : uuid.UUID = conversation_id UpperCamelCase : List[str] = past_user_inputs UpperCamelCase : List[str] = generated_responses UpperCamelCase : Optional[str] = text def __eq__( self , SCREAMING_SNAKE_CASE_ ): if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return False if self.uuid == other.uuid: return True return ( self.new_user_input == other.new_user_input and self.past_user_inputs == other.past_user_inputs and self.generated_responses == other.generated_responses ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False ): if self.new_user_input: if overwrite: logger.warning( f'User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten ' f'with: "{text}".' ) UpperCamelCase : Union[str, Any] = text else: logger.warning( f'User input added while unprocessed input was existing: "{self.new_user_input}" new input ' f'ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input' ) else: UpperCamelCase : str = text def a_ ( self ): if self.new_user_input: self.past_user_inputs.append(self.new_user_input ) UpperCamelCase : Optional[int] = None def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.generated_responses.append(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for user_input, generated_response in zip(self.past_user_inputs , self.generated_responses ): yield True, user_input yield False, generated_response if self.new_user_input: yield True, self.new_user_input def __repr__( self ): UpperCamelCase : List[Any] = f'Conversation id: {self.uuid} \n' for is_user, text in self.iter_texts(): UpperCamelCase : Dict = """user""" if is_user else """bot""" output += f'{name} >> {text} \n' return output @add_end_docstrings( _UpperCAmelCase , R'\n min_length_for_response (`int`, *optional*, defaults to 32):\n The minimum length (in number of tokens) for a response.\n minimum_tokens (`int`, *optional*, defaults to 10):\n The minimum length of tokens to leave for a response.\n ' , ) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if self.tokenizer.pad_token_id is None: UpperCamelCase : str = self.tokenizer.eos_token def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = {} UpperCamelCase : Optional[Any] = {} UpperCamelCase : Tuple = {} if min_length_for_response is not None: UpperCamelCase : Union[str, Any] = min_length_for_response if minimum_tokens is not None: UpperCamelCase : Tuple = minimum_tokens if "max_length" in generate_kwargs: UpperCamelCase : Optional[int] = generate_kwargs["""max_length"""] # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length) if clean_up_tokenization_spaces is not None: UpperCamelCase : Optional[Any] = clean_up_tokenization_spaces if generate_kwargs: forward_params.update(SCREAMING_SNAKE_CASE_ ) return preprocess_params, forward_params, postprocess_params def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = super().__call__(SCREAMING_SNAKE_CASE_ , num_workers=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) == 1: return outputs[0] return outputs def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=32 ): if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): raise ValueError("""ConversationalPipeline, expects Conversation as inputs""" ) if conversation.new_user_input is None: raise ValueError( f'Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. ' """Add user inputs with the conversation's `add_user_input` method""" ) if hasattr(self.tokenizer , """_build_conversation_input_ids""" ): UpperCamelCase : int = self.tokenizer._build_conversation_input_ids(SCREAMING_SNAKE_CASE_ ) else: # If the tokenizer cannot handle conversations, we default to only the old version UpperCamelCase : Dict = self._legacy_parse_and_tokenize(SCREAMING_SNAKE_CASE_ ) if self.framework == "pt": UpperCamelCase : List[str] = torch.LongTensor([input_ids] ) elif self.framework == "tf": UpperCamelCase : Any = tf.constant([input_ids] ) return {"input_ids": input_ids, "conversation": conversation} def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=10 , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = generate_kwargs.get("""max_length""" , self.model.config.max_length ) UpperCamelCase : Optional[Any] = model_inputs["""input_ids"""].shape[1] if max_length - minimum_tokens < n: logger.warning(f'Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})' ) UpperCamelCase : Any = max_length - minimum_tokens UpperCamelCase : Union[str, Any] = model_inputs["""input_ids"""][:, -trim:] if "attention_mask" in model_inputs: UpperCamelCase : str = model_inputs["""attention_mask"""][:, -trim:] UpperCamelCase : Union[str, Any] = model_inputs.pop("""conversation""" ) UpperCamelCase : int = max_length UpperCamelCase : int = self.model.generate(**SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if self.model.config.is_encoder_decoder: UpperCamelCase : List[str] = 1 else: UpperCamelCase : Optional[int] = n return {"output_ids": output_ids[:, start_position:], "conversation": conversation} def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=True ): UpperCamelCase : Dict = model_outputs["""output_ids"""] UpperCamelCase : Union[str, Any] = self.tokenizer.decode( output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = model_outputs["""conversation"""] conversation.mark_processed() conversation.append_response(SCREAMING_SNAKE_CASE_ ) return conversation def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = self.tokenizer.eos_token_id UpperCamelCase : Union[str, Any] = [] for is_user, text in conversation.iter_texts(): if eos_token_id is not None: input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) + [eos_token_id] ) else: input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) ) if len(SCREAMING_SNAKE_CASE_ ) > self.tokenizer.model_max_length: UpperCamelCase : Optional[int] = input_ids[-self.tokenizer.model_max_length :] return input_ids
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 unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=36 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , 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 : List[str] = parent UpperCamelCase : Tuple = batch_size UpperCamelCase : Tuple = seq_length UpperCamelCase : str = is_training UpperCamelCase : List[Any] = use_input_mask UpperCamelCase : Optional[Any] = use_token_type_ids UpperCamelCase : Any = use_labels UpperCamelCase : Tuple = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : str = num_hidden_layers UpperCamelCase : Optional[Any] = num_attention_heads UpperCamelCase : str = intermediate_size UpperCamelCase : Optional[Any] = hidden_act UpperCamelCase : Union[str, Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Tuple = type_vocab_size UpperCamelCase : Any = type_sequence_label_size UpperCamelCase : Optional[Any] = initializer_range UpperCamelCase : Optional[int] = num_labels UpperCamelCase : Optional[Any] = num_choices UpperCamelCase : Any = scope def a_ ( self ): UpperCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Optional[int] = None if self.use_input_mask: UpperCamelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : List[Any] = None if self.use_token_type_ids: UpperCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : List[Any] = None UpperCamelCase : List[str] = None UpperCamelCase : Optional[Any] = None if self.use_labels: UpperCamelCase : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : int = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return MraConfig( 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 ): UpperCamelCase : List[str] = self.get_config() UpperCamelCase : int = 300 return config def a_ ( self ): ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Tuple = self.prepare_config_and_inputs() UpperCamelCase : str = True UpperCamelCase : Any = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) 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 : List[Any] = MraModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ , token_type_ids=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] = True UpperCamelCase : int = MraModel(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_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=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_ ): UpperCamelCase : Union[str, Any] = MraForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : int = 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_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = MraForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = self.num_labels UpperCamelCase : Optional[int] = MraForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : 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_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_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : int = MraForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() 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.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_ ): UpperCamelCase : Optional[Any] = self.num_choices UpperCamelCase : Union[str, Any] = MraForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : List[str] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : 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.num_choices) ) def a_ ( self ): UpperCamelCase : Any = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Any = config_and_inputs UpperCamelCase : Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , unittest.TestCase ): lowercase : Tuple = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) lowercase : List[str] = False lowercase : List[Any] = False lowercase : List[Any] = False lowercase : Optional[int] = False lowercase : List[Any] = () def a_ ( self ): UpperCamelCase : List[str] = MraModelTester(self ) UpperCamelCase : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=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_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[int] = type 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_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Dict = MraModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason="""MRA does not output attentions""" ) def a_ ( self ): return @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : List[str] = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) UpperCamelCase : int = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : str = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) ) @slow def a_ ( self ): UpperCamelCase : Union[str, Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) UpperCamelCase : int = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = 5_0265 UpperCamelCase : Optional[int] = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) ) @slow def a_ ( self ): UpperCamelCase : Optional[Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) UpperCamelCase : List[str] = torch.arange(4096 ).unsqueeze(0 ) with torch.no_grad(): UpperCamelCase : int = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = 5_0265 UpperCamelCase : Any = torch.Size((1, 4096, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
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 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
"""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 dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class lowerCamelCase : lowercase : List[str] lowercase : Optional[str] = None # Automatically constructed lowercase : ClassVar[str] = "dict" lowercase : ClassVar[Any] = None lowercase : str = field(default='Translation' , init=_UpperCAmelCase , repr=_UpperCAmelCase ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def a_ ( self ): from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class lowerCamelCase : lowercase : Optional[List] = None lowercase : Optional[int] = None lowercase : Optional[str] = None # Automatically constructed lowercase : ClassVar[str] = "dict" lowercase : ClassVar[Any] = None lowercase : str = field(default='TranslationVariableLanguages' , init=_UpperCAmelCase , repr=_UpperCAmelCase ) def a_ ( self ): UpperCamelCase : str = sorted(set(self.languages ) ) if self.languages else None UpperCamelCase : Union[str, Any] = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = set(self.languages ) if self.languages and set(SCREAMING_SNAKE_CASE_ ) - lang_set: raise ValueError( f'Some languages in example ({", ".join(sorted(set(SCREAMING_SNAKE_CASE_ ) - lang_set ) )}) are not in valid set ({", ".join(SCREAMING_SNAKE_CASE_ )}).' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. UpperCamelCase : List[Any] = [] for lang, text in translation_dict.items(): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. UpperCamelCase , UpperCamelCase : Any = zip(*sorted(SCREAMING_SNAKE_CASE_ ) ) return {"language": languages, "translation": translations} def a_ ( self ): from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
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""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __A : Any = Path(__file__).resolve().parents[3] / '''src''' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __A : int = {'''base''': '''patrickvonplaten/wav2vec2_tiny_random''', '''robust''': '''patrickvonplaten/wav2vec2_tiny_random_robust'''} __A : List[str] = '''zero2''' __A : Dict = '''zero3''' __A : Any = [ZEROa, ZEROa] def A_ ( snake_case_ : Tuple ,snake_case_ : Dict ,snake_case_ : Optional[Any] ): '''simple docstring''' # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param UpperCamelCase : List[str] = parameterized.to_safe_name("""_""".join(str(snake_case_ ) for x in param.args ) ) return f'{func.__name__}_{param_based_name}' # Cartesian-product of zero stages with models to test __A : Optional[Any] = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class lowerCamelCase ( _UpperCAmelCase ): @parameterized.expand(SCREAMING_SNAKE_CASE_ , name_func=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.run_and_check( stage=SCREAMING_SNAKE_CASE_ , model=SCREAMING_SNAKE_CASE_ , distributed=SCREAMING_SNAKE_CASE_ , fpaa=SCREAMING_SNAKE_CASE_ , ) @require_torch_multi_gpu @parameterized.expand(SCREAMING_SNAKE_CASE_ , name_func=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.run_and_check( stage=SCREAMING_SNAKE_CASE_ , model=SCREAMING_SNAKE_CASE_ , distributed=SCREAMING_SNAKE_CASE_ , fpaa=SCREAMING_SNAKE_CASE_ , ) @parameterized.expand(SCREAMING_SNAKE_CASE_ , name_func=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.run_and_check( stage=SCREAMING_SNAKE_CASE_ , model=SCREAMING_SNAKE_CASE_ , distributed=SCREAMING_SNAKE_CASE_ , fpaa=SCREAMING_SNAKE_CASE_ , ) @require_torch_multi_gpu @parameterized.expand(SCREAMING_SNAKE_CASE_ , name_func=SCREAMING_SNAKE_CASE_ ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.run_and_check( stage=SCREAMING_SNAKE_CASE_ , model=SCREAMING_SNAKE_CASE_ , distributed=SCREAMING_SNAKE_CASE_ , fpaa=SCREAMING_SNAKE_CASE_ , ) def a_ ( self , SCREAMING_SNAKE_CASE_ ): # XXX: run_asr is premature and doesn't save any results # so all we check for now is that the process didn't fail pass def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : int = models[model] UpperCamelCase : Optional[int] = self.run_trainer( stage=SCREAMING_SNAKE_CASE_ , model_name=SCREAMING_SNAKE_CASE_ , eval_steps=SCREAMING_SNAKE_CASE_ , num_train_epochs=1 , distributed=SCREAMING_SNAKE_CASE_ , fpaa=SCREAMING_SNAKE_CASE_ , ) self.do_checks(SCREAMING_SNAKE_CASE_ ) return output_dir def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Optional[int] = self.get_auto_remove_tmp_dir("""./xxx""" , after=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = f'\n --model_name_or_path {model_name}\n --dataset_name hf-internal-testing/librispeech_asr_dummy\n --dataset_config_name clean\n --train_split_name validation\n --validation_split_name validation\n --output_dir {output_dir}\n --num_train_epochs {str(SCREAMING_SNAKE_CASE_ )}\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 2\n --evaluation_strategy steps\n --learning_rate 5e-4\n --warmup_steps 8\n --orthography timit\n --preprocessing_num_workers 1\n --group_by_length\n --freeze_feature_extractor\n --report_to none\n --save_steps 0\n --eval_steps {eval_steps}\n --report_to none\n '.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files UpperCamelCase : int = f'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split() UpperCamelCase : Union[str, Any] = [f'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py'] UpperCamelCase : Dict = self.get_launcher(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=self.get_env() ) return output_dir def a_ ( self , SCREAMING_SNAKE_CASE_=False ): # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup # - it won't be able to handle that # 2. for now testing with just 2 gpus max (since some quality tests may give different # results with mode gpus because we use very little data) UpperCamelCase : Optional[Any] = min(2 , get_gpu_count() ) if distributed else 1 return f'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()
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 random def A_ ( snake_case_ : int ): '''simple docstring''' UpperCamelCase : List[Any] = num - 1 UpperCamelCase : str = 0 while s % 2 == 0: UpperCamelCase : List[str] = s // 2 t += 1 for _ in range(5 ): UpperCamelCase : Optional[Any] = random.randrange(2 ,num - 1 ) UpperCamelCase : List[str] = pow(snake_case_ ,snake_case_ ,snake_case_ ) if v != 1: UpperCamelCase : Tuple = 0 while v != (num - 1): if i == t - 1: return False else: UpperCamelCase : Tuple = i + 1 UpperCamelCase : str = (v**2) % num return True def A_ ( snake_case_ : int ): '''simple docstring''' if num < 2: return False UpperCamelCase : Dict = [ 2, 3, 5, 7, 1_1, 1_3, 1_7, 1_9, 2_3, 2_9, 3_1, 3_7, 4_1, 4_3, 4_7, 5_3, 5_9, 6_1, 6_7, 7_1, 7_3, 7_9, 8_3, 8_9, 9_7, 1_0_1, 1_0_3, 1_0_7, 1_0_9, 1_1_3, 1_2_7, 1_3_1, 1_3_7, 1_3_9, 1_4_9, 1_5_1, 1_5_7, 1_6_3, 1_6_7, 1_7_3, 1_7_9, 1_8_1, 1_9_1, 1_9_3, 1_9_7, 1_9_9, 2_1_1, 2_2_3, 2_2_7, 2_2_9, 2_3_3, 2_3_9, 2_4_1, 2_5_1, 2_5_7, 2_6_3, 2_6_9, 2_7_1, 2_7_7, 2_8_1, 2_8_3, 2_9_3, 3_0_7, 3_1_1, 3_1_3, 3_1_7, 3_3_1, 3_3_7, 3_4_7, 3_4_9, 3_5_3, 3_5_9, 3_6_7, 3_7_3, 3_7_9, 3_8_3, 3_8_9, 3_9_7, 4_0_1, 4_0_9, 4_1_9, 4_2_1, 4_3_1, 4_3_3, 4_3_9, 4_4_3, 4_4_9, 4_5_7, 4_6_1, 4_6_3, 4_6_7, 4_7_9, 4_8_7, 4_9_1, 4_9_9, 5_0_3, 5_0_9, 5_2_1, 5_2_3, 5_4_1, 5_4_7, 5_5_7, 5_6_3, 5_6_9, 5_7_1, 5_7_7, 5_8_7, 5_9_3, 5_9_9, 6_0_1, 6_0_7, 6_1_3, 6_1_7, 6_1_9, 6_3_1, 6_4_1, 6_4_3, 6_4_7, 6_5_3, 6_5_9, 6_6_1, 6_7_3, 6_7_7, 6_8_3, 6_9_1, 7_0_1, 7_0_9, 7_1_9, 7_2_7, 7_3_3, 7_3_9, 7_4_3, 7_5_1, 7_5_7, 7_6_1, 7_6_9, 7_7_3, 7_8_7, 7_9_7, 8_0_9, 8_1_1, 8_2_1, 8_2_3, 8_2_7, 8_2_9, 8_3_9, 8_5_3, 8_5_7, 8_5_9, 8_6_3, 8_7_7, 8_8_1, 8_8_3, 8_8_7, 9_0_7, 9_1_1, 9_1_9, 9_2_9, 9_3_7, 9_4_1, 9_4_7, 9_5_3, 9_6_7, 9_7_1, 9_7_7, 9_8_3, 9_9_1, 9_9_7, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(snake_case_ ) def A_ ( snake_case_ : int = 1_0_2_4 ): '''simple docstring''' while True: UpperCamelCase : Optional[int] = random.randrange(2 ** (keysize - 1) ,2 ** (keysize) ) if is_prime_low_num(snake_case_ ): return num if __name__ == "__main__": __A : Dict = generate_large_prime() print(('''Prime number:''', num)) print(('''is_prime_low_num:''', is_prime_low_num(num)))
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
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. __A : List[str] = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''} @is_pipeline_test class lowerCamelCase ( unittest.TestCase ): lowercase : Dict = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING lowercase : str = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: lowercase : Optional[Any] = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: lowercase : Optional[int] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def a_ ( self ): UpperCamelCase : Tuple = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" ) UpperCamelCase : int = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__a ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) UpperCamelCase : Tuple = text_classifier("""This is great !""" , top_k=2 ) self.assertEqual( nested_simplify(__a ) , [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}] ) UpperCamelCase : Any = text_classifier(["""This is great !""", """This is bad"""] , top_k=2 ) self.assertEqual( nested_simplify(__a ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) UpperCamelCase : List[Any] = text_classifier("""This is great !""" , top_k=1 ) self.assertEqual(nested_simplify(__a ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) # Legacy behavior UpperCamelCase : Optional[Any] = text_classifier("""This is great !""" , return_all_scores=__a ) self.assertEqual(nested_simplify(__a ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) UpperCamelCase : Optional[Any] = text_classifier("""This is great !""" , return_all_scores=__a ) self.assertEqual( nested_simplify(__a ) , [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]] ) UpperCamelCase : str = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=__a ) self.assertEqual( nested_simplify(__a ) , [ [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}], ] , ) UpperCamelCase : Tuple = text_classifier(["""This is great !""", """Something else"""] , return_all_scores=__a ) self.assertEqual( nested_simplify(__a ) , [ {"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_0""", """score""": 0.504}, ] , ) @require_torch def a_ ( self ): import torch UpperCamelCase : Optional[Any] = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""pt""" , device=torch.device("""cpu""" ) , ) UpperCamelCase : Dict = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__a ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @require_tf def a_ ( self ): UpperCamelCase : Dict = pipeline( task="""text-classification""" , model="""hf-internal-testing/tiny-random-distilbert""" , framework="""tf""" ) UpperCamelCase : Dict = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__a ) , [{"""label""": """LABEL_0""", """score""": 0.504}] ) @slow @require_torch def a_ ( self ): UpperCamelCase : int = pipeline("""text-classification""" ) UpperCamelCase : Optional[Any] = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__a ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) UpperCamelCase : List[str] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(__a ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) UpperCamelCase : Optional[Any] = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(__a ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) @slow @require_tf def a_ ( self ): UpperCamelCase : Optional[Any] = pipeline("""text-classification""" , framework="""tf""" ) UpperCamelCase : Dict = text_classifier("""This is great !""" ) self.assertEqual(nested_simplify(__a ) , [{"""label""": """POSITIVE""", """score""": 1.0}] ) UpperCamelCase : List[str] = text_classifier("""This is bad !""" ) self.assertEqual(nested_simplify(__a ) , [{"""label""": """NEGATIVE""", """score""": 1.0}] ) UpperCamelCase : List[Any] = text_classifier("""Birds are a type of animal""" ) self.assertEqual(nested_simplify(__a ) , [{"""label""": """POSITIVE""", """score""": 0.988}] ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = TextClassificationPipeline(model=__a , tokenizer=__a ) return text_classifier, ["HuggingFace is in", "This is another test"] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 UpperCamelCase : Union[str, Any] = 'HuggingFace is in' UpperCamelCase : Tuple = text_classifier(__a ) self.assertEqual(nested_simplify(__a ) , [{"""label""": ANY(__a ), """score""": ANY(__a )}] ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) UpperCamelCase : int = ['HuggingFace is in ', 'Paris is in France'] UpperCamelCase : Dict = text_classifier(__a ) self.assertEqual( nested_simplify(__a ) , [{"""label""": ANY(__a ), """score""": ANY(__a )}, {"""label""": ANY(__a ), """score""": ANY(__a )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format UpperCamelCase : Tuple = text_classifier(__a , top_k=__a ) UpperCamelCase : Optional[int] = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(__a ) , [[{"""label""": ANY(__a ), """score""": ANY(__a )}] * N, [{"""label""": ANY(__a ), """score""": ANY(__a )}] * N] , ) UpperCamelCase : str = {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'} UpperCamelCase : Optional[int] = text_classifier(__a ) self.assertEqual( nested_simplify(__a ) , {"""label""": ANY(__a ), """score""": ANY(__a )} , ) self.assertTrue(outputs["""label"""] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. UpperCamelCase : Optional[Any] = [['HuggingFace is in ', 'Paris is in France']] with self.assertRaises(__a ): text_classifier(__a ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility UpperCamelCase : Tuple = text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]] ) self.assertEqual( nested_simplify(__a ) , [{"""label""": ANY(__a ), """score""": ANY(__a )}] , ) self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values() )
350
"""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
0